From 5c72fba9c3f7922a7bde927d4f5aba5e21a32762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20Szubert?= Date: Wed, 15 Jan 2020 12:04:28 +0100 Subject: [PATCH] Move additional dependencies from private getters to constructor - Magento_Catalog --- .../Product/Attribute/Edit/Tab/Advanced.php | 44 ++-- .../Product/Initialization/Helper.php | 43 ++-- .../Controller/Adminhtml/Product/Validate.php | 96 ++++---- .../Catalog/Cron/RefreshSpecialPrices.php | 69 +++--- .../Magento/Catalog/Model/Product/Option.php | 117 ++++++---- .../Catalog/Model/ResourceModel/Product.php | 163 ++++++------- .../ResourceModel/Product/Collection.php | 214 +++++++++--------- .../ResourceModel/Product/Option/Value.php | 34 +-- .../Product/Initialization/HelperTest.php | 145 ++++++------ .../Unit/Cron/RefreshSpecialPricesTest.php | 198 ++++++++-------- .../Test/Unit/Model/Product/OptionTest.php | 31 ++- .../Unit/Model/ResourceModel/ProductTest.php | 47 ++-- .../Product/Form/Modifier/RelatedTest.php | 15 +- .../Product/Form/Modifier/Categories.php | 60 ++--- .../Product/Form/Modifier/Related.php | 78 +++---- 15 files changed, 656 insertions(+), 698 deletions(-) diff --git a/app/code/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Advanced.php b/app/code/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Advanced.php index 89239a2e3e608..3810042887148 100644 --- a/app/code/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Advanced.php +++ b/app/code/Magento/Catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Advanced.php @@ -6,13 +6,17 @@ namespace Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab; +use Magento\Backend\Block\Template\Context; use Magento\Backend\Block\Widget\Form\Generic; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Config\Model\Config\Source\Yesno; use Magento\Eav\Block\Adminhtml\Attribute\PropertyLocker; use Magento\Eav\Helper\Data; +use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\FormFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Registry; use Magento\Framework\Stdlib\DateTime; /** @@ -47,26 +51,29 @@ class Advanced extends Generic private $propertyLocker; /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Data\FormFactory $formFactory + * @param Context $context + * @param Registry $registry + * @param FormFactory $formFactory * @param Yesno $yesNo * @param Data $eavData * @param array $disableScopeChangeList * @param array $data + * @param PropertyLocker|null $propertyLocker */ public function __construct( - \Magento\Backend\Block\Template\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Data\FormFactory $formFactory, + Context $context, + Registry $registry, + FormFactory $formFactory, Yesno $yesNo, Data $eavData, array $disableScopeChangeList = ['sku'], - array $data = [] + array $data = [], + ?PropertyLocker $propertyLocker = null ) { $this->_yesNo = $yesNo; $this->_eavData = $eavData; $this->disableScopeChangeList = $disableScopeChangeList; + $this->propertyLocker = $propertyLocker ?? ObjectManager::getInstance()->get(PropertyLocker::class); parent::__construct($context, $registry, $formFactory, $data); } @@ -238,14 +245,14 @@ protected function _prepareForm() } $scopes = [ - \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE => __('Store View'), - \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE => __('Website'), - \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL => __('Global'), + ScopedAttributeInterface::SCOPE_STORE => __('Store View'), + ScopedAttributeInterface::SCOPE_WEBSITE => __('Website'), + ScopedAttributeInterface::SCOPE_GLOBAL => __('Global'), ]; if ($attributeObject->getAttributeCode() == 'status' || $attributeObject->getAttributeCode() == 'tax_class_id' ) { - unset($scopes[\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE]); + unset($scopes[ScopedAttributeInterface::SCOPE_STORE]); } $fieldset->addField( @@ -266,7 +273,7 @@ protected function _prepareForm() $form->getElement('is_global')->setDisabled(1); } $this->setForm($form); - $this->getPropertyLocker()->lock($form); + $this->propertyLocker->lock($form); return $this; } @@ -291,19 +298,6 @@ private function getAttributeObject() return $this->_coreRegistry->registry('entity_attribute'); } - /** - * Get property locker - * - * @return PropertyLocker - */ - private function getPropertyLocker() - { - if (null === $this->propertyLocker) { - $this->propertyLocker = ObjectManager::getInstance()->get(PropertyLocker::class); - } - return $this->propertyLocker; - } - /** * Get localized date default value * diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php index 2ae97223d6359..524c879c73333 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Controller\Adminhtml\Product\Initialization; @@ -132,6 +133,7 @@ class Helper * @param FormatInterface|null $localeFormat * @param ProductAuthorization|null $productAuthorization * @param DateTimeFilter|null $dateTimeFilter + * @param LinkResolver|null $linkResolver * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -148,7 +150,8 @@ public function __construct( AttributeFilter $attributeFilter = null, FormatInterface $localeFormat = null, ?ProductAuthorization $productAuthorization = null, - ?DateTimeFilter $dateTimeFilter = null + ?DateTimeFilter $dateTimeFilter = null, + ?LinkResolver $linkResolver = null ) { $this->request = $request; $this->storeManager = $storeManager; @@ -157,15 +160,18 @@ public function __construct( $this->jsHelper = $jsHelper; $this->dateFilter = $dateFilter; - $objectManager = ObjectManager::getInstance(); - $this->customOptionFactory = $customOptionFactory ?: $objectManager->get(CustomOptionFactory::class); - $this->productLinkFactory = $productLinkFactory ?: $objectManager->get(ProductLinkFactory::class); - $this->productRepository = $productRepository ?: $objectManager->get(ProductRepositoryInterface::class); - $this->linkTypeProvider = $linkTypeProvider ?: $objectManager->get(LinkTypeProvider::class); - $this->attributeFilter = $attributeFilter ?: $objectManager->get(AttributeFilter::class); - $this->localeFormat = $localeFormat ?: $objectManager->get(FormatInterface::class); - $this->productAuthorization = $productAuthorization ?? $objectManager->get(ProductAuthorization::class); - $this->dateTimeFilter = $dateTimeFilter ?? $objectManager->get(DateTimeFilter::class); + $this->customOptionFactory = $customOptionFactory ?: + ObjectManager::getInstance()->get(CustomOptionFactory::class); + $this->productLinkFactory = $productLinkFactory ?: ObjectManager::getInstance()->get(ProductLinkFactory::class); + $this->productRepository = $productRepository ?: + ObjectManager::getInstance()->get(ProductRepositoryInterface::class); + $this->linkTypeProvider = $linkTypeProvider ?: ObjectManager::getInstance()->get(LinkTypeProvider::class); + $this->attributeFilter = $attributeFilter ?: ObjectManager::getInstance()->get(AttributeFilter::class); + $this->localeFormat = $localeFormat ?: ObjectManager::getInstance()->get(FormatInterface::class); + $this->productAuthorization = $productAuthorization ?? + ObjectManager::getInstance()->get(ProductAuthorization::class); + $this->dateTimeFilter = $dateTimeFilter ?? ObjectManager::getInstance()->get(DateTimeFilter::class); + $this->linkResolver = $linkResolver ?? ObjectManager::getInstance()->get(LinkResolver::class); } /** @@ -271,7 +277,7 @@ public function initialize(Product $product) */ protected function setProductLinks(Product $product) { - $links = $this->getLinkResolver()->getLinks(); + $links = $this->linkResolver->getLinks(); $product->setProductLinks([]); @@ -396,21 +402,6 @@ private function overwriteValue($optionId, $option, $overwriteOptions) return $option; } - /** - * Get link resolver instance - * - * @return LinkResolver - * @deprecated 101.0.0 - */ - private function getLinkResolver() - { - if (!is_object($this->linkResolver)) { - $this->linkResolver = ObjectManager::getInstance()->get(LinkResolver::class); - } - - return $this->linkResolver; - } - /** * Remove ids of non selected websites from $websiteIds array and return filtered data * diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Validate.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Validate.php index 77c9cfcd40f05..6ae85b03f2e0f 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Validate.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Validate.php @@ -1,16 +1,25 @@ _dateFilter = $dateFilter; $this->productValidator = $productValidator; @@ -81,18 +94,20 @@ public function __construct( $this->resultJsonFactory = $resultJsonFactory; $this->layoutFactory = $layoutFactory; $this->productFactory = $productFactory; + $this->storeManager = $storeManager; + $this->initializationHelper = $initializationHelper; } /** * Validate product * - * @return \Magento\Framework\Controller\Result\Json + * @return Json * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { - $response = new \Magento\Framework\DataObject(); + $response = new DataObject(); $response->setError(false); try { @@ -102,8 +117,8 @@ public function execute() $productData['stock_data']['use_config_manage_stock'] = 0; } $storeId = $this->getRequest()->getParam('store', 0); - $store = $this->getStoreManager()->getStore($storeId); - $this->getStoreManager()->setCurrentStore($store->getCode()); + $store = $this->storeManager->getStore($storeId); + $this->storeManager->setCurrentStore($store->getCode()); /* @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $product->setData('_edit_mode', true); @@ -122,7 +137,7 @@ public function execute() if ($productId) { $product->load($productId); } - $product = $this->getInitializationHelper()->initializeFromData($product, $productData); + $product = $this->initializationHelper->initializeFromData($product, $productData); /* set restrictions for date ranges */ $resource = $product->getResource(); @@ -131,11 +146,11 @@ public function execute() $resource->getAttribute('custom_design_from')->setMaxValue($product->getCustomDesignTo()); $this->productValidator->validate($product, $this->getRequest(), $response); - } catch (\Magento\Eav\Model\Entity\Attribute\Exception $e) { + } catch (Exception $e) { $response->setError(true); $response->setAttribute($e->getAttributeCode()); $response->setMessages([$e->getMessage()]); - } catch (\Magento\Framework\Exception\LocalizedException $e) { + } catch (LocalizedException $e) { $response->setError(true); $response->setMessages([$e->getMessage()]); } catch (\Exception $e) { @@ -148,29 +163,4 @@ public function execute() return $this->resultJsonFactory->create()->setData($response); } - - /** - * @return StoreManagerInterface - * @deprecated 101.0.0 - */ - private function getStoreManager() - { - if (null === $this->storeManager) { - $this->storeManager = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Store\Model\StoreManagerInterface::class); - } - return $this->storeManager; - } - - /** - * @return Initialization\Helper - * @deprecated 101.0.0 - */ - protected function getInitializationHelper() - { - if (null === $this->initializationHelper) { - $this->initializationHelper = ObjectManager::getInstance()->get(Initialization\Helper::class); - } - return $this->initializationHelper; - } } diff --git a/app/code/Magento/Catalog/Cron/RefreshSpecialPrices.php b/app/code/Magento/Catalog/Cron/RefreshSpecialPrices.php index 25668e57e40ed..15c5bfe78c3c7 100644 --- a/app/code/Magento/Catalog/Cron/RefreshSpecialPrices.php +++ b/app/code/Magento/Catalog/Cron/RefreshSpecialPrices.php @@ -3,17 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Cron; use Magento\Catalog\Api\Data\CategoryInterface; -use Magento\Framework\App\ObjectManager; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Eav\Model\Config; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Store\Model\StoreManagerInterface; +/** + * Cron used to refresh special prices + */ class RefreshSpecialPrices { /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManager; @@ -23,27 +33,27 @@ class RefreshSpecialPrices protected $_resource; /** - * @var \Magento\Framework\Stdlib\DateTime + * @var DateTime */ protected $_dateTime; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface + * @var TimezoneInterface */ protected $_localeDate; /** - * @var \Magento\Eav\Model\Config + * @var Config */ protected $_eavConfig; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor + * @var Processor */ protected $_processor; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface + * @var AdapterInterface */ protected $_connection; @@ -53,20 +63,22 @@ class RefreshSpecialPrices private $metadataPool; /** - * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @param StoreManagerInterface $storeManager * @param ResourceConnection $resource - * @param \Magento\Framework\Stdlib\DateTime $dateTime - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Eav\Model\Config $eavConfig - * @param \Magento\Catalog\Model\Indexer\Product\Price\Processor $processor + * @param DateTime $dateTime + * @param TimezoneInterface $localeDate + * @param Config $eavConfig + * @param Processor $processor + * @param MetadataPool $metadataPool */ public function __construct( - \Magento\Store\Model\StoreManagerInterface $storeManager, + StoreManagerInterface $storeManager, ResourceConnection $resource, - \Magento\Framework\Stdlib\DateTime $dateTime, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Eav\Model\Config $eavConfig, - \Magento\Catalog\Model\Indexer\Product\Price\Processor $processor + DateTime $dateTime, + TimezoneInterface $localeDate, + Config $eavConfig, + Processor $processor, + MetadataPool $metadataPool ) { $this->_storeManager = $storeManager; $this->_resource = $resource; @@ -74,12 +86,13 @@ public function __construct( $this->_localeDate = $localeDate; $this->_eavConfig = $eavConfig; $this->_processor = $processor; + $this->metadataPool = $metadataPool; } /** * Retrieve write connection instance * - * @return bool|\Magento\Framework\DB\Adapter\AdapterInterface + * @return bool|AdapterInterface */ protected function _getConnection() { @@ -115,7 +128,7 @@ public function execute() $dateTo = $connection->getDateAddSql( $currDateExpr, -1, - \Magento\Framework\DB\Adapter\AdapterInterface::INTERVAL_DAY + AdapterInterface::INTERVAL_DAY ); $this->_refreshSpecialPriceByStore( $store->getId(), @@ -139,8 +152,8 @@ protected function _refreshSpecialPriceByStore($storeId, $attrCode, $attrConditi $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attrCode); $attributeId = $attribute->getAttributeId(); - $linkField = $this->getMetadataPool()->getMetadata(CategoryInterface::class)->getLinkField(); - $identifierField = $this->getMetadataPool()->getMetadata(CategoryInterface::class)->getIdentifierField(); + $linkField = $this->metadataPool->getMetadata(CategoryInterface::class)->getLinkField(); + $identifierField = $this->metadataPool->getMetadata(CategoryInterface::class)->getIdentifierField(); $connection = $this->_getConnection(); @@ -170,18 +183,4 @@ protected function _refreshSpecialPriceByStore($storeId, $attrCode, $attrConditi $this->_processor->getIndexer()->reindexList($selectData); } } - - /** - * Get MetadataPool instance - * @return MetadataPool - * - * @deprecated 101.0.0 - */ - private function getMetadataPool() - { - if (null === $this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class); - } - return $this->metadataPool; - } } diff --git a/app/code/Magento/Catalog/Model/Product/Option.php b/app/code/Magento/Catalog/Model/Product/Option.php index 128f420e033c2..7206626473cda 100644 --- a/app/code/Magento/Catalog/Model/Product/Option.php +++ b/app/code/Magento/Catalog/Model/Product/Option.php @@ -11,19 +11,28 @@ use Magento\Catalog\Api\Data\ProductCustomOptionValuesInterface; use Magento\Catalog\Api\Data\ProductCustomOptionValuesInterfaceFactory; use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Option\Type\Date; use Magento\Catalog\Model\Product\Option\Type\DefaultType; +use Magento\Catalog\Model\Product\Option\Type\Factory; use Magento\Catalog\Model\Product\Option\Type\File; use Magento\Catalog\Model\Product\Option\Type\Select; use Magento\Catalog\Model\Product\Option\Type\Text; use Magento\Catalog\Model\Product\Option\Value; use Magento\Catalog\Model\ResourceModel\Product\Option\Value\Collection; use Magento\Catalog\Pricing\Price\CalculateCustomOptionCatalogRule; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\Stdlib\StringUtils; /** * Catalog product option model @@ -40,7 +49,7 @@ class Option extends AbstractExtensibleModel implements ProductCustomOptionInterface { /** - * @var Option\Repository + * @var ProductCustomOptionRepositoryInterface * @since 101.0.0 */ protected $optionRepository; @@ -92,12 +101,12 @@ class Option extends AbstractExtensibleModel implements ProductCustomOptionInter /** * Product option factory * - * @var \Magento\Catalog\Model\Product\Option\Type\Factory + * @var Factory */ protected $optionTypeFactory; /** - * @var \Magento\Framework\Stdlib\StringUtils + * @var StringUtils */ protected $string; @@ -132,39 +141,43 @@ class Option extends AbstractExtensibleModel implements ProductCustomOptionInter private $calculateCustomOptionCatalogRule; /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory - * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory + * @param Context $context + * @param Registry $registry + * @param ExtensionAttributesFactory $extensionFactory + * @param AttributeValueFactory $customAttributeFactory * @param Option\Value $productOptionValue * @param Option\Type\Factory $optionFactory - * @param \Magento\Framework\Stdlib\StringUtils $string + * @param StringUtils $string * @param Option\Validator\Pool $validatorPool - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data * @param ProductCustomOptionValuesInterfaceFactory|null $customOptionValuesFactory * @param array $optionGroups * @param array $optionTypesToGroups - * @param CalculateCustomOptionCatalogRule $calculateCustomOptionCatalogRule + * @param CalculateCustomOptionCatalogRule|null $calculateCustomOptionCatalogRule + * @param ProductCustomOptionRepositoryInterface|null $optionRepository + * @param MetadataPool|null $metadataPool * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory, - \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory, + Context $context, + Registry $registry, + ExtensionAttributesFactory $extensionFactory, + AttributeValueFactory $customAttributeFactory, Option\Value $productOptionValue, - \Magento\Catalog\Model\Product\Option\Type\Factory $optionFactory, - \Magento\Framework\Stdlib\StringUtils $string, + Factory $optionFactory, + StringUtils $string, Option\Validator\Pool $validatorPool, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, array $data = [], ProductCustomOptionValuesInterfaceFactory $customOptionValuesFactory = null, array $optionGroups = [], array $optionTypesToGroups = [], - CalculateCustomOptionCatalogRule $calculateCustomOptionCatalogRule = null + CalculateCustomOptionCatalogRule $calculateCustomOptionCatalogRule = null, + ?ProductCustomOptionRepositoryInterface $optionRepository = null, + ?MetadataPool $metadataPool = null ) { $this->productOptionValue = $productOptionValue; $this->optionTypeFactory = $optionFactory; @@ -174,6 +187,9 @@ public function __construct( ObjectManager::getInstance()->get(ProductCustomOptionValuesInterfaceFactory::class); $this->calculateCustomOptionCatalogRule = $calculateCustomOptionCatalogRule ?? ObjectManager::getInstance()->get(CalculateCustomOptionCatalogRule::class); + $this->optionRepository = $optionRepository ?? ObjectManager::getInstance() + ->get(ProductCustomOptionRepositoryInterface::class); + $this->metadataPool = $metadataPool ?? ObjectManager::getInstance()->get(MetadataPool::class); $this->optionGroups = $optionGroups ?: [ self::OPTION_GROUP_DATE => Date::class, self::OPTION_GROUP_FILE => File::class, @@ -242,6 +258,7 @@ public function addValue(Option\Value $value) * Get value by given id * * @param int $valueId + * * @return Option\Value|null */ public function getValueById($valueId) @@ -257,6 +274,7 @@ public function getValueById($valueId) * Whether or not the option type contains sub-values * * @param string $type + * * @return bool * @since 101.1.0 */ @@ -289,6 +307,7 @@ public function getValueInstance() * Add option for save it * * @param array $option + * * @return $this */ public function addOption($option) @@ -311,6 +330,7 @@ public function getOptions() * Set options for array * * @param array $options + * * @return $this */ public function setOptions($options) @@ -344,6 +364,7 @@ public function getProduct() * Set product instance * * @param Product $product + * * @return $this */ public function setProduct(Product $product = null) @@ -356,6 +377,7 @@ public function setProduct(Product $product = null) * Get group name of option by given option type * * @param string $type + * * @return string */ public function getGroupByType($type = null) @@ -371,6 +393,7 @@ public function getGroupByType($type = null) * Group model factory * * @param string $type Option type + * * @return DefaultType * @throws LocalizedException */ @@ -470,6 +493,7 @@ public function afterSave() * Return converted percent to price * * @param bool $flag + * * @return float */ public function getPrice($flag = false) @@ -488,6 +512,7 @@ public function getPrice($flag = false) * Delete prices of option * * @param int $optionId + * * @return $this */ public function deletePrices($optionId) @@ -500,6 +525,7 @@ public function deletePrices($optionId) * Delete titles of option * * @param int $optionId + * * @return $this */ public function deleteTitles($optionId) @@ -512,12 +538,13 @@ public function deleteTitles($optionId) * Get Product Option Collection * * @param Product $product + * * @return \Magento\Catalog\Model\ResourceModel\Product\Option\Collection * @since 101.0.0 */ public function getProductOptions(Product $product) { - return $this->getOptionRepository()->getProductOptions($product, $this->getAddRequiredFilter()); + return $this->optionRepository->getProductOptions($product, $this->getAddRequiredFilter()); } /** @@ -537,6 +564,7 @@ public function getValuesCollection() * * @param array $optionIds * @param int $storeId + * * @return Collection */ public function getOptionValuesByOptionId($optionIds, $storeId) @@ -551,6 +579,7 @@ public function getOptionValuesByOptionId($optionIds, $storeId) * * @param int $oldProductId * @param int $newProductId + * * @return $this */ public function duplicate($oldProductId, $newProductId) @@ -565,6 +594,7 @@ public function duplicate($oldProductId, $newProductId) * * @param int $productId * @param int $storeId + * * @return array */ public function getSearchableData($productId, $storeId) @@ -737,6 +767,7 @@ public function getImageSizeY() * Set product SKU * * @param string $productSku + * * @return $this */ public function setProductSku($productSku) @@ -748,6 +779,7 @@ public function setProductSku($productSku) * Set option id * * @param int $optionId + * * @return $this */ public function setOptionId($optionId) @@ -759,6 +791,7 @@ public function setOptionId($optionId) * Set option title * * @param string $title + * * @return $this */ public function setTitle($title) @@ -770,6 +803,7 @@ public function setTitle($title) * Set option type * * @param string $type + * * @return $this */ public function setType($type) @@ -781,6 +815,7 @@ public function setType($type) * Set sort order * * @param int $sortOrder + * * @return $this */ public function setSortOrder($sortOrder) @@ -803,6 +838,7 @@ public function setIsRequire($isRequired) * Set price * * @param float $price + * * @return $this */ public function setPrice($price) @@ -814,6 +850,7 @@ public function setPrice($price) * Set price type * * @param string $priceType + * * @return $this */ public function setPriceType($priceType) @@ -825,6 +862,7 @@ public function setPriceType($priceType) * Set Sku * * @param string $sku + * * @return $this */ public function setSku($sku) @@ -836,6 +874,7 @@ public function setSku($sku) * Set File Extension * * @param string $fileExtension + * * @return $this */ public function setFileExtension($fileExtension) @@ -847,6 +886,7 @@ public function setFileExtension($fileExtension) * Set Max Characters * * @param int $maxCharacters + * * @return $this */ public function setMaxCharacters($maxCharacters) @@ -858,6 +898,7 @@ public function setMaxCharacters($maxCharacters) * Set Image Size X * * @param int $imageSizeX + * * @return $this */ public function setImageSizeX($imageSizeX) @@ -869,6 +910,7 @@ public function setImageSizeX($imageSizeX) * Set Image Size Y * * @param int $imageSizeY + * * @return $this */ public function setImageSizeY($imageSizeY) @@ -880,6 +922,7 @@ public function setImageSizeY($imageSizeY) * Set value * * @param ProductCustomOptionValuesInterface[] $values + * * @return $this */ public function setValues(array $values = null) @@ -918,6 +961,7 @@ public function getRegularPrice() * Get Product Option Collection * * @param Product $product + * * @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection */ public function getProductOptionCollection(Product $product) @@ -925,7 +969,7 @@ public function getProductOptionCollection(Product $product) $collection = clone $this->getCollection(); $collection->addFieldToFilter( 'product_id', - $product->getData($this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField()) + $product->getData($this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()) )->addTitleToResult( $product->getStoreId() )->addPriceToResult( @@ -950,6 +994,7 @@ public function getProductOptionCollection(Product $product) * @inheritdoc * * @param \Magento\Catalog\Api\Data\ProductCustomOptionExtensionInterface $extensionAttributes + * * @return $this */ public function setExtensionAttributes( @@ -958,34 +1003,6 @@ public function setExtensionAttributes( return $this->_setExtensionAttributes($extensionAttributes); } - /** - * Get option repository - * - * @return Option\Repository - */ - private function getOptionRepository() - { - if (null === $this->optionRepository) { - $this->optionRepository = ObjectManager::getInstance() - ->get(\Magento\Catalog\Model\Product\Option\Repository::class); - } - return $this->optionRepository; - } - - /** - * Get metadata pool - * - * @return \Magento\Framework\EntityManager\MetadataPool - */ - private function getMetadataPool() - { - if (null === $this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance() - ->get(\Magento\Framework\EntityManager\MetadataPool::class); - } - return $this->metadataPool; - } - //@codeCoverageIgnoreEnd /** diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product.php b/app/code/Magento/Catalog/Model/ResourceModel/Product.php index c5587d3b25665..925245c76aba3 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product.php @@ -3,17 +3,29 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Model\ResourceModel; +use Magento\Catalog\Model\Factory; +use Magento\Catalog\Model\Product\Attribute\DefaultAttributes; +use Magento\Catalog\Model\Product\Visibility; use Magento\Catalog\Model\ResourceModel\Product\Website\Link as ProductWebsiteLink; use Magento\Eav\Api\AttributeManagementInterface; +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\Entity\Attribute\Source\Table; +use Magento\Eav\Model\Entity\Context; +use Magento\Eav\Model\Entity\TypeFactory; use Magento\Framework\App\ObjectManager; use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer; use Magento\Catalog\Model\Product as ProductEntity; use Magento\Eav\Model\Entity\Attribute\UniqueValidationInterface; use Magento\Framework\DataObject; +use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\EntityManager; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Model\AbstractModel; +use Magento\Store\Model\StoreManagerInterface; /** * Product entity resource model @@ -54,17 +66,17 @@ class Product extends AbstractResource protected $_categoryCollectionFactory; /** - * @var \Magento\Framework\Event\ManagerInterface + * @var ManagerInterface */ protected $eventManager; /** - * @var \Magento\Eav\Model\Entity\Attribute\SetFactory + * @var SetFactory */ protected $setFactory; /** - * @var \Magento\Eav\Model\Entity\TypeFactory + * @var TypeFactory */ protected $typeFactory; @@ -75,10 +87,15 @@ class Product extends AbstractResource protected $entityManager; /** - * @var \Magento\Catalog\Model\Product\Attribute\DefaultAttributes + * @var DefaultAttributes */ protected $defaultAttributes; + /** + * @var ProductWebsiteLink + */ + private $productWebsiteLink; + /** * @var array * @since 101.0.0 @@ -101,35 +118,41 @@ class Product extends AbstractResource private $eavAttributeManagement; /** - * @param \Magento\Eav\Model\Entity\Context $context - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Catalog\Model\Factory $modelFactory + * @param Context $context + * @param StoreManagerInterface $storeManager + * @param Factory $modelFactory * @param Category\CollectionFactory $categoryCollectionFactory * @param Category $catalogCategory - * @param \Magento\Framework\Event\ManagerInterface $eventManager - * @param \Magento\Eav\Model\Entity\Attribute\SetFactory $setFactory - * @param \Magento\Eav\Model\Entity\TypeFactory $typeFactory - * @param \Magento\Catalog\Model\Product\Attribute\DefaultAttributes $defaultAttributes + * @param ManagerInterface $eventManager + * @param SetFactory $setFactory + * @param TypeFactory $typeFactory + * @param DefaultAttributes $defaultAttributes * @param array $data * @param TableMaintainer|null $tableMaintainer * @param UniqueValidationInterface|null $uniqueValidator * @param AttributeManagementInterface|null $eavAttributeManagement + * @param EntityManager|null $entityManager + * @param ProductWebsiteLink|null $productWebsiteLink + * @param Product\CategoryLink|null $productCategoryLink * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Eav\Model\Entity\Context $context, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Catalog\Model\Factory $modelFactory, + Context $context, + StoreManagerInterface $storeManager, + Factory $modelFactory, Category\CollectionFactory $categoryCollectionFactory, Category $catalogCategory, - \Magento\Framework\Event\ManagerInterface $eventManager, - \Magento\Eav\Model\Entity\Attribute\SetFactory $setFactory, - \Magento\Eav\Model\Entity\TypeFactory $typeFactory, - \Magento\Catalog\Model\Product\Attribute\DefaultAttributes $defaultAttributes, + ManagerInterface $eventManager, + SetFactory $setFactory, + TypeFactory $typeFactory, + DefaultAttributes $defaultAttributes, $data = [], TableMaintainer $tableMaintainer = null, UniqueValidationInterface $uniqueValidator = null, - AttributeManagementInterface $eavAttributeManagement = null + AttributeManagementInterface $eavAttributeManagement = null, + ?EntityManager $entityManager = null, + ?ProductWebsiteLink $productWebsiteLink = null, + ?Product\CategoryLink $productCategoryLink = null ) { $this->_categoryCollectionFactory = $categoryCollectionFactory; $this->_catalogCategory = $catalogCategory; @@ -148,6 +171,10 @@ public function __construct( $this->tableMaintainer = $tableMaintainer ?: ObjectManager::getInstance()->get(TableMaintainer::class); $this->eavAttributeManagement = $eavAttributeManagement ?? ObjectManager::getInstance()->get(AttributeManagementInterface::class); + $this->entityManager = $entityManager ?? ObjectManager::getInstance()->get(EntityManager::class); + $this->productWebsiteLink = $productWebsiteLink ?? ObjectManager::getInstance()->get(ProductWebsiteLink::class); + $this->productCategoryLink = $productCategoryLink ?? ObjectManager::getInstance() + ->get(Product\CategoryLink::class); } /** @@ -159,7 +186,7 @@ public function __construct( public function getEntityType() { if (empty($this->_type)) { - $this->setType(\Magento\Catalog\Model\Product::ENTITY); + $this->setType(ProductEntity::ENTITY); } return parent::getEntityType(); } @@ -204,19 +231,19 @@ protected function _getDefaultAttributes() /** * Retrieve product website identifiers * - * @deprecated 101.1.0 - * @param \Magento\Catalog\Model\Product|int $product + * @param ProductEntity|int $product * @return array + * @deprecated 101.1.0 */ public function getWebsiteIds($product) { - if ($product instanceof \Magento\Catalog\Model\Product) { + if ($product instanceof ProductEntity) { $productId = $product->getEntityId(); } else { $productId = $product; } - return $this->getProductWebsiteLink()->getWebsiteIdsByProductId($productId); + return $this->productWebsiteLink->getWebsiteIdsByProductId($productId); } /** @@ -249,12 +276,12 @@ public function getWebsiteIdsByProductIds($productIds) /** * Retrieve product category identifiers * - * @param \Magento\Catalog\Model\Product $product + * @param ProductEntity $product * @return array */ public function getCategoryIds($product) { - $result = $this->getProductCategoryLink()->getCategoryLinks($product); + $result = $this->productCategoryLink->getCategoryLinks($product); return array_column($result, 'category_id'); } @@ -340,6 +367,7 @@ private function removeNotInSetAttributeValues(DataObject $product): DataObject * * @param DataObject $product * @param array $attributeCodes + * * @return void */ private function deleteSelectedEntityAttributeRows(DataObject $product, array $attributeCodes): void @@ -368,7 +396,7 @@ private function deleteSelectedEntityAttributeRows(DataObject $product, array $a */ public function delete($object) { - $this->getEntityManager()->delete($object); + $this->entityManager->delete($object); $this->eventManager->dispatch( 'catalog_product_delete_after_done', ['product' => $object] @@ -379,9 +407,10 @@ public function delete($object) /** * Save product website relations * - * @deprecated 101.1.0 - * @param \Magento\Catalog\Model\Product $product + * @param ProductEntity $product + * * @return $this + * @deprecated 101.1.0 */ protected function _saveWebsiteIds($product) { @@ -392,7 +421,7 @@ protected function _saveWebsiteIds($product) } $websiteIds = $product->getWebsiteIds(); $product->setIsChangedWebsites(false); - $changed = $this->getProductWebsiteLink()->saveWebsiteIds($product, $websiteIds); + $changed = $this->productWebsiteLink->saveWebsiteIds($product, $websiteIds); if ($changed) { $product->setIsChangedWebsites(true); @@ -406,6 +435,7 @@ protected function _saveWebsiteIds($product) * Save product category relations * * @param DataObject $object + * * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @deprecated 101.1.0 @@ -418,7 +448,8 @@ protected function _saveCategories(DataObject $object) /** * Get collection of product categories * - * @param \Magento\Catalog\Model\Product $product + * @param ProductEntity $product + * * @return Category\Collection */ public function getCategoryCollection($product) @@ -441,7 +472,8 @@ public function getCategoryCollection($product) /** * Retrieve category ids where product is available * - * @param \Magento\Catalog\Model\Product $object + * @param ProductEntity $object + * * @return array */ public function getAvailableInCategories($object) @@ -458,7 +490,7 @@ public function getAvailableInCategories($object) } $unionSelect = new \Magento\Framework\DB\Sql\UnionExpression( $unionTables, - \Magento\Framework\DB\Select::SQL_UNION_ALL + Select::SQL_UNION_ALL ); $this->availableCategoryIdsCache[$entityId] = array_unique($this->getConnection()->fetchCol($unionSelect)); } @@ -470,7 +502,8 @@ public function getAvailableInCategories($object) * * @param int $entityId * @param string $tableName - * @return \Magento\Framework\DB\Select + * + * @return Select */ private function getAvailableInCategoriesSelect($entityId, $tableName) { @@ -482,7 +515,7 @@ private function getAvailableInCategoriesSelect($entityId, $tableName) $entityId )->where( 'visibility != ?', - \Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE + Visibility::VISIBILITY_NOT_VISIBLE ); } @@ -493,19 +526,20 @@ private function getAvailableInCategoriesSelect($entityId, $tableName) */ public function getDefaultAttributeSourceModel() { - return \Magento\Eav\Model\Entity\Attribute\Source\Table::class; + return Table::class; } /** * Check availability display product in category * - * @param \Magento\Catalog\Model\Product|int $product + * @param ProductEntity|int $product * @param int $categoryId + * * @return string */ public function canBeShowInCategory($product, $categoryId) { - if ($product instanceof \Magento\Catalog\Model\Product) { + if ($product instanceof ProductEntity) { $productId = $product->getEntityId(); $storeId = $product->getStoreId(); } else { @@ -532,6 +566,7 @@ public function canBeShowInCategory($product, $categoryId) * * @param int $oldId * @param int $newId + * * @return $this */ public function duplicate($oldId, $newId) @@ -585,6 +620,7 @@ public function duplicate($oldId, $newId) * Get SKU through product identifiers * * @param array $productIds + * * @return array */ public function getProductsSku(array $productIds) @@ -603,6 +639,7 @@ public function getProductsSku(array $productIds) * Get product ids by their sku * * @param array $productSkuList + * * @return array */ public function getProductsIdsBySkus(array $productSkuList) @@ -629,6 +666,7 @@ public function getProductsIdsBySkus(array $productSkuList) * * @param string $sku * @param array $productSkuList + * * @return string */ private function getResultKey(string $sku, array $productSkuList): string @@ -644,6 +682,7 @@ private function getResultKey(string $sku, array $productSkuList): string * Retrieve product entities info * * @param array|string|null $columns + * * @return array */ public function getProductEntitiesInfo($columns = null) @@ -683,7 +722,7 @@ public function countAll() public function validate($object) { //validate attribute set entity type - $entityType = $this->typeFactory->create()->loadByCode(\Magento\Catalog\Model\Product::ENTITY); + $entityType = $this->typeFactory->create()->loadByCode(ProductEntity::ENTITY); $attributeSet = $this->setFactory->create()->load($object->getAttributeSetId()); if ($attributeSet->getEntityTypeId() != $entityType->getId()) { return ['attribute_set' => 'Invalid attribute set entity type']; @@ -698,6 +737,7 @@ public function validate($object) * @param AbstractModel $object * @param integer $entityId * @param array|null $attributes + * * @return $this * @since 101.0.0 */ @@ -713,7 +753,7 @@ public function load($object, $entityId, $attributes = []) } $this->loadAttributesForObject($attributes, $object); - $this->getEntityManager()->load($object, $entityId); + $this->entityManager->load($object, $entityId); return $this; } @@ -749,56 +789,17 @@ protected function evaluateDelete($object, $id, $connection) * Save entity's attributes into the object's resource * * @param AbstractModel $object + * * @return $this * @throws \Exception * @since 101.0.0 */ public function save(AbstractModel $object) { - $this->getEntityManager()->save($object); + $this->entityManager->save($object); return $this; } - /** - * Retrieve entity manager. - * - * @return EntityManager - */ - private function getEntityManager() - { - if (null === $this->entityManager) { - $this->entityManager = ObjectManager::getInstance() - ->get(EntityManager::class); - } - return $this->entityManager; - } - - /** - * Retrieve ProductWebsiteLink instance. - * - * @deprecated 101.1.0 - * @return ProductWebsiteLink - */ - private function getProductWebsiteLink() - { - return ObjectManager::getInstance()->get(ProductWebsiteLink::class); - } - - /** - * Retrieve CategoryLink instance. - * - * @deprecated 101.1.0 - * @return Product\CategoryLink - */ - private function getProductCategoryLink() - { - if (null === $this->productCategoryLink) { - $this->productCategoryLink = ObjectManager::getInstance() - ->get(Product\CategoryLink::class); - } - return $this->productCategoryLink; - } - /** * Extends parent method to be appropriate for product. * diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php index afbe279045a38..f0e59e6e730fe 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php @@ -9,21 +9,46 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer; +use Magento\Catalog\Model\Indexer\Product\Flat\State; use Magento\Catalog\Model\Indexer\Product\Price\PriceTableResolver; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Attribute\Source\Status as ProductStatus; use Magento\Catalog\Model\Product\Gallery\ReadHandler as GalleryReadHandler; +use Magento\Catalog\Model\Product\OptionFactory; +use Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection; +use Magento\Catalog\Model\ResourceModel\Helper; +use Magento\Catalog\Model\ResourceModel\Product as ProductResource; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use Magento\Catalog\Model\ResourceModel\Url; use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator; use Magento\CatalogUrlRewrite\Model\Storage\DbStorage; use Magento\Customer\Api\GroupManagementInterface; use Magento\Customer\Model\Indexer\CustomerGroupDimensionProvider; +use Magento\Customer\Model\Session; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend; +use Magento\Eav\Model\EntityFactory as EavEntityFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactory; +use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Event\ManagerInterface; use Magento\Framework\Indexer\DimensionFactory; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; +use Magento\Framework\Module\Manager; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\Validator\UniversalFactory; use Magento\Store\Model\Indexer\WebsiteDimensionProvider; use Magento\Store\Model\Store; use Magento\Catalog\Model\ResourceModel\Category; +use Magento\Store\Model\StoreManagerInterface; +use Psr\Log\LoggerInterface; /** * Product collection @@ -37,7 +62,7 @@ * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) * @since 100.0.2 */ -class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection +class Collection extends AbstractCollection { /** * Alias for index table @@ -111,7 +136,7 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac protected $_addTaxPercents = false; /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation + * @var ProductLimitation */ protected $_productLimitationFilters; @@ -186,64 +211,64 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac /** * Catalog product flat * - * @var \Magento\Catalog\Model\Indexer\Product\Flat\State + * @var State */ protected $_catalogProductFlatState = null; /** * Catalog data * - * @var \Magento\Framework\Module\Manager + * @var Manager */ protected $moduleManager = null; /** * Core store config * - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var ScopeConfigInterface */ protected $_scopeConfig; /** * Customer session * - * @var \Magento\Customer\Model\Session + * @var Session */ protected $_customerSession; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface + * @var TimezoneInterface */ protected $_localeDate; /** * Catalog url * - * @var \Magento\Catalog\Model\ResourceModel\Url + * @var Url */ protected $_catalogUrl; /** * Product option factory * - * @var \Magento\Catalog\Model\Product\OptionFactory + * @var OptionFactory */ protected $_productOptionFactory; /** * Catalog resource helper * - * @var \Magento\Catalog\Model\ResourceModel\Helper + * @var Helper */ protected $_resourceHelper; /** - * @var \Magento\Framework\Stdlib\DateTime + * @var DateTime */ protected $dateTime; /** - * @var \Magento\Customer\Api\GroupManagementInterface + * @var GroupManagementInterface */ protected $_groupManagement; @@ -275,7 +300,7 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac private $linkField; /** - * @var \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend + * @var AbstractBackend */ private $backend; @@ -312,62 +337,68 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac /** * Collection constructor * - * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy - * @param \Magento\Framework\Event\ManagerInterface $eventManager - * @param \Magento\Eav\Model\Config $eavConfig - * @param \Magento\Framework\App\ResourceConnection $resource - * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory - * @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper - * @param \Magento\Framework\Validator\UniversalFactory $universalFactory - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory - * @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\Stdlib\DateTime $dateTime + * @param EntityFactory $entityFactory + * @param LoggerInterface $logger + * @param FetchStrategyInterface $fetchStrategy + * @param ManagerInterface $eventManager + * @param Config $eavConfig + * @param ResourceConnection $resource + * @param EavEntityFactory $eavEntityFactory + * @param Helper $resourceHelper + * @param UniversalFactory $universalFactory + * @param StoreManagerInterface $storeManager + * @param Manager $moduleManager + * @param State $catalogProductFlatState + * @param ScopeConfigInterface $scopeConfig + * @param OptionFactory $productOptionFactory + * @param Url $catalogUrl + * @param TimezoneInterface $localeDate + * @param Session $customerSession + * @param DateTime $dateTime * @param GroupManagementInterface $groupManagement - * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection + * @param AdapterInterface|null $connection * @param ProductLimitationFactory|null $productLimitationFactory * @param MetadataPool|null $metadataPool * @param TableMaintainer|null $tableMaintainer * @param PriceTableResolver|null $priceTableResolver * @param DimensionFactory|null $dimensionFactory * @param Category|null $categoryResourceModel + * @param DbStorage|null $urlFinder + * @param GalleryReadHandler|null $productGalleryReadHandler + * @param Gallery|null $mediaGalleryResource * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Data\Collection\EntityFactory $entityFactory, - \Psr\Log\LoggerInterface $logger, - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, - \Magento\Framework\Event\ManagerInterface $eventManager, - \Magento\Eav\Model\Config $eavConfig, - \Magento\Framework\App\ResourceConnection $resource, - \Magento\Eav\Model\EntityFactory $eavEntityFactory, - \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper, - \Magento\Framework\Validator\UniversalFactory $universalFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory, - \Magento\Catalog\Model\ResourceModel\Url $catalogUrl, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\Stdlib\DateTime $dateTime, + EntityFactory $entityFactory, + LoggerInterface $logger, + FetchStrategyInterface $fetchStrategy, + ManagerInterface $eventManager, + Config $eavConfig, + ResourceConnection $resource, + EavEntityFactory $eavEntityFactory, + Helper $resourceHelper, + UniversalFactory $universalFactory, + StoreManagerInterface $storeManager, + Manager $moduleManager, + State $catalogProductFlatState, + ScopeConfigInterface $scopeConfig, + OptionFactory $productOptionFactory, + Url $catalogUrl, + TimezoneInterface $localeDate, + Session $customerSession, + DateTime $dateTime, GroupManagementInterface $groupManagement, - \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, + AdapterInterface $connection = null, ProductLimitationFactory $productLimitationFactory = null, MetadataPool $metadataPool = null, TableMaintainer $tableMaintainer = null, PriceTableResolver $priceTableResolver = null, DimensionFactory $dimensionFactory = null, - Category $categoryResourceModel = null + Category $categoryResourceModel = null, + ?DbStorage $urlFinder = null, + ?GalleryReadHandler $productGalleryReadHandler = null, + ?Gallery $mediaGalleryResource = null ) { $this->moduleManager = $moduleManager; $this->_catalogProductFlatState = $catalogProductFlatState; @@ -379,9 +410,8 @@ public function __construct( $this->_resourceHelper = $resourceHelper; $this->dateTime = $dateTime; $this->_groupManagement = $groupManagement; - $productLimitationFactory = $productLimitationFactory ?: ObjectManager::getInstance()->get( - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory::class - ); + $productLimitationFactory = $productLimitationFactory ?: + ObjectManager::getInstance()->get(ProductLimitationFactory::class); $this->_productLimitationFilters = $productLimitationFactory->create(); $this->metadataPool = $metadataPool ?: ObjectManager::getInstance()->get(MetadataPool::class); parent::__construct( @@ -399,23 +429,12 @@ public function __construct( ); $this->tableMaintainer = $tableMaintainer ?: ObjectManager::getInstance()->get(TableMaintainer::class); $this->priceTableResolver = $priceTableResolver ?: ObjectManager::getInstance()->get(PriceTableResolver::class); - $this->dimensionFactory = $dimensionFactory - ?: ObjectManager::getInstance()->get(DimensionFactory::class); - $this->categoryResourceModel = $categoryResourceModel ?: ObjectManager::getInstance() - ->get(Category::class); - } - - /** - * Retrieve urlFinder - * - * @return GalleryReadHandler - */ - private function getUrlFinder() - { - if ($this->urlFinder === null) { - $this->urlFinder = ObjectManager::getInstance()->get(DbStorage::class); - } - return $this->urlFinder; + $this->dimensionFactory = $dimensionFactory ?: ObjectManager::getInstance()->get(DimensionFactory::class); + $this->categoryResourceModel = $categoryResourceModel ?: ObjectManager::getInstance()->get(Category::class); + $this->urlFinder = $urlFinder ?? ObjectManager::getInstance()->get(DbStorage::class); + $this->productGalleryReadHandler = $productGalleryReadHandler ?? ObjectManager::getInstance() + ->get(GalleryReadHandler::class); + $this->mediaGalleryResource = $mediaGalleryResource ?? ObjectManager::getInstance()->get(Gallery::class); } /** @@ -533,11 +552,11 @@ protected function _construct() { if ($this->isEnabledFlat()) { $this->_init( - \Magento\Catalog\Model\Product::class, - \Magento\Catalog\Model\ResourceModel\Product\Flat::class + Product::class, + Flat::class ); } else { - $this->_init(\Magento\Catalog\Model\Product::class, \Magento\Catalog\Model\ResourceModel\Product::class); + $this->_init(Product::class, ProductResource::class); } $this->_initTables(); } @@ -552,7 +571,7 @@ protected function _construct() protected function _init($model, $entityModel) { if ($this->isEnabledFlat()) { - $entityModel = \Magento\Catalog\Model\ResourceModel\Product\Flat::class; + $entityModel = Flat::class; } return parent::_init($model, $entityModel); } @@ -606,7 +625,7 @@ public function getNewEmptyItem() */ public function setEntity($entity) { - if ($this->isEnabledFlat() && $entity instanceof \Magento\Framework\Model\ResourceModel\Db\AbstractDb) { + if ($this->isEnabledFlat() && $entity instanceof AbstractDb) { $this->_entity = $entity; return $this; } @@ -735,7 +754,7 @@ protected function _afterLoad() protected function prepareStoreId() { if ($this->getStoreId() !== null) { - /** @var $item \Magento\Catalog\Model\Product */ + /** @var $item Product */ foreach ($this->_items as $item) { $item->setStoreId($this->getStoreId()); } @@ -752,7 +771,7 @@ protected function prepareStoreId() protected function _prepareUrlDataObject() { $objects = []; - /** @var $item \Magento\Catalog\Model\Product */ + /** @var $item Product */ foreach ($this->_items as $item) { if ($this->getFlag('do_not_use_category_id')) { $item->setDoNotUseCategoryId(true); @@ -1458,7 +1477,7 @@ protected function _addUrlRewrite() $filter['metadata']['category_id'] = $this->_urlRewriteCategory; } - $rewrites = $this->getUrlFinder()->findAllByData($filter); + $rewrites = $this->urlFinder->findAllByData($filter); foreach ($rewrites as $rewrite) { if ($item = $this->getItemById($rewrite->getEntityId())) { $item->setData('request_path', $rewrite->getRequestPath()); @@ -2293,7 +2312,7 @@ private function getLinkField() /** * Retrieve backend model and cache it. * - * @return \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend + * @return AbstractBackend */ private function getBackend() { @@ -2350,7 +2369,7 @@ public function addMediaGalleryData() $items = $this->getItems(); $linkField = $this->getProductEntityMetadata()->getLinkField(); - $select = $this->getMediaGalleryResource() + $select = $this->mediaGalleryResource ->createBatchBaseSelect( $this->getStoreId(), $this->getAttribute('media_gallery')->getAttributeId() @@ -2372,7 +2391,7 @@ function ($item) use ($linkField) { } foreach ($items as $item) { - $this->getGalleryReadHandler() + $this->productGalleryReadHandler ->addMediaDataToProduct( $item, $mediaGalleries[$item->getOrigData($linkField)] ?? [] @@ -2394,35 +2413,6 @@ public function getProductEntityMetadata() return $this->metadataPool->getMetadata(ProductInterface::class); } - /** - * Retrieve GalleryReadHandler - * - * @return GalleryReadHandler - * @deprecated 101.0.1 - */ - private function getGalleryReadHandler() - { - if ($this->productGalleryReadHandler === null) { - $this->productGalleryReadHandler = ObjectManager::getInstance()->get(GalleryReadHandler::class); - } - return $this->productGalleryReadHandler; - } - - /** - * Retrieve Media gallery resource. - * - * @deprecated 101.0.1 - * - * @return \Magento\Catalog\Model\ResourceModel\Product\Gallery - */ - private function getMediaGalleryResource() - { - if (null === $this->mediaGalleryResource) { - $this->mediaGalleryResource = ObjectManager::getInstance()->get(Gallery::class); - } - return $this->mediaGalleryResource; - } - /** * Clear collection * diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Value.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Value.php index 494dbac02d792..85c1e4dbfa893 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Value.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Value.php @@ -3,13 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Model\ResourceModel\Product\Option; +use Magento\Catalog\Helper\Data; use Magento\Catalog\Model\Product\Option\Value as OptionValue; use Magento\Directory\Model\Currency; use Magento\Directory\Model\CurrencyFactory; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Locale\FormatInterface; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; @@ -17,7 +19,6 @@ use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; -use Magento\Catalog\Helper\Data; /** * Catalog product custom option resource model @@ -64,22 +65,24 @@ class Value extends AbstractDb * @param CurrencyFactory $currencyFactory * @param StoreManagerInterface $storeManager * @param ScopeConfigInterface $config - * @param string $connectionName + * @param FormatInterface $localeFormat * @param Data $dataHelper + * @param string $connectionName */ public function __construct( Context $context, CurrencyFactory $currencyFactory, StoreManagerInterface $storeManager, ScopeConfigInterface $config, - $connectionName = null, - Data $dataHelper = null + FormatInterface $localeFormat, + Data $dataHelper, + $connectionName = null ) { $this->_currencyFactory = $currencyFactory; $this->_storeManager = $storeManager; $this->_config = $config; - $this->dataHelper = $dataHelper ?: ObjectManager::getInstance() - ->get(Data::class); + $this->localeFormat = $localeFormat; + $this->dataHelper = $dataHelper; parent::__construct($context, $connectionName); } @@ -121,7 +124,7 @@ protected function _saveValuePrices(AbstractModel $object) { $objectPrice = $object->getPrice(); $priceTable = $this->getTable('catalog_product_option_type_price'); - $formattedPrice = $this->getLocaleFormatter()->getNumber($objectPrice); + $formattedPrice = $this->localeFormat->getNumber($objectPrice); $price = (double)sprintf('%F', $formattedPrice); $priceType = $object->getPriceType(); @@ -450,19 +453,4 @@ public function duplicate(OptionValue $object, $oldOptionId, $newOptionId) return $object; } - - /** - * Get FormatInterface to convert price from string to number format - * - * @return FormatInterface - * @deprecated 101.0.8 - */ - private function getLocaleFormatter() - { - if ($this->localeFormat === null) { - $this->localeFormat = ObjectManager::getInstance() - ->get(FormatInterface::class); - } - return $this->localeFormat; - } } diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php index 2aea34244437d..2af7db721d2fc 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Initialization/HelperTest.php @@ -3,110 +3,119 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Catalog\Test\Unit\Controller\Adminhtml\Product\Initialization; +use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; +use Magento\Catalog\Api\Data\ProductLinkTypeInterface; use Magento\Catalog\Api\ProductRepositoryInterface as ProductRepository; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper; +use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter; use Magento\Catalog\Controller\Adminhtml\Product\Initialization\StockDataFilter; use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Filter\DateTime; +use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; +use Magento\Catalog\Model\Product\Link\Resolver; +use Magento\Catalog\Model\Product\LinkTypeProvider; use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\ProductLink\Link as ProductLink; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Eav\Model\Entity\Attribute\Backend\DefaultBackend; use Magento\Framework\App\RequestInterface; use Magento\Framework\Locale\Format; use Magento\Framework\Locale\FormatInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Store\Api\Data\WebsiteInterface; use Magento\Store\Model\StoreManagerInterface; -use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory; -use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; -use Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks; -use Magento\Catalog\Model\Product\LinkTypeProvider; -use Magento\Catalog\Api\Data\ProductLinkTypeInterface; -use Magento\Catalog\Model\ProductLink\Link as ProductLink; -use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * Test class for \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.ExcessivePublicCount) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.TooManyFields) */ -class HelperTest extends \PHPUnit\Framework\TestCase +class HelperTest extends TestCase { /** * @var ObjectManager */ - protected $objectManager; + private $objectManager; /** * @var Helper */ - protected $helper; + private $helper; /** - * @var ProductLinkInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinkInterfaceFactory|MockObject */ - protected $productLinkFactoryMock; + private $productLinkFactoryMock; /** - * @var RequestInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RequestInterface|MockObject */ - protected $requestMock; + private $requestMock; /** - * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - protected $storeManagerMock; + private $storeManagerMock; /** - * @var StockDataFilter|\PHPUnit_Framework_MockObject_MockObject + * @var StockDataFilter|MockObject */ - protected $stockFilterMock; + private $stockFilterMock; /** - * @var Product|\PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ - protected $productMock; + private $productMock; /** - * @var ProductRepository|\PHPUnit_Framework_MockObject_MockObject + * @var ProductRepository|MockObject */ - protected $productRepositoryMock; + private $productRepositoryMock; /** - * @var ProductCustomOptionInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ProductCustomOptionInterfaceFactory|MockObject */ - protected $customOptionFactoryMock; + private $customOptionFactoryMock; /** - * @var \Magento\Catalog\Model\Product\Link\Resolver|\PHPUnit_Framework_MockObject_MockObject + * @var Resolver|MockObject */ - protected $linkResolverMock; + private $linkResolverMock; /** - * @var \Magento\Catalog\Model\Product\LinkTypeProvider|\PHPUnit_Framework_MockObject_MockObject + * @var LinkTypeProvider|MockObject */ - protected $linkTypeProviderMock; + private $linkTypeProviderMock; /** - * @var ProductLinks|\PHPUnit_Framework_MockObject_MockObject + * @var ProductLinks|MockObject */ - protected $productLinksMock; + private $productLinksMock; /** - * @var AttributeFilter|\PHPUnit_Framework_MockObject_MockObject + * @var AttributeFilter|MockObject */ - protected $attributeFilterMock; + private $attributeFilterMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $dateTimeFilterMock; /** - * @var FormatInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FormatInterface|MockObject */ - protected $localeFormatMock; + private $localeFormatMock; /** * @inheritdoc @@ -147,6 +156,9 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); + $this->linkResolverMock = $this->getMockBuilder(Resolver::class) + ->disableOriginalConstructor() + ->getMock(); $this->productLinksMock = $this->getMockBuilder(ProductLinks::class) ->disableOriginalConstructor() ->getMock(); @@ -165,7 +177,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->dateTimeFilterMock = $this->createMock(\Magento\Catalog\Model\Product\Filter\DateTime::class); + $this->dateTimeFilterMock = $this->createMock(DateTime::class); $this->helper = $this->objectManager->getObject( Helper::class, @@ -174,6 +186,7 @@ protected function setUp() 'storeManager' => $this->storeManagerMock, 'stockFilter' => $this->stockFilterMock, 'productLinks' => $this->productLinksMock, + 'linkResolver' => $this->linkResolverMock, 'customOptionFactory' => $this->customOptionFactoryMock, 'productLinkFactory' => $this->productLinkFactoryMock, 'productRepository' => $this->productRepositoryMock, @@ -183,14 +196,6 @@ protected function setUp() 'dateTimeFilter' => $this->dateTimeFilterMock ] ); - - $this->linkResolverMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Link\Resolver::class) - ->disableOriginalConstructor() - ->getMock(); - $helperReflection = new \ReflectionClass(get_class($this->helper)); - $resolverProperty = $helperReflection->getProperty('linkResolver'); - $resolverProperty->setAccessible(true); - $resolverProperty->setValue($this->helper, $this->linkResolverMock); } /** @@ -266,8 +271,8 @@ public function testInitialize( $this->productMock->expects($this->once())->method('isLockedAttribute')->with('media')->willReturn(true); $this->productMock->expects($this->once())->method('unlockAttribute')->with('media'); $this->productMock->expects($this->once())->method('lockAttribute')->with('media'); - $this->productMock->expects($this->any())->method('getSku')->willReturn('sku'); - $this->productMock->expects($this->any())->method('getOptionsReadOnly')->willReturn(false); + $this->productMock->method('getSku')->willReturn('sku'); + $this->productMock->method('getOptionsReadOnly')->willReturn(false); $customOptionMock = $this->getMockBuilder(Option::class) ->disableOriginalConstructor() @@ -277,8 +282,7 @@ public function testInitialize( $firstExpectedCustomOption->setData($optionsData['option2']); $secondExpectedCustomOption = clone $customOptionMock; $secondExpectedCustomOption->setData($optionsData['option3']); - $this->customOptionFactoryMock->expects($this->any()) - ->method('create') + $this->customOptionFactoryMock->method('create') ->willReturnMap( [ [ @@ -292,17 +296,16 @@ public function testInitialize( ] ); $website = $this->getMockBuilder(WebsiteInterface::class)->getMockForAbstractClass(); - $website->expects($this->any())->method('getId')->willReturn(1); + $website->method('getId')->willReturn(1); $this->storeManagerMock->expects($this->once())->method('isSingleStoreMode')->willReturn($isSingleStore); - $this->storeManagerMock->expects($this->any())->method('getWebsite')->willReturn($website); - $this->localeFormatMock->expects($this->any()) + $this->storeManagerMock->method('getWebsite')->willReturn($website); + $this->localeFormatMock ->method('getNumber') ->willReturnArgument(0); $this->assembleProductRepositoryMock($links); - $this->productLinkFactoryMock->expects($this->any()) - ->method('create') + $this->productLinkFactoryMock->method('create') ->willReturnCallback( function () { return $this->getMockBuilder(ProductLink::class) @@ -318,12 +321,12 @@ function () { $this->assertEquals($expWebsiteIds, $this->productMock->getDataByKey('website_ids')); $productOptions = $this->productMock->getOptions(); - $this->assertTrue(2 == count($productOptions)); - list($option2, $option3) = $productOptions; - $this->assertTrue($option2->getOptionId() == $optionsData['option2']['option_id']); - $this->assertTrue('sku' == $option2->getData('product_sku')); - $this->assertTrue($option3->getOptionId() == $optionsData['option3']['option_id']); - $this->assertTrue('sku' == $option2->getData('product_sku')); + $this->assertCount(2, $productOptions); + [$option2, $option3] = $productOptions; + $this->assertEquals($option2->getOptionId(), $optionsData['option2']['option_id']); + $this->assertEquals('sku', $option2->getData('product_sku')); + $this->assertEquals($option3->getOptionId(), $optionsData['option3']['option_id']); + $this->assertEquals('sku', $option2->getData('product_sku')); $productLinks = $this->productMock->getProductLinks(); $this->assertCount(count($expectedLinks), $productLinks); @@ -350,17 +353,14 @@ private function setProductAttributes(array $attributes): void { $attributesModels = []; foreach ($attributes as $attribute) { - $attributeModel = $this->createMock(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class); + $attributeModel = $this->createMock(Attribute::class); $backendModel = $attribute['backend_model'] - ?? $this->createMock(\Magento\Eav\Model\Entity\Attribute\Backend\DefaultBackend::class); - $attributeModel->expects($this->any()) - ->method('getBackend') + ?? $this->createMock(DefaultBackend::class); + $attributeModel->method('getBackend') ->willReturn($backendModel); - $attributeModel->expects($this->any()) - ->method('getAttributeCode') + $attributeModel->method('getAttributeCode') ->willReturn($attribute['code']); - $backendModel->expects($this->any()) - ->method('getType') + $backendModel->method('getType') ->willReturn($attribute['backend_type']); $attributesModels[$attribute['code']] = $attributeModel; } @@ -736,12 +736,10 @@ private function assembleProductRepositoryMock($links) ->disableOriginalConstructor() ->getMock(); - $mockLinkedProduct->expects($this->any()) - ->method('getId') + $mockLinkedProduct->method('getId') ->willReturn($link['id']); - $mockLinkedProduct->expects($this->any()) - ->method('getSku') + $mockLinkedProduct->method('getSku') ->willReturn($link['sku']); // Even optional arguments need to be provided for returnMapValue @@ -749,8 +747,7 @@ private function assembleProductRepositoryMock($links) } } - $this->productRepositoryMock->expects($this->any()) - ->method('getById') - ->will($this->returnValueMap($repositoryReturnMap)); + $this->productRepositoryMock->method('getById') + ->willReturnMap($repositoryReturnMap); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php b/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php index 458ed98ecf946..d3413db4e50a6 100644 --- a/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Cron/RefreshSpecialPricesTest.php @@ -3,104 +3,117 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Cron; -use Magento\Framework\App\ResourceConnection; +use Magento\Catalog\Cron\RefreshSpecialPrices; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\EntityMetadata; use Magento\Framework\EntityManager\MetadataPool; +use Magento\Framework\Stdlib\DateTime; +use Magento\Framework\Stdlib\DateTime\TimezoneInterface; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Indexer\Model\Indexer; +use Magento\Store\Model\Store; +use Magento\Store\Model\StoreManagerInterface; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** + * Test class for \Magento\Catalog\Cron\RefreshSpecialPrices + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class RefreshSpecialPricesTest extends \PHPUnit\Framework\TestCase +class RefreshSpecialPricesTest extends TestCase { /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ObjectManager */ - protected $_objectManager; + private $objectManager; /** - * @var \Magento\Catalog\Cron\RefreshSpecialPrices + * @var RefreshSpecialPrices */ - protected $_model; + private $model; /** - * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var StoreManagerInterface|MockObject */ - protected $_storeManagerMock; + private $storeManagerMock; /** - * @var Resource|\PHPUnit_Framework_MockObject_MockObject + * @var Resource|MockObject */ - protected $_resourceMock; + private $resourceMock; /** - * @var \Magento\Framework\Stdlib\DateTime|\PHPUnit_Framework_MockObject_MockObject + * @var DateTime|MockObject */ - protected $_dateTimeMock; + private $dateTimeMock; /** - * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject + * @var TimezoneInterface|MockObject */ - protected $_localeDateMock; + private $localeDateMock; /** - * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ - protected $_eavConfigMock; + private $eavConfigMock; /** - * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor|\PHPUnit_Framework_MockObject_MockObject + * @var Processor|MockObject */ - protected $_priceProcessorMock; + private $priceProcessorMock; /** - * @var MetadataPool|\PHPUnit_Framework_MockObject_MockObject + * @var MetadataPool|MockObject */ - protected $metadataPool; + private $metadataPoolMock; /** - * @var \Magento\Framework\EntityManager\EntityMetadata|\PHPUnit_Framework_MockObject_MockObject + * @var EntityMetadata|MockObject */ - protected $metadataMock; + private $metadataMock; protected function setUp() { - $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new ObjectManager($this); - $this->_storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->_resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); - $this->_dateTimeMock = $this->createMock(\Magento\Framework\Stdlib\DateTime::class); - $this->_localeDateMock = $this->createMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); - $this->_eavConfigMock = $this->createMock(\Magento\Eav\Model\Config::class); - $this->_priceProcessorMock = $this->createMock(\Magento\Catalog\Model\Indexer\Product\Price\Processor::class); + $this->storeManagerMock = $this->createMock(StoreManagerInterface::class); + $this->resourceMock = $this->createMock(\Magento\Framework\App\ResourceConnection::class); + $this->dateTimeMock = $this->createMock(DateTime::class); + $this->localeDateMock = $this->createMock(TimezoneInterface::class); + $this->eavConfigMock = $this->createMock(Config::class); + $this->priceProcessorMock = $this->createMock(Processor::class); + $this->metadataPoolMock = $this->createMock(MetadataPool::class); - $this->metadataMock = $this->createMock(\Magento\Framework\EntityManager\EntityMetadata::class); + $this->metadataMock = $this->createMock(EntityMetadata::class); - $this->_model = $this->_objectManager->getObject( - \Magento\Catalog\Cron\RefreshSpecialPrices::class, + $this->model = $this->objectManager->getObject( + RefreshSpecialPrices::class, [ - 'storeManager' => $this->_storeManagerMock, - 'resource' => $this->_resourceMock, - 'dateTime' => $this->_dateTimeMock, - 'localeDate' => $this->_localeDateMock, - 'eavConfig' => $this->_eavConfigMock, - 'processor' => $this->_priceProcessorMock + 'storeManager' => $this->storeManagerMock, + 'resource' => $this->resourceMock, + 'dateTime' => $this->dateTimeMock, + 'localeDate' => $this->localeDateMock, + 'eavConfig' => $this->eavConfigMock, + 'processor' => $this->priceProcessorMock, + 'metadataPool' => $this->metadataPoolMock ] ); - - $this->metadataPool = $this->createMock(MetadataPool::class); - - $reflection = new \ReflectionClass(get_class($this->_model)); - $reflectionProperty = $reflection->getProperty('metadataPool'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($this->_model, $this->metadataPool); } public function testRefreshSpecialPrices() { $idsToProcess = [1, 2, 3]; - $this->metadataPool->expects($this->atLeastOnce()) + $this->metadataPoolMock->expects($this->atLeastOnce()) ->method('getMetadata') ->willReturn($this->metadataMock); @@ -108,73 +121,44 @@ public function testRefreshSpecialPrices() $this->metadataMock->expects($this->atLeastOnce())->method('getIdentifierField')->willReturn('entity_id'); - $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); - $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('joinLeft')->will($this->returnSelf()); - $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); - - $connectionMock = $this->createMock(\Magento\Framework\DB\Adapter\AdapterInterface::class); - $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); - $connectionMock->expects( - $this->any() - )->method( - 'fetchCol' - )->will( - $this->returnValue($idsToProcess) - ); + $selectMock = $this->createMock(Select::class); + $selectMock->method('from')->will($this->returnSelf()); + $selectMock->method('joinLeft')->will($this->returnSelf()); + $selectMock->method('where')->will($this->returnSelf()); - $this->_resourceMock->expects( - $this->once() - )->method( - 'getConnection' - )->will( - $this->returnValue($connectionMock) - ); + $connectionMock = $this->createMock(AdapterInterface::class); + $connectionMock->method('select')->willReturn($selectMock); + $connectionMock->method('fetchCol') + ->willReturn($idsToProcess); - $this->_resourceMock->expects( - $this->any() - )->method( - 'getTableName' - )->will( - $this->returnValue('category') - ); + $this->resourceMock->expects($this->once()) + ->method('getConnection') + ->willReturn($connectionMock); + $this->resourceMock->method('getTableName') + ->willReturn('category'); - $storeMock = $this->createMock(\Magento\Store\Model\Store::class); - $storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); - - $this->_storeManagerMock->expects( - $this->once() - )->method( - 'getStores' - )->with( - true - )->will( - $this->returnValue([$storeMock]) - ); + $storeMock = $this->createMock(Store::class); + $storeMock->method('getId')->willReturn(1); - $this->_localeDateMock->expects( - $this->once() - )->method( - 'scopeTimeStamp' - )->with( - $storeMock - )->will( - $this->returnValue(32000) - ); + $this->storeManagerMock->expects($this->once()) + ->method('getStores') + ->with(true) + ->willReturn([$storeMock]); - $indexerMock = $this->createMock(\Magento\Indexer\Model\Indexer::class); + $this->localeDateMock->expects($this->once()) + ->method('scopeTimeStamp') + ->with($storeMock) + ->willReturn(strtotime(date('Y-m-d'))); + + $indexerMock = $this->createMock(Indexer::class); $indexerMock->expects($this->exactly(2))->method('reindexList'); - $this->_priceProcessorMock->expects( - $this->exactly(2) - )->method( - 'getIndexer' - )->will( - $this->returnValue($indexerMock) - ); + $this->priceProcessorMock->expects($this->exactly(2)) + ->method('getIndexer') + ->willReturn($indexerMock); $attributeMock = $this->getMockForAbstractClass( - \Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class, + AbstractAttribute::class, [], '', false, @@ -182,10 +166,10 @@ public function testRefreshSpecialPrices() true, ['__wakeup', 'getAttributeId'] ); - $attributeMock->expects($this->any())->method('getAttributeId')->will($this->returnValue(1)); + $attributeMock->method('getAttributeId')->willReturn(1); - $this->_eavConfigMock->expects($this->any())->method('getAttribute')->will($this->returnValue($attributeMock)); + $this->eavConfigMock->method('getAttribute')->willReturn($attributeMock); - $this->_model->execute(); + $this->model->execute(); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php index 1bd85c4053263..128d6c1e36f58 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/OptionTest.php @@ -5,26 +5,35 @@ */ namespace Magento\Catalog\Test\Unit\Model\Product; -use \Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Option; +use Magento\Catalog\Model\Product\Option\Value; +use Magento\Framework\Pricing\Amount\AmountInterface; +use Magento\Framework\Pricing\PriceInfoInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class OptionTest extends \PHPUnit\Framework\TestCase +/** + * Test class for \Magento\Catalog\Model\Product\Option + */ +class OptionTest extends TestCase { /** - * @var \Magento\Catalog\Model\Product\Option + * @var Option */ - protected $model; + private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Product|MockObject */ - protected $productMock; + private $productMock; protected function setUp() { - $this->productMock = $this->createMock(\Magento\Catalog\Model\Product::class); + $this->productMock = $this->createMock(Product::class); $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject(\Magento\Catalog\Model\Product\Option::class); + $this->model = $objectManager->getObject(Option::class); $this->model->setProduct($this->productMock); } @@ -47,7 +56,7 @@ public function testHasValues() public function testGetRegularPrice() { $priceInfoMock = $this->getMockForAbstractClass( - \Magento\Framework\Pricing\PriceInfoInterface::class, + PriceInfoInterface::class, [], '', false, @@ -56,14 +65,14 @@ public function testGetRegularPrice() ['getAmount', 'getPrice'] ); $priceInfoMock->expects($this->once())->method('getPrice')->willReturnSelf(); - $amountMock = $this->getMockForAbstractClass(\Magento\Framework\Pricing\Amount\AmountInterface::class); + $amountMock = $this->getMockForAbstractClass(AmountInterface::class); $priceInfoMock->expects($this->once())->method('getAmount')->willReturn($amountMock); $this->productMock->expects($this->once())->method('getPriceInfo')->willReturn($priceInfoMock); $amountMock->expects($this->once())->method('getValue')->willReturn(50); $this->model->setPrice(50); - $this->model->setPriceType(\Magento\Catalog\Model\Product\Option\Value::TYPE_PERCENT); + $this->model->setPriceType(Value::TYPE_PERCENT); $this->assertEquals(25, $this->model->getRegularPrice()); $this->model->setPriceType(null); $this->assertEquals(50, $this->model->getRegularPrice()); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php index 0606a31befcb7..4f4706f71d0cb 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/ProductTest.php @@ -6,40 +6,51 @@ namespace Magento\Catalog\Test\Unit\Model\ResourceModel; +use Magento\Catalog\Model\ResourceModel\Product; +use Magento\Eav\Model\Entity\Attribute\Set; +use Magento\Eav\Model\Entity\Attribute\SetFactory; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\Entity\TypeFactory; +use Magento\Framework\DataObject; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; -class ProductTest extends \PHPUnit\Framework\TestCase +/** + * Test class for \Magento\Catalog\Model\ResourceModel\Product + */ +class ProductTest extends TestCase { /** - * @var \Magento\Catalog\Model\ResourceModel\Product + * @var Product */ - protected $model; + private $model; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var SetFactory|MockObject */ - protected $setFactoryMock; + private $setFactoryMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var TypeFactory|MockObject */ - protected $typeFactoryMock; + private $typeFactoryMock; protected function setUp() { $objectManager = new ObjectManager($this); $this->setFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\SetFactory::class, + SetFactory::class, ['create', '__wakeup'] ); $this->typeFactoryMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\TypeFactory::class, + TypeFactory::class, ['create', '__wakeup'] ); $this->model = $objectManager->getObject( - \Magento\Catalog\Model\ResourceModel\Product::class, + Product::class, [ 'setFactory' => $this->setFactoryMock, 'typeFactory' => $this->typeFactoryMock, @@ -53,28 +64,28 @@ public function testValidateWrongAttributeSet() $expectedErrorMessage = ['attribute_set' => 'Invalid attribute set entity type']; $productMock = $this->createPartialMock( - \Magento\Framework\DataObject::class, + DataObject::class, ['getAttributeSetId', '__wakeup'] ); $attributeSetMock = $this->createPartialMock( - \Magento\Eav\Model\Entity\Attribute\Set::class, + Set::class, ['load', 'getEntityTypeId', '__wakeup'] ); - $entityTypeMock = $this->createMock(\Magento\Eav\Model\Entity\Type::class); + $entityTypeMock = $this->createMock(Type::class); - $this->typeFactoryMock->expects($this->once())->method('create')->will($this->returnValue($entityTypeMock)); + $this->typeFactoryMock->expects($this->once())->method('create')->willReturn($entityTypeMock); $entityTypeMock->expects($this->once())->method('loadByCode')->with('catalog_product')->willReturnSelf(); $productAttributeSetId = 4; $productMock->expects($this->once())->method('getAttributeSetId') - ->will($this->returnValue($productAttributeSetId)); + ->willReturn($productAttributeSetId); - $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); + $this->setFactoryMock->expects($this->once())->method('create')->willReturn($attributeSetMock); $attributeSetMock->expects($this->once())->method('load')->with($productAttributeSetId)->willReturnSelf(); //attribute set of wrong type - $attributeSetMock->expects($this->once())->method('getEntityTypeId')->will($this->returnValue(3)); - $entityTypeMock->expects($this->once())->method('getId')->will($this->returnValue($productTypeId)); + $attributeSetMock->expects($this->once())->method('getEntityTypeId')->willReturn(3); + $entityTypeMock->expects($this->once())->method('getId')->willReturn($productTypeId); $this->assertEquals($expectedErrorMessage, $this->model->validate($productMock)); } diff --git a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php index 438c6ee13af57..8642a2e7a1621 100644 --- a/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Ui/DataProvider/Product/Form/Modifier/RelatedTest.php @@ -3,23 +3,28 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Test\Unit\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related; /** - * Class RelatedTest + * Test class for \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related */ class RelatedTest extends AbstractModifierTest { /** - * @return \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related + * @return Related */ protected function createModel() { - return $this->objectManager->getObject(\Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related::class, [ - 'locator' => $this->locatorMock, - ]); + return $this->objectManager->getObject( + Related::class, + [ + 'locator' => $this->locatorMock, + ] + ); } /** diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php index cd1f8e8e3379b..fa417a789bd03 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php @@ -7,17 +7,19 @@ namespace Magento\Catalog\Ui\DataProvider\Product\Form\Modifier; +use Magento\Catalog\Model\Category as CategoryModel; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\ResourceModel\Category\Collection; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; -use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\Cache\Type\Block; use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\AuthorizationInterface; use Magento\Framework\DB\Helper as DbHelper; -use Magento\Catalog\Model\Category as CategoryModel; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Serialize\SerializerInterface; -use Magento\Framework\UrlInterface; use Magento\Framework\Stdlib\ArrayManager; -use Magento\Framework\AuthorizationInterface; +use Magento\Framework\UrlInterface; /** * Data provider for categories field of product page @@ -92,8 +94,9 @@ class Categories extends AbstractModifier * @param DbHelper $dbHelper * @param UrlInterface $urlBuilder * @param ArrayManager $arrayManager - * @param SerializerInterface $serializer - * @param AuthorizationInterface $authorization + * @param SerializerInterface|null $serializer + * @param AuthorizationInterface|null $authorization + * @param CacheInterface|null $cacheManager */ public function __construct( LocatorInterface $locator, @@ -102,7 +105,8 @@ public function __construct( UrlInterface $urlBuilder, ArrayManager $arrayManager, SerializerInterface $serializer = null, - AuthorizationInterface $authorization = null + AuthorizationInterface $authorization = null, + ?CacheInterface $cacheManager = null ) { $this->locator = $locator; $this->categoryCollectionFactory = $categoryCollectionFactory; @@ -111,21 +115,7 @@ public function __construct( $this->arrayManager = $arrayManager; $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); $this->authorization = $authorization ?: ObjectManager::getInstance()->get(AuthorizationInterface::class); - } - - /** - * Retrieve cache interface - * - * @return CacheInterface - * @deprecated 101.0.3 - */ - private function getCacheManager(): CacheInterface - { - if (!$this->cacheManager) { - $this->cacheManager = ObjectManager::getInstance() - ->get(CacheInterface::class); - } - return $this->cacheManager; + $this->cacheManager = $cacheManager ?? ObjectManager::getInstance()->get(CacheInterface::class); } /** @@ -165,6 +155,7 @@ public function modifyData(array $data) * Create slide-out panel for new category creation * * @param array $meta + * * @return array * @since 101.0.0 */ @@ -224,6 +215,7 @@ protected function createNewCategoryModal(array $meta) * Customize Categories field * * @param array $meta + * * @return array * @throws LocalizedException * @since 101.0.0 @@ -283,6 +275,7 @@ protected function customizeCategoriesField(array $meta) ], ] ]; + if ($this->isAllowed()) { $value['children']['create_category_button'] = [ 'arguments' => [ @@ -301,13 +294,11 @@ protected function customizeCategoriesField(array $meta) 'actionName' => 'toggleModal', ], [ - 'targetName' => - 'product_form.product_form.create_category_modal.create_category', + 'targetName' => 'product_form.product_form.create_category_modal.create_category', 'actionName' => 'render' ], [ - 'targetName' => - 'product_form.product_form.create_category_modal.create_category', + 'targetName' => 'product_form.product_form.create_category_modal.create_category', 'actionName' => 'resetForm' ] ], @@ -339,8 +330,7 @@ protected function getCategoriesTree($filter = null) { $storeId = (int) $this->locator->getStore()->getId(); - $cachedCategoriesTree = $this->getCacheManager() - ->load($this->getCategoriesTreeCacheId($storeId, (string) $filter)); + $cachedCategoriesTree = $this->cacheManager->load($this->getCategoriesTreeCacheId($storeId, (string) $filter)); if (!empty($cachedCategoriesTree)) { return $this->serializer->unserialize($cachedCategoriesTree); } @@ -350,12 +340,12 @@ protected function getCategoriesTree($filter = null) $this->retrieveShownCategoriesIds($storeId, (string) $filter) ); - $this->getCacheManager()->save( + $this->cacheManager->save( $this->serializer->serialize($categoriesTree), $this->getCategoriesTreeCacheId($storeId, (string) $filter), [ - \Magento\Catalog\Model\Category::CACHE_TAG, - \Magento\Framework\App\Cache\Type\Block::CACHE_TAG + CategoryModel::CACHE_TAG, + Block::CACHE_TAG ] ); @@ -372,7 +362,7 @@ protected function getCategoriesTree($filter = null) private function getCategoriesTreeCacheId(int $storeId, string $filter = '') : string { return self::CATEGORY_TREE_ID - . '_' . (string) $storeId + . '_' . $storeId . '_' . $filter; } @@ -386,7 +376,7 @@ private function getCategoriesTreeCacheId(int $storeId, string $filter = '') : s */ private function retrieveShownCategoriesIds(int $storeId, string $filter = '') : array { - /* @var $matchingNamesCollection \Magento\Catalog\Model\ResourceModel\Category\Collection */ + /* @var $matchingNamesCollection Collection */ $matchingNamesCollection = $this->categoryCollectionFactory->create(); if (!empty($filter)) { @@ -402,7 +392,7 @@ private function retrieveShownCategoriesIds(int $storeId, string $filter = '') : $shownCategoriesIds = []; - /** @var \Magento\Catalog\Model\Category $category */ + /** @var CategoryModel $category */ foreach ($matchingNamesCollection as $category) { foreach (explode('/', $category->getPath()) as $parentId) { $shownCategoriesIds[$parentId] = 1; @@ -422,7 +412,7 @@ private function retrieveShownCategoriesIds(int $storeId, string $filter = '') : */ private function retrieveCategoriesTree(int $storeId, array $shownCategoriesIds) : ?array { - /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */ + /* @var $collection Collection */ $collection = $this->categoryCollectionFactory->create(); $collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)]) diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php index b822a5e3ef88a..18d9500654065 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php @@ -3,13 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Catalog\Ui\DataProvider\Product\Form\Modifier; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\Data\ProductLinkInterface; use Magento\Catalog\Api\ProductLinkRepositoryInterface; use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Catalog\Helper\Image as ImageHelper; use Magento\Catalog\Model\Locator\LocatorInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Attribute\Source\Status; +use Magento\Catalog\Ui\Component\Listing\Columns\Price; use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Phrase; @@ -21,8 +27,6 @@ use Magento\Ui\Component\Form\Field; use Magento\Ui\Component\Form\Fieldset; use Magento\Ui\Component\Modal; -use Magento\Catalog\Helper\Image as ImageHelper; -use Magento\Catalog\Model\Product\Attribute\Source\Status; /** * Related products modifier @@ -92,6 +96,11 @@ class Related extends AbstractModifier */ protected $attributeSetRepository; + /** + * @var Price + */ + private $priceModifier; + /** * @var string * @since 101.0.0 @@ -104,11 +113,6 @@ class Related extends AbstractModifier */ protected $scopePrefix; - /** - * @var \Magento\Catalog\Ui\Component\Listing\Columns\Price - */ - private $priceModifier; - /** * @param LocatorInterface $locator * @param UrlInterface $urlBuilder @@ -119,6 +123,9 @@ class Related extends AbstractModifier * @param AttributeSetRepositoryInterface $attributeSetRepository * @param string $scopeName * @param string $scopePrefix + * @param Price|null $priceModifier + * + * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( LocatorInterface $locator, @@ -129,7 +136,8 @@ public function __construct( Status $status, AttributeSetRepositoryInterface $attributeSetRepository, $scopeName = '', - $scopePrefix = '' + $scopePrefix = '', + ?Price $priceModifier = null ) { $this->locator = $locator; $this->urlBuilder = $urlBuilder; @@ -140,10 +148,11 @@ public function __construct( $this->attributeSetRepository = $attributeSetRepository; $this->scopeName = $scopeName; $this->scopePrefix = $scopePrefix; + $this->priceModifier = $priceModifier ?? ObjectManager::getInstance()->get(Price::class); } /** - * @inheritdoc + * @inheritDoc * @since 101.0.0 */ public function modifyMeta(array $meta) @@ -164,12 +173,11 @@ public function modifyMeta(array $meta) 'collapsible' => true, 'componentType' => Fieldset::NAME, 'dataScope' => static::DATA_SCOPE, - 'sortOrder' => - $this->getNextGroupSortOrder( - $meta, - self::$previousGroup, - self::$sortOrder - ), + 'sortOrder' => $this->getNextGroupSortOrder( + $meta, + self::$previousGroup, + self::$sortOrder + ), ], ], @@ -182,12 +190,12 @@ public function modifyMeta(array $meta) } /** - * @inheritdoc + * @inheritDoc * @since 101.0.0 */ public function modifyData(array $data) { - /** @var \Magento\Catalog\Model\Product $product */ + /** @var Product $product */ $product = $this->locator->getProduct(); $productId = $product->getId(); @@ -195,11 +203,10 @@ public function modifyData(array $data) return $data; } - $priceModifier = $this->getPriceModifier(); /** * Set field name for modifier */ - $priceModifier->setData('name', 'price'); + $this->priceModifier->setData('name', 'price'); foreach ($this->getDataScopes() as $dataScope) { $data[$productId]['links'][$dataScope] = []; @@ -208,7 +215,7 @@ public function modifyData(array $data) continue; } - /** @var \Magento\Catalog\Model\Product $linkedProduct */ + /** @var Product $linkedProduct */ $linkedProduct = $this->productRepository->get( $linkItem->getLinkedProductSku(), false, @@ -217,7 +224,7 @@ public function modifyData(array $data) $data[$productId]['links'][$dataScope][] = $this->fillData($linkedProduct, $linkItem); } if (!empty($data[$productId]['links'][$dataScope])) { - $dataMap = $priceModifier->prepareDataSource([ + $dataMap = $this->priceModifier->prepareDataSource([ 'data' => [ 'items' => $data[$productId]['links'][$dataScope] ] @@ -232,27 +239,12 @@ public function modifyData(array $data) return $data; } - /** - * Get price modifier - * - * @return \Magento\Catalog\Ui\Component\Listing\Columns\Price - * @deprecated 101.0.0 - */ - private function getPriceModifier() - { - if (!$this->priceModifier) { - $this->priceModifier = ObjectManager::getInstance()->get( - \Magento\Catalog\Ui\Component\Listing\Columns\Price::class - ); - } - return $this->priceModifier; - } - /** * Prepare data column * * @param ProductInterface $linkedProduct * @param ProductLinkInterface $linkItem + * * @return array * @since 101.0.0 */ @@ -415,6 +407,7 @@ protected function getCrossSellFieldset() * @param Phrase $content * @param Phrase $buttonTitle * @param string $scope + * * @return array * @since 101.0.0 */ @@ -468,6 +461,7 @@ protected function getButtonSet(Phrase $content, Phrase $buttonTitle, $scope) * * @param Phrase $title * @param string $scope + * * @return array * @since 101.0.0 */ @@ -475,7 +469,7 @@ protected function getGenericModal(Phrase $title, $scope) { $listingTarget = $scope . '_product_listing'; - $modal = [ + return [ 'arguments' => [ 'data' => [ 'config' => [ @@ -539,14 +533,13 @@ protected function getGenericModal(Phrase $title, $scope) ], ], ]; - - return $modal; } /** * Retrieve grid * * @param string $scope + * * @return array * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @since 101.0.0 @@ -676,12 +669,13 @@ protected function fillMeta() * @param bool $fit * @param Phrase $label * @param int $sortOrder + * * @return array * @since 101.0.0 */ protected function getTextColumn($dataScope, $fit, Phrase $label, $sortOrder) { - $column = [ + return [ 'arguments' => [ 'data' => [ 'config' => [ @@ -698,7 +692,5 @@ protected function getTextColumn($dataScope, $fit, Phrase $label, $sortOrder) ], ], ]; - - return $column; } }