Product.php 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Catalog\Model;
  7. use Magento\Catalog\Api\CategoryRepositoryInterface;
  8. use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface;
  9. use Magento\Catalog\Api\Data\ProductInterface;
  10. use Magento\Catalog\Api\ProductLinkRepositoryInterface;
  11. use Magento\Catalog\Model\Product\Attribute\Backend\Media\EntryConverterPool;
  12. use Magento\Catalog\Model\FilterProductCustomAttribute;
  13. use Magento\Framework\Api\AttributeValueFactory;
  14. use Magento\Framework\App\Filesystem\DirectoryList;
  15. use Magento\Framework\App\ObjectManager;
  16. use Magento\Framework\DataObject\IdentityInterface;
  17. use Magento\Framework\Pricing\SaleableInterface;
  18. /**
  19. * Catalog product model
  20. *
  21. * @api
  22. * @method Product setHasError(bool $value)
  23. * @method null|bool getHasError()
  24. * @method array getAssociatedProductIds()
  25. * @method Product setNewVariationsAttributeSetId(int $value)
  26. * @method int getNewVariationsAttributeSetId()
  27. * @method int getPriceType()
  28. * @method string getUrlKey()
  29. * @method Product setUrlKey(string $urlKey)
  30. * @method Product setRequestPath(string $requestPath)
  31. * @method Product setWebsiteIds(array $ids)
  32. *
  33. * @SuppressWarnings(PHPMD.LongVariable)
  34. * @SuppressWarnings(PHPMD.ExcessivePublicCount)
  35. * @SuppressWarnings(PHPMD.TooManyFields)
  36. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  37. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  38. * @since 100.0.2
  39. */
  40. class Product extends \Magento\Catalog\Model\AbstractModel implements
  41. IdentityInterface,
  42. SaleableInterface,
  43. ProductInterface
  44. {
  45. /**
  46. * @var ProductLinkRepositoryInterface
  47. * @since 101.0.0
  48. */
  49. protected $linkRepository;
  50. /**
  51. * Entity code.
  52. * Can be used as part of method name for entity processing
  53. */
  54. const ENTITY = 'catalog_product';
  55. /**
  56. * Product cache tag
  57. */
  58. const CACHE_TAG = 'cat_p';
  59. /**
  60. * Category product relation cache tag
  61. */
  62. const CACHE_PRODUCT_CATEGORY_TAG = 'cat_c_p';
  63. /**
  64. * Product Store Id
  65. */
  66. const STORE_ID = 'store_id';
  67. /**
  68. * @var string
  69. */
  70. protected $_cacheTag = self::CACHE_TAG;
  71. /**
  72. * @var string
  73. */
  74. protected $_eventPrefix = 'catalog_product';
  75. /**
  76. * @var string
  77. */
  78. protected $_eventObject = 'product';
  79. /**
  80. * @var bool
  81. */
  82. protected $_canAffectOptions = false;
  83. /**
  84. * Product type singleton instance
  85. *
  86. * @var \Magento\Catalog\Model\Product\Type\AbstractType
  87. */
  88. protected $_typeInstance = null;
  89. /**
  90. * Product link instance
  91. *
  92. * @var Product\Link
  93. */
  94. protected $_linkInstance;
  95. /**
  96. * Product object customization (not stored in DB)
  97. *
  98. * @var array
  99. */
  100. protected $_customOptions = [];
  101. /**
  102. * Product Url Instance
  103. *
  104. * @var Product\Url
  105. */
  106. protected $_urlModel = null;
  107. /**
  108. * @var ResourceModel\Product
  109. * @since 102.0.6
  110. */
  111. protected $_resource;
  112. /**
  113. * @var string
  114. */
  115. protected static $_url;
  116. /**
  117. * @var array
  118. */
  119. protected $_errors = [];
  120. /**
  121. * Product option factory
  122. *
  123. * @var Product\OptionFactory
  124. */
  125. protected $optionFactory;
  126. /**
  127. * Product option
  128. *
  129. * @var Product\Option
  130. */
  131. protected $optionInstance;
  132. /**
  133. * @var array
  134. */
  135. protected $_links = null;
  136. /**
  137. * Flag for available duplicate function
  138. *
  139. * @var boolean
  140. */
  141. protected $_isDuplicable = true;
  142. /**
  143. * Flag for get Price function
  144. *
  145. * @var boolean
  146. */
  147. protected $_calculatePrice = true;
  148. /**
  149. * Catalog product
  150. *
  151. * @var \Magento\Catalog\Helper\Product
  152. */
  153. protected $_catalogProduct = null;
  154. /**
  155. * @var \Magento\Framework\Module\Manager
  156. */
  157. protected $moduleManager;
  158. /**
  159. * @var \Magento\Framework\Data\CollectionFactory
  160. */
  161. protected $_collectionFactory;
  162. /**
  163. * Catalog product type
  164. *
  165. * @var Product\Type
  166. */
  167. protected $_catalogProductType;
  168. /**
  169. * Catalog product media config
  170. *
  171. * @var Product\Media\Config
  172. */
  173. protected $_catalogProductMediaConfig;
  174. /**
  175. * Catalog product status
  176. *
  177. * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
  178. */
  179. protected $_catalogProductStatus;
  180. /**
  181. * Catalog product visibility
  182. *
  183. * @var Product\Visibility
  184. */
  185. protected $_catalogProductVisibility;
  186. /**
  187. * Stock item factory
  188. *
  189. * @var \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory
  190. */
  191. protected $_stockItemFactory;
  192. /**
  193. * Item option factory
  194. *
  195. * @var \Magento\Catalog\Model\Product\Configuration\Item\OptionFactory
  196. */
  197. protected $_itemOptionFactory;
  198. /**
  199. * Filesystem facade
  200. *
  201. * @var \Magento\Framework\Filesystem
  202. */
  203. protected $_filesystem;
  204. /**
  205. * @var \Magento\Framework\Indexer\IndexerRegistry
  206. */
  207. protected $indexerRegistry;
  208. /**
  209. * @var \Magento\Catalog\Model\Indexer\Product\Flat\Processor
  210. */
  211. protected $_productFlatIndexerProcessor;
  212. /**
  213. * @var \Magento\Catalog\Model\Indexer\Product\Price\Processor
  214. */
  215. protected $_productPriceIndexerProcessor;
  216. /**
  217. * @var Indexer\Product\Eav\Processor
  218. */
  219. protected $_productEavIndexerProcessor;
  220. /**
  221. * @var \Magento\Framework\Pricing\PriceInfo\Base
  222. */
  223. protected $_priceInfo;
  224. /**
  225. * @var CategoryRepository
  226. */
  227. protected $categoryRepository;
  228. /**
  229. * Instance of category collection.
  230. *
  231. * @var \Magento\Catalog\Model\ResourceModel\Category\Collection
  232. */
  233. protected $categoryCollection;
  234. /**
  235. * @var Product\Image\CacheFactory
  236. */
  237. protected $imageCacheFactory;
  238. /**
  239. * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
  240. * @deprecated 102.0.6 Not used anymore due to performance issue (loaded all product attributes)
  241. */
  242. protected $metadataService;
  243. /**
  244. * @param \Magento\Catalog\Model\ProductLink\CollectionProvider
  245. */
  246. protected $entityCollectionProvider;
  247. /**
  248. * @param \Magento\Catalog\Model\Product\LinkTypeProvider
  249. */
  250. protected $linkProvider;
  251. /**
  252. * @param \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory
  253. */
  254. protected $productLinkFactory;
  255. /**
  256. * @param \Magento\Catalog\Api\Data\ProductLinkExtensionFactory
  257. */
  258. protected $productLinkExtensionFactory;
  259. /**
  260. * @var \Magento\Framework\Api\DataObjectHelper
  261. */
  262. protected $dataObjectHelper;
  263. /**
  264. * @var int
  265. */
  266. protected $_productIdCached;
  267. /**
  268. * List of attributes in ProductInterface
  269. *
  270. * @deprecated 103.0.0
  271. * @see ProductInterface::ATTRIBUTES
  272. * @var array
  273. */
  274. protected $interfaceAttributes = ProductInterface::ATTRIBUTES;
  275. /**
  276. * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface
  277. */
  278. protected $joinProcessor;
  279. /**
  280. * Media converter pool
  281. *
  282. * @var Product\Attribute\Backend\Media\EntryConverterPool
  283. */
  284. protected $mediaGalleryEntryConverterPool;
  285. /**
  286. * @var \Magento\Catalog\Model\Product\Gallery\Processor
  287. * @since 101.0.0
  288. */
  289. protected $mediaGalleryProcessor;
  290. /**
  291. * @var Product\LinkTypeProvider
  292. * @since 101.0.0
  293. */
  294. protected $linkTypeProvider;
  295. /**
  296. * @var \Magento\Eav\Model\Config
  297. */
  298. private $eavConfig;
  299. /**
  300. * @var FilterProductCustomAttribute|null
  301. */
  302. private $filterCustomAttribute;
  303. /**
  304. * @param \Magento\Framework\Model\Context $context
  305. * @param \Magento\Framework\Registry $registry
  306. * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
  307. * @param AttributeValueFactory $customAttributeFactory
  308. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  309. * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataService
  310. * @param Product\Url $url
  311. * @param Product\Link $productLink
  312. * @param Product\Configuration\Item\OptionFactory $itemOptionFactory
  313. * @param \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory $stockItemFactory
  314. * @param Product\OptionFactory $catalogProductOptionFactory
  315. * @param Product\Visibility $catalogProductVisibility
  316. * @param Product\Attribute\Source\Status $catalogProductStatus
  317. * @param Product\Media\Config $catalogProductMediaConfig
  318. * @param Product\Type $catalogProductType
  319. * @param \Magento\Framework\Module\Manager $moduleManager
  320. * @param \Magento\Catalog\Helper\Product $catalogProduct
  321. * @param ResourceModel\Product $resource
  322. * @param ResourceModel\Product\Collection $resourceCollection
  323. * @param \Magento\Framework\Data\CollectionFactory $collectionFactory
  324. * @param \Magento\Framework\Filesystem $filesystem
  325. * @param \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry
  326. * @param Indexer\Product\Flat\Processor $productFlatIndexerProcessor
  327. * @param Indexer\Product\Price\Processor $productPriceIndexerProcessor
  328. * @param Indexer\Product\Eav\Processor $productEavIndexerProcessor
  329. * @param CategoryRepositoryInterface $categoryRepository
  330. * @param Product\Image\CacheFactory $imageCacheFactory
  331. * @param ProductLink\CollectionProvider $entityCollectionProvider
  332. * @param Product\LinkTypeProvider $linkTypeProvider
  333. * @param \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory $productLinkFactory
  334. * @param \Magento\Catalog\Api\Data\ProductLinkExtensionFactory $productLinkExtensionFactory
  335. * @param EntryConverterPool $mediaGalleryEntryConverterPool
  336. * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
  337. * @param \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $joinProcessor
  338. * @param array $data
  339. * @param \Magento\Eav\Model\Config|null $config
  340. * @param FilterProductCustomAttribute|null $filterCustomAttribute
  341. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  342. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  343. */
  344. public function __construct(
  345. \Magento\Framework\Model\Context $context,
  346. \Magento\Framework\Registry $registry,
  347. \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
  348. AttributeValueFactory $customAttributeFactory,
  349. \Magento\Store\Model\StoreManagerInterface $storeManager,
  350. \Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataService,
  351. Product\Url $url,
  352. Product\Link $productLink,
  353. \Magento\Catalog\Model\Product\Configuration\Item\OptionFactory $itemOptionFactory,
  354. \Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory $stockItemFactory,
  355. \Magento\Catalog\Model\Product\OptionFactory $catalogProductOptionFactory,
  356. \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
  357. \Magento\Catalog\Model\Product\Attribute\Source\Status $catalogProductStatus,
  358. \Magento\Catalog\Model\Product\Media\Config $catalogProductMediaConfig,
  359. Product\Type $catalogProductType,
  360. \Magento\Framework\Module\Manager $moduleManager,
  361. \Magento\Catalog\Helper\Product $catalogProduct,
  362. \Magento\Catalog\Model\ResourceModel\Product $resource,
  363. \Magento\Catalog\Model\ResourceModel\Product\Collection $resourceCollection,
  364. \Magento\Framework\Data\CollectionFactory $collectionFactory,
  365. \Magento\Framework\Filesystem $filesystem,
  366. \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry,
  367. \Magento\Catalog\Model\Indexer\Product\Flat\Processor $productFlatIndexerProcessor,
  368. \Magento\Catalog\Model\Indexer\Product\Price\Processor $productPriceIndexerProcessor,
  369. \Magento\Catalog\Model\Indexer\Product\Eav\Processor $productEavIndexerProcessor,
  370. CategoryRepositoryInterface $categoryRepository,
  371. Product\Image\CacheFactory $imageCacheFactory,
  372. \Magento\Catalog\Model\ProductLink\CollectionProvider $entityCollectionProvider,
  373. \Magento\Catalog\Model\Product\LinkTypeProvider $linkTypeProvider,
  374. \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory $productLinkFactory,
  375. \Magento\Catalog\Api\Data\ProductLinkExtensionFactory $productLinkExtensionFactory,
  376. EntryConverterPool $mediaGalleryEntryConverterPool,
  377. \Magento\Framework\Api\DataObjectHelper $dataObjectHelper,
  378. \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $joinProcessor,
  379. array $data = [],
  380. \Magento\Eav\Model\Config $config = null,
  381. FilterProductCustomAttribute $filterCustomAttribute = null
  382. ) {
  383. $this->metadataService = $metadataService;
  384. $this->_itemOptionFactory = $itemOptionFactory;
  385. $this->_stockItemFactory = $stockItemFactory;
  386. $this->optionFactory = $catalogProductOptionFactory;
  387. $this->_catalogProductVisibility = $catalogProductVisibility;
  388. $this->_catalogProductStatus = $catalogProductStatus;
  389. $this->_catalogProductMediaConfig = $catalogProductMediaConfig;
  390. $this->_catalogProductType = $catalogProductType;
  391. $this->moduleManager = $moduleManager;
  392. $this->_catalogProduct = $catalogProduct;
  393. $this->_collectionFactory = $collectionFactory;
  394. $this->_urlModel = $url;
  395. $this->_linkInstance = $productLink;
  396. $this->_filesystem = $filesystem;
  397. $this->indexerRegistry = $indexerRegistry;
  398. $this->_productFlatIndexerProcessor = $productFlatIndexerProcessor;
  399. $this->_productPriceIndexerProcessor = $productPriceIndexerProcessor;
  400. $this->_productEavIndexerProcessor = $productEavIndexerProcessor;
  401. $this->categoryRepository = $categoryRepository;
  402. $this->imageCacheFactory = $imageCacheFactory;
  403. $this->entityCollectionProvider = $entityCollectionProvider;
  404. $this->linkTypeProvider = $linkTypeProvider;
  405. $this->productLinkFactory = $productLinkFactory;
  406. $this->productLinkExtensionFactory = $productLinkExtensionFactory;
  407. $this->mediaGalleryEntryConverterPool = $mediaGalleryEntryConverterPool;
  408. $this->dataObjectHelper = $dataObjectHelper;
  409. $this->joinProcessor = $joinProcessor;
  410. parent::__construct(
  411. $context,
  412. $registry,
  413. $extensionFactory,
  414. $customAttributeFactory,
  415. $storeManager,
  416. $resource,
  417. $resourceCollection,
  418. $data
  419. );
  420. $this->eavConfig = $config ?? ObjectManager::getInstance()->get(\Magento\Eav\Model\Config::class);
  421. $this->filterCustomAttribute = $filterCustomAttribute
  422. ?? ObjectManager::getInstance()->get(FilterProductCustomAttribute::class);
  423. }
  424. /**
  425. * Initialize resources
  426. *
  427. * @return void
  428. */
  429. protected function _construct()
  430. {
  431. $this->_init(\Magento\Catalog\Model\ResourceModel\Product::class);
  432. }
  433. /**
  434. * Get resource instance
  435. *
  436. * @throws \Magento\Framework\Exception\LocalizedException
  437. * @return \Magento\Catalog\Model\ResourceModel\Product
  438. * @deprecated 102.0.6 because resource models should be used directly
  439. * @since 102.0.6
  440. */
  441. protected function _getResource()
  442. {
  443. return parent::_getResource();
  444. }
  445. /**
  446. * Get a list of custom attribute codes that belongs to product attribute set.
  447. *
  448. * If attribute set not specified for product will return all product attribute codes
  449. *
  450. * @return string[]
  451. */
  452. protected function getCustomAttributesCodes()
  453. {
  454. if ($this->customAttributesCodes === null) {
  455. $this->customAttributesCodes = array_diff(
  456. array_keys(
  457. $this->filterCustomAttribute->execute(
  458. $this->eavConfig->getEntityAttributes(
  459. self::ENTITY,
  460. $this
  461. )
  462. )
  463. ),
  464. ProductInterface::ATTRIBUTES
  465. );
  466. }
  467. return $this->customAttributesCodes;
  468. }
  469. /**
  470. * Retrieve Store Id
  471. *
  472. * @return int
  473. */
  474. public function getStoreId()
  475. {
  476. if ($this->hasData(self::STORE_ID)) {
  477. return (int)$this->getData(self::STORE_ID);
  478. }
  479. return (int)$this->_storeManager->getStore()->getId();
  480. }
  481. /**
  482. * Get product url model
  483. *
  484. * @return Product\Url
  485. */
  486. public function getUrlModel()
  487. {
  488. return $this->_urlModel;
  489. }
  490. /**
  491. * Validate Product Data
  492. *
  493. * @todo implement full validation process with errors returning which are ignoring now
  494. *
  495. * @return array
  496. */
  497. public function validate()
  498. {
  499. $this->_eventManager->dispatch($this->_eventPrefix . '_validate_before', $this->_getEventData());
  500. $result = $this->_getResource()->validate($this);
  501. $this->_eventManager->dispatch($this->_eventPrefix . '_validate_after', $this->_getEventData());
  502. return $result;
  503. }
  504. /**
  505. * Get product name
  506. *
  507. * @return string
  508. * @codeCoverageIgnoreStart
  509. */
  510. public function getName()
  511. {
  512. return $this->_getData(self::NAME);
  513. }
  514. //@codeCoverageIgnoreEnd
  515. /**
  516. * Get product price through type instance
  517. *
  518. * @return float
  519. */
  520. public function getPrice()
  521. {
  522. if ($this->_calculatePrice || !$this->getData(self::PRICE)) {
  523. return $this->getPriceModel()->getPrice($this);
  524. } else {
  525. return $this->getData(self::PRICE);
  526. }
  527. }
  528. /**
  529. * Get visibility status
  530. *
  531. * @codeCoverageIgnoreStart
  532. * @see \Magento\Catalog\Model\Product\Visibility
  533. *
  534. * @return int
  535. */
  536. public function getVisibility()
  537. {
  538. return $this->_getData(self::VISIBILITY);
  539. }
  540. /**
  541. * Get product attribute set id
  542. *
  543. * @return int
  544. */
  545. public function getAttributeSetId()
  546. {
  547. return $this->_getData(self::ATTRIBUTE_SET_ID);
  548. }
  549. /**
  550. * Get product creation date
  551. *
  552. * @return string
  553. */
  554. public function getCreatedAt()
  555. {
  556. return $this->_getData(self::CREATED_AT);
  557. }
  558. /**
  559. * Get previous product update date
  560. *
  561. * @return string
  562. */
  563. public function getUpdatedAt()
  564. {
  565. return $this->_getData(self::UPDATED_AT);
  566. }
  567. /**
  568. * Set Price calculation flag
  569. *
  570. * @param bool $calculate
  571. * @return void
  572. * @deprecated 102.0.4
  573. */
  574. public function setPriceCalculation($calculate = true)
  575. {
  576. $this->_calculatePrice = $calculate;
  577. }
  578. /**
  579. * Get product type identifier
  580. *
  581. * @return array|string
  582. */
  583. public function getTypeId()
  584. {
  585. return $this->_getData(self::TYPE_ID);
  586. }
  587. //@codeCoverageIgnoreEnd
  588. /**
  589. * Get product status
  590. *
  591. * @return int
  592. */
  593. public function getStatus()
  594. {
  595. $status = $this->_getData(self::STATUS);
  596. return $status !== null ? $status : \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED;
  597. }
  598. /**
  599. * Retrieve type instance of the product.
  600. *
  601. * Type instance implements product type depended logic and is a singleton shared by all products of the same type.
  602. *
  603. * @return \Magento\Catalog\Model\Product\Type\AbstractType
  604. */
  605. public function getTypeInstance()
  606. {
  607. if ($this->_typeInstance === null) {
  608. $this->_typeInstance = $this->_catalogProductType->factory($this);
  609. }
  610. return $this->_typeInstance;
  611. }
  612. /**
  613. * Set type instance for the product
  614. *
  615. * @param \Magento\Catalog\Model\Product\Type\AbstractType|null $instance Product type instance
  616. * @return \Magento\Catalog\Model\Product
  617. */
  618. public function setTypeInstance($instance)
  619. {
  620. $this->_typeInstance = $instance;
  621. return $this;
  622. }
  623. /**
  624. * Retrieve link instance
  625. *
  626. * @return Product\Link
  627. */
  628. public function getLinkInstance()
  629. {
  630. return $this->_linkInstance;
  631. }
  632. /**
  633. * Retrieve product id by sku
  634. *
  635. * @param string $sku
  636. * @return integer
  637. */
  638. public function getIdBySku($sku)
  639. {
  640. return $this->_getResource()->getIdBySku($sku);
  641. }
  642. /**
  643. * Retrieve product category id
  644. *
  645. * @return int
  646. */
  647. public function getCategoryId()
  648. {
  649. $category = $this->_registry->registry('current_category');
  650. if ($category && in_array($category->getId(), $this->getCategoryIds())) {
  651. return $category->getId();
  652. }
  653. return false;
  654. }
  655. /**
  656. * Retrieve product category
  657. *
  658. * @return \Magento\Catalog\Model\Category
  659. */
  660. public function getCategory()
  661. {
  662. $category = $this->getData('category');
  663. if ($category === null && $this->getCategoryId()) {
  664. $category = $this->categoryRepository->get($this->getCategoryId());
  665. $this->setCategory($category);
  666. }
  667. return $category;
  668. }
  669. /**
  670. * Retrieve assigned category Ids
  671. *
  672. * @return array
  673. */
  674. public function getCategoryIds()
  675. {
  676. if (!$this->hasData('category_ids')) {
  677. $wasLocked = false;
  678. if ($this->isLockedAttribute('category_ids')) {
  679. $wasLocked = true;
  680. $this->unlockAttribute('category_ids');
  681. }
  682. $ids = $this->_getResource()->getCategoryIds($this);
  683. $this->setData('category_ids', $ids);
  684. if ($wasLocked) {
  685. $this->lockAttribute('category_ids');
  686. }
  687. }
  688. return (array) $this->_getData('category_ids');
  689. }
  690. /**
  691. * Retrieve product categories
  692. *
  693. * @return \Magento\Framework\Data\Collection
  694. */
  695. public function getCategoryCollection()
  696. {
  697. if ($this->categoryCollection === null || $this->getId() != $this->_productIdCached) {
  698. $categoryCollection = $this->_getResource()->getCategoryCollection($this);
  699. $this->setCategoryCollection($categoryCollection);
  700. $this->_productIdCached = $this->getId();
  701. }
  702. return $this->categoryCollection;
  703. }
  704. /**
  705. * Set product categories.
  706. *
  707. * @param \Magento\Framework\Data\Collection $categoryCollection
  708. * @return $this
  709. */
  710. protected function setCategoryCollection(\Magento\Framework\Data\Collection $categoryCollection)
  711. {
  712. $this->categoryCollection = $categoryCollection;
  713. return $this;
  714. }
  715. /**
  716. * Retrieve product websites identifiers
  717. *
  718. * @return array
  719. */
  720. public function getWebsiteIds()
  721. {
  722. if (!$this->hasWebsiteIds()) {
  723. $ids = $this->_getResource()->getWebsiteIds($this);
  724. $this->setWebsiteIds($ids);
  725. }
  726. return $this->getData('website_ids');
  727. }
  728. /**
  729. * Get all sore ids where product is presented
  730. *
  731. * @return array
  732. */
  733. public function getStoreIds()
  734. {
  735. if (!$this->hasStoreIds()) {
  736. $storeIds = [];
  737. if ($websiteIds = $this->getWebsiteIds()) {
  738. if ($this->_storeManager->isSingleStoreMode()) {
  739. $websiteIds = array_keys($websiteIds);
  740. }
  741. foreach ($websiteIds as $websiteId) {
  742. $websiteStores = $this->_storeManager->getWebsite($websiteId)->getStoreIds();
  743. $storeIds = array_merge($storeIds, $websiteStores);
  744. }
  745. }
  746. $this->setStoreIds($storeIds);
  747. }
  748. return $this->getData('store_ids');
  749. }
  750. /**
  751. * Retrieve product attributes
  752. *
  753. * If $groupId is null - retrieve all product attributes
  754. *
  755. * @param int $groupId Retrieve attributes of the specified group
  756. * @param bool $skipSuper Not used
  757. * @return \Magento\Eav\Model\Entity\Attribute\AbstractAttribute[]
  758. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  759. */
  760. public function getAttributes($groupId = null, $skipSuper = false)
  761. {
  762. $productAttributes = $this->getTypeInstance()->getSetAttributes($this);
  763. if ($groupId) {
  764. $attributes = [];
  765. foreach ($productAttributes as $attribute) {
  766. if ($attribute->isInGroup($this->getAttributeSetId(), $groupId)) {
  767. $attributes[] = $attribute;
  768. }
  769. }
  770. } else {
  771. $attributes = $productAttributes;
  772. }
  773. return $attributes;
  774. }
  775. /**
  776. * Check product options and type options and save them, too
  777. *
  778. * @return void
  779. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  780. * @SuppressWarnings(PHPMD.NPathComplexity)
  781. */
  782. public function beforeSave()
  783. {
  784. $this->cleanCache();
  785. $this->setTypeHasOptions(false);
  786. $this->setTypeHasRequiredOptions(false);
  787. $this->setHasOptions(false);
  788. $this->setRequiredOptions(false);
  789. $this->getTypeInstance()->beforeSave($this);
  790. $hasOptions = false;
  791. $hasRequiredOptions = false;
  792. /**
  793. * $this->_canAffectOptions - set by type instance only
  794. * $this->getCanSaveCustomOptions() - set either in controller when "Custom Options" ajax tab is loaded,
  795. * or in type instance as well
  796. */
  797. $this->canAffectOptions($this->_canAffectOptions && $this->getCanSaveCustomOptions());
  798. if ($this->getCanSaveCustomOptions()) {
  799. $options = $this->getOptions();
  800. if (is_array($options)) {
  801. $this->setIsCustomOptionChanged(true);
  802. foreach ($options as $option) {
  803. if ($option instanceof \Magento\Catalog\Api\Data\ProductCustomOptionInterface) {
  804. $option = $option->getData();
  805. }
  806. if (!isset($option['is_delete']) || $option['is_delete'] != '1') {
  807. $hasOptions = true;
  808. }
  809. if ($option['is_require'] == '1') {
  810. $hasRequiredOptions = true;
  811. break;
  812. }
  813. }
  814. }
  815. }
  816. /**
  817. * Set true, if any
  818. * Set false, ONLY if options have been affected by Options tab and Type instance tab
  819. */
  820. if ($hasOptions || (bool)$this->getTypeHasOptions()) {
  821. $this->setHasOptions(true);
  822. if ($hasRequiredOptions || (bool)$this->getTypeHasRequiredOptions()) {
  823. $this->setRequiredOptions(true);
  824. } elseif ($this->canAffectOptions()) {
  825. $this->setRequiredOptions(false);
  826. }
  827. } elseif ($this->canAffectOptions()) {
  828. $this->setHasOptions(false);
  829. $this->setRequiredOptions(false);
  830. }
  831. if (!$this->getOrigData('website_ids')) {
  832. $websiteIds = $this->_getResource()->getWebsiteIds($this);
  833. $this->setOrigData('website_ids', $websiteIds);
  834. }
  835. parent::beforeSave();
  836. }
  837. /**
  838. * Check/set if options can be affected when saving product
  839. *
  840. * If value specified, it will be set.
  841. *
  842. * @param bool $value
  843. * @return bool
  844. */
  845. public function canAffectOptions($value = null)
  846. {
  847. if (null !== $value) {
  848. $this->_canAffectOptions = (bool) $value;
  849. }
  850. return $this->_canAffectOptions;
  851. }
  852. /**
  853. * Saving product type related data and init index
  854. *
  855. * @return \Magento\Catalog\Model\Product
  856. */
  857. public function afterSave()
  858. {
  859. $this->getLinkInstance()->saveProductRelations($this);
  860. $this->getTypeInstance()->save($this);
  861. if ($this->getStockData()) {
  862. $this->setForceReindexEavRequired(true);
  863. }
  864. $this->_getResource()->addCommitCallback([$this, 'priceReindexCallback']);
  865. $this->_getResource()->addCommitCallback([$this, 'eavReindexCallback']);
  866. $result = parent::afterSave();
  867. $this->_getResource()->addCommitCallback([$this, 'reindex']);
  868. $this->reloadPriceInfo();
  869. return $result;
  870. }
  871. /**
  872. * Set quantity for product
  873. *
  874. * @param float $qty
  875. * @return $this
  876. */
  877. public function setQty($qty)
  878. {
  879. if ($this->getData('qty') != $qty) {
  880. $this->setData('qty', $qty);
  881. $this->reloadPriceInfo();
  882. }
  883. return $this;
  884. }
  885. /**
  886. * Get quantity for product
  887. *
  888. * @return float
  889. */
  890. public function getQty()
  891. {
  892. return (float)$this->getData('qty');
  893. }
  894. /**
  895. * Callback for entity reindex
  896. *
  897. * @return void
  898. */
  899. public function priceReindexCallback()
  900. {
  901. if ($this->isObjectNew() || $this->_catalogProduct->isDataForPriceIndexerWasChanged($this)) {
  902. $this->_productPriceIndexerProcessor->reindexRow($this->getEntityId());
  903. }
  904. }
  905. /**
  906. * Reindex callback for EAV indexer
  907. *
  908. * @return void
  909. */
  910. public function eavReindexCallback()
  911. {
  912. if ($this->isObjectNew() || $this->isDataChanged($this)) {
  913. $this->_productEavIndexerProcessor->reindexRow($this->getEntityId());
  914. }
  915. }
  916. /**
  917. * Check if data was changed
  918. *
  919. * @return bool
  920. */
  921. public function isDataChanged()
  922. {
  923. foreach (array_keys($this->getData()) as $field) {
  924. if ($this->dataHasChangedFor($field)) {
  925. return true;
  926. }
  927. }
  928. return false;
  929. }
  930. /**
  931. * Init indexing process after product save
  932. *
  933. * @return void
  934. */
  935. public function reindex()
  936. {
  937. if ($this->_catalogProduct->isDataForProductCategoryIndexerWasChanged($this) || $this->isDeleted()) {
  938. $productCategoryIndexer = $this->indexerRegistry->get(Indexer\Product\Category::INDEXER_ID);
  939. if (!$productCategoryIndexer->isScheduled()) {
  940. $productCategoryIndexer->reindexRow($this->getId());
  941. }
  942. }
  943. $this->_productFlatIndexerProcessor->reindexRow($this->getEntityId());
  944. }
  945. /**
  946. * Clear cache related with product and protect delete from not admin
  947. *
  948. * Register indexing event before delete product
  949. *
  950. * @return \Magento\Catalog\Model\Product
  951. * @throws \Magento\Framework\Exception\LocalizedException
  952. */
  953. public function beforeDelete()
  954. {
  955. $this->cleanCache();
  956. return parent::beforeDelete();
  957. }
  958. /**
  959. * Init indexing process after product delete commit
  960. *
  961. * @return void
  962. */
  963. public function afterDeleteCommit()
  964. {
  965. $this->reindex();
  966. $this->_productPriceIndexerProcessor->reindexRow($this->getId());
  967. parent::afterDeleteCommit();
  968. }
  969. /**
  970. * Load product options if they exists
  971. *
  972. * @return $this
  973. */
  974. protected function _afterLoad()
  975. {
  976. if (!$this->hasData(self::STATUS)) {
  977. $this->setData(self::STATUS, \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
  978. }
  979. parent::_afterLoad();
  980. return $this;
  981. }
  982. /**
  983. * Clear cache related with product id
  984. *
  985. * @return $this
  986. */
  987. public function cleanCache()
  988. {
  989. $this->_cacheManager->clean('catalog_product_' . $this->getId());
  990. return $this;
  991. }
  992. /**
  993. * Get product price model
  994. *
  995. * @return \Magento\Catalog\Model\Product\Type\Price
  996. */
  997. public function getPriceModel()
  998. {
  999. return $this->_catalogProductType->priceFactory($this->getTypeId());
  1000. }
  1001. /**
  1002. * Get product Price Info object
  1003. *
  1004. * @return \Magento\Framework\Pricing\PriceInfo\Base
  1005. */
  1006. public function getPriceInfo()
  1007. {
  1008. if (!$this->_priceInfo) {
  1009. $this->_priceInfo = $this->_catalogProductType->getPriceInfo($this);
  1010. }
  1011. return $this->_priceInfo;
  1012. }
  1013. /**
  1014. * Gets list of product tier prices
  1015. *
  1016. * @return \Magento\Catalog\Api\Data\ProductTierPriceInterface[]|null
  1017. */
  1018. public function getTierPrices()
  1019. {
  1020. return $this->getPriceModel()->getTierPrices($this);
  1021. }
  1022. /**
  1023. * Sets list of product tier prices
  1024. *
  1025. * @param \Magento\Catalog\Api\Data\ProductTierPriceInterface[] $tierPrices
  1026. * @return $this
  1027. */
  1028. public function setTierPrices(array $tierPrices = null)
  1029. {
  1030. $this->getPriceModel()->setTierPrices($this, $tierPrices);
  1031. return $this;
  1032. }
  1033. /**
  1034. * Get product tier price for the customer, based on qty of this product
  1035. *
  1036. * @param float $qty
  1037. * @return float|array
  1038. */
  1039. public function getTierPrice($qty = null)
  1040. {
  1041. return $this->getPriceModel()->getTierPrice($qty, $this);
  1042. }
  1043. /**
  1044. * Get formatted by currency product price
  1045. *
  1046. * @return array|double
  1047. * @since 102.0.6
  1048. */
  1049. public function getFormattedPrice()
  1050. {
  1051. return $this->getPriceModel()->getFormattedPrice($this);
  1052. }
  1053. /**
  1054. * Get formatted by currency product price
  1055. *
  1056. * @return array|double
  1057. *
  1058. * @deprecated 102.0.6
  1059. * @see getFormattedPrice()
  1060. */
  1061. public function getFormatedPrice()
  1062. {
  1063. return $this->getFormattedPrice();
  1064. }
  1065. /**
  1066. * Sets final price of product
  1067. *
  1068. * This func is equal to magic 'setFinalPrice()', but added as a separate func, because in cart with bundle
  1069. * products it's called very often in Item->getProduct(). So removing chain of magic with more cpu consuming
  1070. * algorithms gives nice optimization boost.
  1071. *
  1072. * @param float $price Price amount
  1073. * @return \Magento\Catalog\Model\Product
  1074. */
  1075. public function setFinalPrice($price)
  1076. {
  1077. $this->_data['final_price'] = $price;
  1078. return $this;
  1079. }
  1080. /**
  1081. * Get product final price
  1082. *
  1083. * @param float $qty
  1084. * @return float
  1085. */
  1086. public function getFinalPrice($qty = null)
  1087. {
  1088. if ($this->_calculatePrice || $this->_getData('final_price') === null) {
  1089. return $this->getPriceModel()->getFinalPrice($qty, $this);
  1090. } else {
  1091. return $this->_getData('final_price');
  1092. }
  1093. }
  1094. /**
  1095. * Returns calculated final price
  1096. *
  1097. * @return float
  1098. */
  1099. public function getCalculatedFinalPrice()
  1100. {
  1101. return $this->_getData('calculated_final_price');
  1102. }
  1103. /**
  1104. * Returns minimal price
  1105. *
  1106. * @return float
  1107. */
  1108. public function getMinimalPrice()
  1109. {
  1110. return max($this->_getData('minimal_price'), 0);
  1111. }
  1112. /**
  1113. * Returns special price
  1114. *
  1115. * @return float
  1116. */
  1117. public function getSpecialPrice()
  1118. {
  1119. return $this->_getData('special_price');
  1120. }
  1121. /**
  1122. * Returns starting date of the special price
  1123. *
  1124. * @return mixed
  1125. */
  1126. public function getSpecialFromDate()
  1127. {
  1128. return $this->_getData('special_from_date');
  1129. }
  1130. /**
  1131. * Returns end date of the special price
  1132. *
  1133. * @return mixed
  1134. */
  1135. public function getSpecialToDate()
  1136. {
  1137. return $this->_getData('special_to_date');
  1138. }
  1139. /**
  1140. * Retrieve array of related products
  1141. *
  1142. * @return array
  1143. */
  1144. public function getRelatedProducts()
  1145. {
  1146. if (!$this->hasRelatedProducts()) {
  1147. $products = [];
  1148. $collection = $this->getRelatedProductCollection();
  1149. foreach ($collection as $product) {
  1150. $products[] = $product;
  1151. }
  1152. $this->setRelatedProducts($products);
  1153. }
  1154. return $this->getData('related_products');
  1155. }
  1156. /**
  1157. * Retrieve related products identifiers
  1158. *
  1159. * @return array
  1160. */
  1161. public function getRelatedProductIds()
  1162. {
  1163. if (!$this->hasRelatedProductIds()) {
  1164. $ids = [];
  1165. foreach ($this->getRelatedProducts() as $product) {
  1166. $ids[] = $product->getId();
  1167. }
  1168. $this->setRelatedProductIds($ids);
  1169. }
  1170. return $this->getData('related_product_ids');
  1171. }
  1172. /**
  1173. * Retrieve collection related product
  1174. *
  1175. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection
  1176. */
  1177. public function getRelatedProductCollection()
  1178. {
  1179. $collection = $this->getLinkInstance()->useRelatedLinks()->getProductCollection()->setIsStrongMode();
  1180. $collection->setProduct($this);
  1181. return $collection;
  1182. }
  1183. /**
  1184. * Retrieve collection related link
  1185. *
  1186. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Collection
  1187. */
  1188. public function getRelatedLinkCollection()
  1189. {
  1190. $collection = $this->getLinkInstance()->useRelatedLinks()->getLinkCollection();
  1191. $collection->setProduct($this);
  1192. $collection->addLinkTypeIdFilter();
  1193. $collection->addProductIdFilter();
  1194. $collection->joinAttributes();
  1195. return $collection;
  1196. }
  1197. /**
  1198. * Retrieve array of up sell products
  1199. *
  1200. * @return array
  1201. */
  1202. public function getUpSellProducts()
  1203. {
  1204. if (!$this->hasUpSellProducts()) {
  1205. $products = [];
  1206. foreach ($this->getUpSellProductCollection() as $product) {
  1207. $products[] = $product;
  1208. }
  1209. $this->setUpSellProducts($products);
  1210. }
  1211. return $this->getData('up_sell_products');
  1212. }
  1213. /**
  1214. * Retrieve up sell products identifiers
  1215. *
  1216. * @return array
  1217. */
  1218. public function getUpSellProductIds()
  1219. {
  1220. if (!$this->hasUpSellProductIds()) {
  1221. $ids = [];
  1222. foreach ($this->getUpSellProducts() as $product) {
  1223. $ids[] = $product->getId();
  1224. }
  1225. $this->setUpSellProductIds($ids);
  1226. }
  1227. return $this->getData('up_sell_product_ids');
  1228. }
  1229. /**
  1230. * Retrieve collection up sell product
  1231. *
  1232. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection
  1233. */
  1234. public function getUpSellProductCollection()
  1235. {
  1236. $collection = $this->getLinkInstance()->useUpSellLinks()->getProductCollection()->setIsStrongMode();
  1237. $collection->setProduct($this);
  1238. return $collection;
  1239. }
  1240. /**
  1241. * Retrieve collection up sell link
  1242. *
  1243. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Collection
  1244. */
  1245. public function getUpSellLinkCollection()
  1246. {
  1247. $collection = $this->getLinkInstance()->useUpSellLinks()->getLinkCollection();
  1248. $collection->setProduct($this);
  1249. $collection->addLinkTypeIdFilter();
  1250. $collection->addProductIdFilter();
  1251. $collection->joinAttributes();
  1252. return $collection;
  1253. }
  1254. /**
  1255. * Retrieve array of cross sell products
  1256. *
  1257. * @return array
  1258. */
  1259. public function getCrossSellProducts()
  1260. {
  1261. if (!$this->hasCrossSellProducts()) {
  1262. $products = [];
  1263. foreach ($this->getCrossSellProductCollection() as $product) {
  1264. $products[] = $product;
  1265. }
  1266. $this->setCrossSellProducts($products);
  1267. }
  1268. return $this->getData('cross_sell_products');
  1269. }
  1270. /**
  1271. * Retrieve cross sell products identifiers
  1272. *
  1273. * @return array
  1274. */
  1275. public function getCrossSellProductIds()
  1276. {
  1277. if (!$this->hasCrossSellProductIds()) {
  1278. $ids = [];
  1279. foreach ($this->getCrossSellProducts() as $product) {
  1280. $ids[] = $product->getId();
  1281. }
  1282. $this->setCrossSellProductIds($ids);
  1283. }
  1284. return $this->getData('cross_sell_product_ids');
  1285. }
  1286. /**
  1287. * Retrieve collection cross sell product
  1288. *
  1289. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection
  1290. */
  1291. public function getCrossSellProductCollection()
  1292. {
  1293. $collection = $this->getLinkInstance()->useCrossSellLinks()->getProductCollection()->setIsStrongMode();
  1294. $collection->setProduct($this);
  1295. return $collection;
  1296. }
  1297. /**
  1298. * Retrieve collection cross sell link
  1299. *
  1300. * @return \Magento\Catalog\Model\ResourceModel\Product\Link\Collection
  1301. */
  1302. public function getCrossSellLinkCollection()
  1303. {
  1304. $collection = $this->getLinkInstance()->useCrossSellLinks()->getLinkCollection();
  1305. $collection->setProduct($this);
  1306. $collection->addLinkTypeIdFilter();
  1307. $collection->addProductIdFilter();
  1308. $collection->joinAttributes();
  1309. return $collection;
  1310. }
  1311. /**
  1312. * Get product links info
  1313. *
  1314. * @return \Magento\Catalog\Api\Data\ProductLinkInterface[]
  1315. */
  1316. public function getProductLinks()
  1317. {
  1318. if ($this->_links === null) {
  1319. $this->_links = $this->getLinkRepository()->getList($this);
  1320. }
  1321. return $this->_links;
  1322. }
  1323. /**
  1324. * Set product links info
  1325. *
  1326. * @param \Magento\Catalog\Api\Data\ProductLinkInterface[] $links
  1327. * @return $this
  1328. */
  1329. public function setProductLinks(array $links = null)
  1330. {
  1331. if ($links === null) {
  1332. $this->setData('ignore_links_flag', true);
  1333. } else {
  1334. $this->setData('ignore_links_flag', false);
  1335. }
  1336. $this->_links = $links;
  1337. return $this;
  1338. }
  1339. /**
  1340. * Retrieve attributes for media gallery
  1341. *
  1342. * @return array
  1343. */
  1344. public function getMediaAttributes()
  1345. {
  1346. if (!$this->hasMediaAttributes()) {
  1347. $mediaAttributes = [];
  1348. foreach ($this->getAttributes() as $attribute) {
  1349. if ($attribute->getFrontend()->getInputType() == 'media_image') {
  1350. $mediaAttributes[$attribute->getAttributeCode()] = $attribute;
  1351. }
  1352. }
  1353. $this->setMediaAttributes($mediaAttributes);
  1354. }
  1355. return $this->getData('media_attributes');
  1356. }
  1357. /**
  1358. * Retrieve assoc array that contains media attribute values of the product
  1359. *
  1360. * @return array
  1361. */
  1362. public function getMediaAttributeValues()
  1363. {
  1364. $mediaAttributeCodes = $this->_catalogProductMediaConfig->getMediaAttributeCodes();
  1365. $mediaAttributeValues = [];
  1366. foreach ($mediaAttributeCodes as $attributeCode) {
  1367. $mediaAttributeValues[$attributeCode] = $this->getData($attributeCode);
  1368. }
  1369. return $mediaAttributeValues;
  1370. }
  1371. /**
  1372. * Retrieve media gallery images
  1373. *
  1374. * @return \Magento\Framework\Data\Collection
  1375. */
  1376. public function getMediaGalleryImages()
  1377. {
  1378. $directory = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA);
  1379. if (!$this->hasData('media_gallery_images')) {
  1380. $this->setData('media_gallery_images', $this->_collectionFactory->create());
  1381. }
  1382. if (!$this->getData('media_gallery_images')->count() && is_array($this->getMediaGallery('images'))) {
  1383. $images = $this->getData('media_gallery_images');
  1384. foreach ($this->getMediaGallery('images') as $image) {
  1385. if (!empty($image['disabled'])
  1386. || !empty($image['removed'])
  1387. || empty($image['value_id'])
  1388. || $images->getItemById($image['value_id']) != null
  1389. ) {
  1390. continue;
  1391. }
  1392. $image['url'] = $this->getMediaConfig()->getMediaUrl($image['file']);
  1393. $image['id'] = $image['value_id'];
  1394. $image['path'] = $directory->getAbsolutePath($this->getMediaConfig()->getMediaPath($image['file']));
  1395. $images->addItem(new \Magento\Framework\DataObject($image));
  1396. }
  1397. $this->setData('media_gallery_images', $images);
  1398. }
  1399. return $this->getData('media_gallery_images');
  1400. }
  1401. /**
  1402. * Checks whether product has Media Gallery attribute.
  1403. *
  1404. * @return bool
  1405. * @since 101.0.0
  1406. */
  1407. public function hasGalleryAttribute()
  1408. {
  1409. $attributes = $this->getAttributes();
  1410. if (!isset($attributes['media_gallery'])
  1411. || !($attributes['media_gallery'] instanceof \Magento\Eav\Model\Entity\Attribute\AbstractAttribute)
  1412. ) {
  1413. return false;
  1414. }
  1415. return true;
  1416. }
  1417. /**
  1418. * Add image to media gallery
  1419. *
  1420. * @param string $file file path of image in file system
  1421. * @param string|array $mediaAttribute code of attribute with type 'media_image',
  1422. * leave blank if image should be only in gallery
  1423. * @param bool $move if true, it will move source file
  1424. * @param bool $exclude mark image as disabled in product page view
  1425. * @return \Magento\Catalog\Model\Product
  1426. * @throws \Magento\Framework\Exception\LocalizedException
  1427. */
  1428. public function addImageToMediaGallery($file, $mediaAttribute = null, $move = false, $exclude = true)
  1429. {
  1430. if ($this->hasGalleryAttribute()) {
  1431. $this->getMediaGalleryProcessor()->addImage(
  1432. $this,
  1433. $file,
  1434. $mediaAttribute,
  1435. $move,
  1436. $exclude
  1437. );
  1438. }
  1439. return $this;
  1440. }
  1441. /**
  1442. * Retrieve product media config
  1443. *
  1444. * @return Product\Media\Config
  1445. */
  1446. public function getMediaConfig()
  1447. {
  1448. return $this->_catalogProductMediaConfig;
  1449. }
  1450. /**
  1451. * Returns visible status IDs in catalog
  1452. *
  1453. * @return array
  1454. */
  1455. public function getVisibleInCatalogStatuses()
  1456. {
  1457. return $this->_catalogProductStatus->getVisibleStatusIds();
  1458. }
  1459. /**
  1460. * Retrieve visible statuses
  1461. *
  1462. * @return array
  1463. */
  1464. public function getVisibleStatuses()
  1465. {
  1466. return $this->_catalogProductStatus->getVisibleStatusIds();
  1467. }
  1468. /**
  1469. * Check Product visible in catalog
  1470. *
  1471. * @return bool
  1472. */
  1473. public function isVisibleInCatalog()
  1474. {
  1475. return in_array($this->getStatus(), $this->getVisibleInCatalogStatuses());
  1476. }
  1477. /**
  1478. * Retrieve visible in site visibilities
  1479. *
  1480. * @return array
  1481. */
  1482. public function getVisibleInSiteVisibilities()
  1483. {
  1484. return $this->_catalogProductVisibility->getVisibleInSiteIds();
  1485. }
  1486. /**
  1487. * Check Product visible in site
  1488. *
  1489. * @return bool
  1490. */
  1491. public function isVisibleInSiteVisibility()
  1492. {
  1493. return in_array($this->getVisibility(), $this->getVisibleInSiteVisibilities());
  1494. }
  1495. /**
  1496. * Checks product can be duplicated
  1497. *
  1498. * @return boolean
  1499. */
  1500. public function isDuplicable()
  1501. {
  1502. return $this->_isDuplicable;
  1503. }
  1504. /**
  1505. * Set is duplicable flag
  1506. *
  1507. * @param boolean $value
  1508. * @return \Magento\Catalog\Model\Product
  1509. */
  1510. public function setIsDuplicable($value)
  1511. {
  1512. $this->_isDuplicable = (bool)$value;
  1513. return $this;
  1514. }
  1515. /**
  1516. * Check is product available for sale
  1517. *
  1518. * @return bool
  1519. */
  1520. public function isSalable()
  1521. {
  1522. if ($this->_catalogProduct->getSkipSaleableCheck()) {
  1523. return true;
  1524. }
  1525. if (($this->getOrigData('status') != $this->getData('status'))
  1526. || $this->isStockStatusChanged()) {
  1527. $this->unsetData('salable');
  1528. }
  1529. if ($this->hasData('salable')) {
  1530. return $this->getData('salable');
  1531. }
  1532. $this->_eventManager->dispatch('catalog_product_is_salable_before', ['product' => $this]);
  1533. $salable = $this->isAvailable();
  1534. $object = new \Magento\Framework\DataObject(['product' => $this, 'is_salable' => $salable]);
  1535. $this->_eventManager->dispatch(
  1536. 'catalog_product_is_salable_after',
  1537. ['product' => $this, 'salable' => $object]
  1538. );
  1539. $this->setData('salable', $object->getIsSalable());
  1540. return $this->getData('salable');
  1541. }
  1542. /**
  1543. * Check whether the product type or stock allows to purchase the product
  1544. *
  1545. * @return bool
  1546. */
  1547. public function isAvailable()
  1548. {
  1549. return $this->_catalogProduct->getSkipSaleableCheck() || $this->getTypeInstance()->isSalable($this);
  1550. }
  1551. /**
  1552. * Is product salable detecting by product type
  1553. *
  1554. * @return bool
  1555. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  1556. */
  1557. public function getIsSalable()
  1558. {
  1559. $productType = $this->getTypeInstance();
  1560. if (method_exists($productType, 'getIsSalable')) {
  1561. return $productType->getIsSalable($this);
  1562. }
  1563. if ($this->hasData('is_saleable')) {
  1564. return $this->getData('is_saleable');
  1565. }
  1566. return $this->isSalable();
  1567. }
  1568. /**
  1569. * Check is a virtual product
  1570. *
  1571. * @return bool
  1572. */
  1573. public function isVirtual()
  1574. {
  1575. return $this->getIsVirtual();
  1576. }
  1577. /**
  1578. * Alias for isSalable()
  1579. *
  1580. * @return bool
  1581. */
  1582. public function isSaleable()
  1583. {
  1584. return $this->isSalable();
  1585. }
  1586. /**
  1587. * Whether product available in stock
  1588. *
  1589. * @return bool
  1590. */
  1591. public function isInStock()
  1592. {
  1593. return $this->getStatus() == \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED;
  1594. }
  1595. /**
  1596. * Get attribute text by its code
  1597. *
  1598. * @param string $attributeCode Code of the attribute
  1599. * @return string|array|null
  1600. */
  1601. public function getAttributeText($attributeCode)
  1602. {
  1603. return $this->getResource()->getAttribute($attributeCode)->getSource()->getOptionText(
  1604. $this->getData($attributeCode)
  1605. );
  1606. }
  1607. /**
  1608. * Returns array with dates for custom design
  1609. *
  1610. * @return array
  1611. */
  1612. public function getCustomDesignDate()
  1613. {
  1614. $result = [];
  1615. $result['from'] = $this->getData('custom_design_from');
  1616. $result['to'] = $this->getData('custom_design_to');
  1617. return $result;
  1618. }
  1619. /**
  1620. * Retrieve Product URL
  1621. *
  1622. * @param bool $useSid
  1623. * @return string
  1624. */
  1625. public function getProductUrl($useSid = null)
  1626. {
  1627. return $this->getUrlModel()->getProductUrl($this, $useSid);
  1628. }
  1629. /**
  1630. * Retrieve URL in current store
  1631. *
  1632. * @param array $params the route params
  1633. * @return string
  1634. */
  1635. public function getUrlInStore($params = [])
  1636. {
  1637. return $this->getUrlModel()->getUrlInStore($this, $params);
  1638. }
  1639. /**
  1640. * Formats URL key
  1641. *
  1642. * @param string $str URL
  1643. * @return string
  1644. */
  1645. public function formatUrlKey($str)
  1646. {
  1647. return $this->getUrlModel()->formatUrlKey($str);
  1648. }
  1649. /**
  1650. * Save current attribute with code $code and assign new value
  1651. *
  1652. * @param string $code Attribute code
  1653. * @param mixed $value New attribute value
  1654. * @param int $store Store ID
  1655. * @return void
  1656. */
  1657. public function addAttributeUpdate($code, $value, $store)
  1658. {
  1659. $oldValue = $this->getData($code);
  1660. $oldStore = $this->getStoreId();
  1661. $this->setData($code, $value);
  1662. $this->setStoreId($store);
  1663. $this->getResource()->saveAttribute($this, $code);
  1664. $this->setData($code, $oldValue);
  1665. $this->setStoreId($oldStore);
  1666. }
  1667. /**
  1668. * Renders the object to array
  1669. *
  1670. * @param array $arrAttributes Attribute array
  1671. * @return array
  1672. */
  1673. public function toArray(array $arrAttributes = [])
  1674. {
  1675. $data = parent::toArray($arrAttributes);
  1676. $stock = $this->getStockItem();
  1677. if ($stock) {
  1678. $data['stock_item'] = $stock->toArray();
  1679. }
  1680. unset($data['stock_item']['product']);
  1681. return $data;
  1682. }
  1683. /**
  1684. * Same as setData(), but also initiates the stock item (if it is there)
  1685. *
  1686. * @param array $data Array to form the object from
  1687. * @return \Magento\Catalog\Model\Product
  1688. */
  1689. public function fromArray(array $data)
  1690. {
  1691. if (isset($data['stock_item'])) {
  1692. if ($this->moduleManager->isEnabled('Magento_CatalogInventory')) {
  1693. $stockItem = $this->_stockItemFactory->create();
  1694. $this->dataObjectHelper->populateWithArray(
  1695. $stockItem,
  1696. $data['stock_item'],
  1697. \Magento\CatalogInventory\Api\Data\StockItemInterface::class
  1698. );
  1699. $stockItem->setProduct($this);
  1700. $this->setStockItem($stockItem);
  1701. }
  1702. unset($data['stock_item']);
  1703. }
  1704. $this->setData($data);
  1705. return $this;
  1706. }
  1707. /**
  1708. * Returns request path
  1709. *
  1710. * @return string
  1711. */
  1712. public function getRequestPath()
  1713. {
  1714. return $this->_getData('request_path');
  1715. }
  1716. /**
  1717. * Custom function for other modules
  1718. *
  1719. * @return string
  1720. */
  1721. public function getGiftMessageAvailable()
  1722. {
  1723. return $this->_getData('gift_message_available');
  1724. }
  1725. /**
  1726. * Check is product composite
  1727. *
  1728. * @return bool
  1729. */
  1730. public function isComposite()
  1731. {
  1732. return $this->getTypeInstance()->isComposite($this);
  1733. }
  1734. /**
  1735. * Check if product can be configured
  1736. *
  1737. * @return bool
  1738. */
  1739. public function canConfigure()
  1740. {
  1741. $options = $this->getOptions();
  1742. return !empty($options) || $this->getTypeInstance()->canConfigure($this);
  1743. }
  1744. /**
  1745. * Retrieve sku through type instance
  1746. *
  1747. * @return string
  1748. */
  1749. public function getSku()
  1750. {
  1751. return $this->getTypeInstance()->getSku($this);
  1752. }
  1753. /**
  1754. * Retrieve weight through type instance
  1755. *
  1756. * @return float
  1757. */
  1758. public function getWeight()
  1759. {
  1760. return $this->getTypeInstance()->getWeight($this);
  1761. }
  1762. /**
  1763. * Retrieve option instance
  1764. *
  1765. * @return Product\Option
  1766. */
  1767. public function getOptionInstance()
  1768. {
  1769. if (!isset($this->optionInstance)) {
  1770. $this->optionInstance = $this->optionFactory->create();
  1771. $this->optionInstance->setProduct($this);
  1772. }
  1773. return $this->optionInstance;
  1774. }
  1775. /**
  1776. * Add option to array of product options
  1777. *
  1778. * @param Product\Option $option
  1779. * @return \Magento\Catalog\Model\Product
  1780. */
  1781. public function addOption(Product\Option $option)
  1782. {
  1783. $options = (array)$this->getData('options');
  1784. $options[] = $option;
  1785. $option->setProduct($this);
  1786. $this->setData('options', $options);
  1787. return $this;
  1788. }
  1789. /**
  1790. * Get option from options array of product by given option id
  1791. *
  1792. * @param int $optionId
  1793. * @return Product\Option|null
  1794. */
  1795. public function getOptionById($optionId)
  1796. {
  1797. if (is_array($this->getOptions())) {
  1798. /** @var \Magento\Catalog\Model\Product\Option $option */
  1799. foreach ($this->getOptions() as $option) {
  1800. if ($option->getId() == $optionId) {
  1801. return $option;
  1802. }
  1803. }
  1804. }
  1805. return null;
  1806. }
  1807. /**
  1808. * Retrieve options collection of product
  1809. *
  1810. * @return \Magento\Catalog\Model\ResourceModel\Product\Option\Collection
  1811. */
  1812. public function getProductOptionsCollection()
  1813. {
  1814. return $this->getOptionInstance()->getProductOptionCollection($this);
  1815. }
  1816. /**
  1817. * Get all options of product
  1818. *
  1819. * @return \Magento\Catalog\Api\Data\ProductCustomOptionInterface[]|null
  1820. */
  1821. public function getOptions()
  1822. {
  1823. return $this->getData('options');
  1824. }
  1825. /**
  1826. * Set product options
  1827. *
  1828. * @param \Magento\Catalog\Api\Data\ProductCustomOptionInterface[] $options
  1829. * @return $this
  1830. */
  1831. public function setOptions(array $options = null)
  1832. {
  1833. $this->setData('options', $options);
  1834. return $this;
  1835. }
  1836. /**
  1837. * Retrieve is a virtual product
  1838. *
  1839. * @return bool
  1840. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  1841. */
  1842. public function getIsVirtual()
  1843. {
  1844. return $this->getTypeInstance()->isVirtual($this);
  1845. }
  1846. /**
  1847. * Add custom option information to product
  1848. *
  1849. * @param string $code Option code
  1850. * @param mixed $value Value of the option
  1851. * @param int|Product|null $product Product ID
  1852. * @return $this
  1853. */
  1854. public function addCustomOption($code, $value, $product = null)
  1855. {
  1856. $product = $product ?: $this;
  1857. $option = $this->_itemOptionFactory->create()->addData(
  1858. ['product_id' => $product->getId(), 'product' => $product, 'code' => $code, 'value' => $value]
  1859. );
  1860. $this->_customOptions[$code] = $option;
  1861. return $this;
  1862. }
  1863. /**
  1864. * Sets custom options for the product
  1865. *
  1866. * @param array $options Array of options
  1867. * @return void
  1868. */
  1869. public function setCustomOptions(array $options)
  1870. {
  1871. $this->_customOptions = $options;
  1872. }
  1873. /**
  1874. * Get all custom options of the product
  1875. *
  1876. * @return array
  1877. */
  1878. public function getCustomOptions()
  1879. {
  1880. return $this->_customOptions;
  1881. }
  1882. /**
  1883. * Get product custom option info
  1884. *
  1885. * @param string $code
  1886. * @return array
  1887. */
  1888. public function getCustomOption($code)
  1889. {
  1890. if (isset($this->_customOptions[$code])) {
  1891. return $this->_customOptions[$code];
  1892. }
  1893. return null;
  1894. }
  1895. /**
  1896. * Checks if there custom option for this product
  1897. *
  1898. * @return bool
  1899. */
  1900. public function hasCustomOptions()
  1901. {
  1902. if (count($this->_customOptions)) {
  1903. return true;
  1904. } else {
  1905. return false;
  1906. }
  1907. }
  1908. /**
  1909. * Check availability display product in category
  1910. *
  1911. * @param int $categoryId
  1912. * @return bool
  1913. */
  1914. public function canBeShowInCategory($categoryId)
  1915. {
  1916. return $this->_getResource()->canBeShowInCategory($this, $categoryId);
  1917. }
  1918. /**
  1919. * Retrieve category ids where product is available
  1920. *
  1921. * @return array
  1922. */
  1923. public function getAvailableInCategories()
  1924. {
  1925. return $this->_getResource()->getAvailableInCategories($this);
  1926. }
  1927. /**
  1928. * Retrieve default attribute set id
  1929. *
  1930. * @return int
  1931. */
  1932. public function getDefaultAttributeSetId()
  1933. {
  1934. return $this->getResource()->getEntityType()->getDefaultAttributeSetId();
  1935. }
  1936. /**
  1937. * Reset all model data
  1938. *
  1939. * @return \Magento\Catalog\Model\Product
  1940. */
  1941. public function reset()
  1942. {
  1943. $this->unlockAttributes();
  1944. $this->_clearData();
  1945. return $this;
  1946. }
  1947. /**
  1948. * Get cache tags associated with object id
  1949. *
  1950. * @deprecated 102.0.5
  1951. * @see \Magento\Catalog\Model\Product::getIdentities
  1952. * @return string[]
  1953. */
  1954. public function getCacheIdTags()
  1955. {
  1956. $tags = parent::getCacheIdTags();
  1957. $affectedCategoryIds = $this->getAffectedCategoryIds();
  1958. if (!$affectedCategoryIds) {
  1959. $affectedCategoryIds = $this->getCategoryIds();
  1960. }
  1961. foreach ($affectedCategoryIds as $categoryId) {
  1962. $tags[] = \Magento\Catalog\Model\Category::CACHE_TAG . '_' . $categoryId;
  1963. }
  1964. return $tags;
  1965. }
  1966. /**
  1967. * Check for empty SKU on each product
  1968. *
  1969. * @param array $productIds
  1970. * @return boolean|null
  1971. */
  1972. public function isProductsHasSku(array $productIds)
  1973. {
  1974. $products = $this->_getResource()->getProductsSku($productIds);
  1975. if (count($products)) {
  1976. foreach ($products as $product) {
  1977. if (!strlen($product['sku'])) {
  1978. return false;
  1979. }
  1980. }
  1981. return true;
  1982. }
  1983. return null;
  1984. }
  1985. /**
  1986. * Parse buyRequest into options values used by product
  1987. *
  1988. * @param \Magento\Framework\DataObject $buyRequest
  1989. * @return \Magento\Framework\DataObject
  1990. */
  1991. public function processBuyRequest(\Magento\Framework\DataObject $buyRequest)
  1992. {
  1993. $options = new \Magento\Framework\DataObject();
  1994. /* add product custom options data */
  1995. $customOptions = $buyRequest->getOptions();
  1996. if (is_array($customOptions)) {
  1997. array_filter(
  1998. $customOptions,
  1999. function ($value) {
  2000. return $value !== '';
  2001. }
  2002. );
  2003. $options->setOptions($customOptions);
  2004. }
  2005. /* add product type selected options data */
  2006. $type = $this->getTypeInstance();
  2007. $typeSpecificOptions = $type->processBuyRequest($this, $buyRequest);
  2008. $options->addData($typeSpecificOptions);
  2009. /* check correctness of product's options */
  2010. $options->setErrors($type->checkProductConfiguration($this, $buyRequest));
  2011. return $options;
  2012. }
  2013. /**
  2014. * Get preconfigured values from product
  2015. *
  2016. * @return \Magento\Framework\DataObject
  2017. */
  2018. public function getPreconfiguredValues()
  2019. {
  2020. $preConfiguredValues = $this->getData('preconfigured_values');
  2021. if (!$preConfiguredValues) {
  2022. $preConfiguredValues = new \Magento\Framework\DataObject();
  2023. }
  2024. return $preConfiguredValues;
  2025. }
  2026. /**
  2027. * Prepare product custom options.
  2028. *
  2029. * To be sure that all product custom options does not has ID and has product instance
  2030. *
  2031. * @return \Magento\Catalog\Model\Product
  2032. */
  2033. public function prepareCustomOptions()
  2034. {
  2035. foreach ($this->getCustomOptions() as $option) {
  2036. if (!is_object($option->getProduct()) || $option->getId()) {
  2037. $this->addCustomOption($option->getCode(), $option->getValue());
  2038. }
  2039. }
  2040. return $this;
  2041. }
  2042. /**
  2043. * Clearing references on product
  2044. *
  2045. * @return \Magento\Catalog\Model\Product
  2046. */
  2047. protected function _clearReferences()
  2048. {
  2049. $this->_clearOptionReferences();
  2050. return $this;
  2051. }
  2052. /**
  2053. * Clearing product's data
  2054. *
  2055. * @return \Magento\Catalog\Model\Product
  2056. */
  2057. protected function _clearData()
  2058. {
  2059. foreach ($this->_data as $data) {
  2060. if (is_object($data) && method_exists($data, 'reset') && is_callable([$data, 'reset'])) {
  2061. $data->reset();
  2062. }
  2063. }
  2064. $this->setData([]);
  2065. $this->setOrigData();
  2066. $this->_customOptions = [];
  2067. $this->_canAffectOptions = false;
  2068. $this->_errors = [];
  2069. return $this;
  2070. }
  2071. /**
  2072. * Clearing references to product from product's options
  2073. *
  2074. * @return \Magento\Catalog\Model\Product
  2075. */
  2076. protected function _clearOptionReferences()
  2077. {
  2078. /**
  2079. * unload product options
  2080. */
  2081. if (!empty($this->getOptions())) {
  2082. /** @var \Magento\Catalog\Model\Product\Option $option */
  2083. foreach ($this->getOptions() as $option) {
  2084. $option->setProduct();
  2085. $option->clearInstance();
  2086. }
  2087. }
  2088. return $this;
  2089. }
  2090. /**
  2091. * Retrieve product entities info as array
  2092. *
  2093. * @param string|array $columns One or several columns
  2094. * @return array
  2095. */
  2096. public function getProductEntitiesInfo($columns = null)
  2097. {
  2098. return $this->_getResource()->getProductEntitiesInfo($columns);
  2099. }
  2100. /**
  2101. * Checks whether product has disabled status
  2102. *
  2103. * @return bool
  2104. */
  2105. public function isDisabled()
  2106. {
  2107. return $this->getStatus() == \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED;
  2108. }
  2109. /**
  2110. * Sets product image from it's child if possible
  2111. *
  2112. * @return string
  2113. */
  2114. public function getImage()
  2115. {
  2116. $this->getTypeInstance()->setImageFromChildProduct($this);
  2117. return parent::getImage();
  2118. }
  2119. /**
  2120. * Get identities
  2121. *
  2122. * @return array
  2123. */
  2124. public function getIdentities()
  2125. {
  2126. $identities = [self::CACHE_TAG . '_' . $this->getId()];
  2127. if ($this->getIsChangedCategories()) {
  2128. foreach ($this->getAffectedCategoryIds() as $categoryId) {
  2129. $identities[] = self::CACHE_PRODUCT_CATEGORY_TAG . '_' . $categoryId;
  2130. }
  2131. }
  2132. if (($this->getOrigData('status') != $this->getData('status')) || $this->isStockStatusChanged()) {
  2133. foreach ($this->getCategoryIds() as $categoryId) {
  2134. $identities[] = self::CACHE_PRODUCT_CATEGORY_TAG . '_' . $categoryId;
  2135. }
  2136. }
  2137. if ($this->_appState->getAreaCode() == \Magento\Framework\App\Area::AREA_FRONTEND) {
  2138. $identities[] = self::CACHE_TAG;
  2139. }
  2140. return array_unique($identities);
  2141. }
  2142. /**
  2143. * Check whether stock status changed
  2144. *
  2145. * @return bool
  2146. */
  2147. private function isStockStatusChanged()
  2148. {
  2149. $stockItem = null;
  2150. $extendedAttributes = $this->getExtensionAttributes();
  2151. if ($extendedAttributes !== null) {
  2152. $stockItem = $extendedAttributes->getStockItem();
  2153. }
  2154. $stockData = $this->getStockData();
  2155. return (
  2156. (is_array($stockData))
  2157. && array_key_exists('is_in_stock', $stockData)
  2158. && (null !== $stockItem)
  2159. && ($stockItem->getIsInStock() != $stockData['is_in_stock'])
  2160. );
  2161. }
  2162. /**
  2163. * Reload PriceInfo object
  2164. *
  2165. * @return \Magento\Framework\Pricing\PriceInfo\Base
  2166. */
  2167. public function reloadPriceInfo()
  2168. {
  2169. if ($this->_priceInfo) {
  2170. $this->_priceInfo = null;
  2171. return $this->getPriceInfo();
  2172. }
  2173. }
  2174. /**
  2175. * Return Data Object data in array format.
  2176. *
  2177. * @return array
  2178. * @todo refactor with converter for AbstractExtensibleModel
  2179. */
  2180. public function __toArray()
  2181. {
  2182. $data = $this->_data;
  2183. $hasToArray = function ($model) {
  2184. return is_object($model) && method_exists($model, '__toArray') && is_callable([$model, '__toArray']);
  2185. };
  2186. foreach ($data as $key => $value) {
  2187. if ($hasToArray($value)) {
  2188. $data[$key] = $value->__toArray();
  2189. } elseif (is_array($value)) {
  2190. foreach ($value as $nestedKey => $nestedValue) {
  2191. if ($hasToArray($nestedValue)) {
  2192. $value[$nestedKey] = $nestedValue->__toArray();
  2193. }
  2194. }
  2195. $data[$key] = $value;
  2196. }
  2197. }
  2198. return $data;
  2199. }
  2200. /**
  2201. * Convert Category model into flat array.
  2202. *
  2203. * @return array
  2204. */
  2205. public function toFlatArray()
  2206. {
  2207. $dataArray = $this->__toArray();
  2208. //process custom attributes if present
  2209. if (array_key_exists('custom_attributes', $dataArray) && !empty($dataArray['custom_attributes'])) {
  2210. /** @var \Magento\Framework\Api\AttributeInterface[] $customAttributes */
  2211. $customAttributes = $dataArray['custom_attributes'];
  2212. unset($dataArray['custom_attributes']);
  2213. foreach ($customAttributes as $attributeValue) {
  2214. $dataArray[$attributeValue[\Magento\Framework\Api\AttributeInterface::ATTRIBUTE_CODE]]
  2215. = $attributeValue[\Magento\Framework\Api\AttributeInterface::VALUE];
  2216. }
  2217. }
  2218. return $dataArray;
  2219. }
  2220. /**
  2221. * Set product sku
  2222. *
  2223. * @param string $sku
  2224. * @return $this
  2225. */
  2226. public function setSku($sku)
  2227. {
  2228. return $this->setData(self::SKU, $sku);
  2229. }
  2230. /**
  2231. * Set product name
  2232. *
  2233. * @param string $name
  2234. * @return $this
  2235. */
  2236. public function setName($name)
  2237. {
  2238. return $this->setData(self::NAME, $name);
  2239. }
  2240. /**
  2241. * Set product store id
  2242. *
  2243. * @param int $storeId
  2244. * @return $this
  2245. */
  2246. public function setStoreId($storeId)
  2247. {
  2248. return $this->setData(self::STORE_ID, $storeId);
  2249. }
  2250. /**
  2251. * Set product attribute set id
  2252. *
  2253. * @param int $attributeSetId
  2254. * @return $this
  2255. */
  2256. public function setAttributeSetId($attributeSetId)
  2257. {
  2258. return $this->setData(self::ATTRIBUTE_SET_ID, $attributeSetId);
  2259. }
  2260. /**
  2261. * Set product price
  2262. *
  2263. * @param float $price
  2264. * @return $this
  2265. */
  2266. public function setPrice($price)
  2267. {
  2268. return $this->setData(self::PRICE, $price);
  2269. }
  2270. /**
  2271. * Set product status
  2272. *
  2273. * @param int $status
  2274. * @return $this
  2275. */
  2276. public function setStatus($status)
  2277. {
  2278. return $this->setData(self::STATUS, $status);
  2279. }
  2280. /**
  2281. * Set product visibility
  2282. *
  2283. * @param int $visibility
  2284. * @return $this
  2285. */
  2286. public function setVisibility($visibility)
  2287. {
  2288. return $this->setData(self::VISIBILITY, $visibility);
  2289. }
  2290. /**
  2291. * Set product created date
  2292. *
  2293. * @param string $createdAt
  2294. * @return $this
  2295. */
  2296. public function setCreatedAt($createdAt)
  2297. {
  2298. return $this->setData(self::CREATED_AT, $createdAt);
  2299. }
  2300. /**
  2301. * Set product updated date
  2302. *
  2303. * @param string $updatedAt
  2304. * @return $this
  2305. */
  2306. public function setUpdatedAt($updatedAt)
  2307. {
  2308. return $this->setData(self::UPDATED_AT, $updatedAt);
  2309. }
  2310. /**
  2311. * Set product weight
  2312. *
  2313. * @param float $weight
  2314. * @return $this
  2315. */
  2316. public function setWeight($weight)
  2317. {
  2318. return $this->setData(self::WEIGHT, $weight);
  2319. }
  2320. /**
  2321. * Set product type id
  2322. *
  2323. * @param string $typeId
  2324. * @return $this
  2325. */
  2326. public function setTypeId($typeId)
  2327. {
  2328. if ($typeId !== $this->_getData('type_id')) {
  2329. $this->_typeInstance = null;
  2330. }
  2331. return $this->setData(self::TYPE_ID, $typeId);
  2332. }
  2333. /**
  2334. * @inheritdoc
  2335. *
  2336. * @return \Magento\Framework\Api\ExtensionAttributesInterface
  2337. */
  2338. public function getExtensionAttributes()
  2339. {
  2340. return $this->_getExtensionAttributes();
  2341. }
  2342. /**
  2343. * @inheritdoc
  2344. *
  2345. * @param \Magento\Catalog\Api\Data\ProductExtensionInterface $extensionAttributes
  2346. * @return $this
  2347. */
  2348. public function setExtensionAttributes(\Magento\Catalog\Api\Data\ProductExtensionInterface $extensionAttributes)
  2349. {
  2350. return $this->_setExtensionAttributes($extensionAttributes);
  2351. }
  2352. //@codeCoverageIgnoreEnd
  2353. /**
  2354. * Convert Image to ProductAttributeMediaGalleryEntryInterface
  2355. *
  2356. * @param array $mediaGallery
  2357. * @return \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface[]
  2358. * @throws \Magento\Framework\Exception\LocalizedException
  2359. */
  2360. protected function convertToMediaGalleryInterface(array $mediaGallery)
  2361. {
  2362. $entries = [];
  2363. foreach ($mediaGallery as $image) {
  2364. $entry = $this
  2365. ->mediaGalleryEntryConverterPool
  2366. ->getConverterByMediaType($image['media_type'])
  2367. ->convertTo($this, $image);
  2368. $entries[] = $entry;
  2369. }
  2370. return $entries;
  2371. }
  2372. /**
  2373. * Get media gallery entries
  2374. *
  2375. * @return \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface[]|null
  2376. * @throws \Magento\Framework\Exception\LocalizedException
  2377. */
  2378. public function getMediaGalleryEntries()
  2379. {
  2380. $mediaGallery = $this->getMediaGallery('images');
  2381. if ($mediaGallery === null) {
  2382. return null;
  2383. }
  2384. //convert the data
  2385. $convertedEntries = $this->convertToMediaGalleryInterface($mediaGallery);
  2386. return $convertedEntries;
  2387. }
  2388. /**
  2389. * Set media gallery entries
  2390. *
  2391. * @param ProductAttributeMediaGalleryEntryInterface[] $mediaGalleryEntries
  2392. * @return $this
  2393. * @throws \Magento\Framework\Exception\LocalizedException
  2394. */
  2395. public function setMediaGalleryEntries(array $mediaGalleryEntries = null)
  2396. {
  2397. if ($mediaGalleryEntries !== null) {
  2398. $images = [];
  2399. foreach ($mediaGalleryEntries as $entry) {
  2400. $images[] = $this
  2401. ->mediaGalleryEntryConverterPool
  2402. ->getConverterByMediaType($entry->getMediaType())
  2403. ->convertFrom($entry);
  2404. }
  2405. $this->setData('media_gallery', ['images' => $images]);
  2406. }
  2407. return $this;
  2408. }
  2409. /**
  2410. * Identifier getter
  2411. *
  2412. * @return int
  2413. * @since 101.0.0
  2414. */
  2415. public function getId()
  2416. {
  2417. return $this->_getData('entity_id');
  2418. }
  2419. /**
  2420. * Set entity Id
  2421. *
  2422. * @param int $value
  2423. * @return $this
  2424. * @since 101.0.0
  2425. */
  2426. public function setId($value)
  2427. {
  2428. return $this->setData('entity_id', $value);
  2429. }
  2430. /**
  2431. * Get link repository
  2432. *
  2433. * @return ProductLinkRepositoryInterface
  2434. */
  2435. private function getLinkRepository()
  2436. {
  2437. if (null === $this->linkRepository) {
  2438. $this->linkRepository = \Magento\Framework\App\ObjectManager::getInstance()
  2439. ->get(\Magento\Catalog\Api\ProductLinkRepositoryInterface::class);
  2440. }
  2441. return $this->linkRepository;
  2442. }
  2443. /**
  2444. * Get media gallery processor
  2445. *
  2446. * @return Product\Gallery\Processor
  2447. */
  2448. private function getMediaGalleryProcessor()
  2449. {
  2450. if (null === $this->mediaGalleryProcessor) {
  2451. $this->mediaGalleryProcessor = \Magento\Framework\App\ObjectManager::getInstance()
  2452. ->get(\Magento\Catalog\Model\Product\Gallery\Processor::class);
  2453. }
  2454. return $this->mediaGalleryProcessor;
  2455. }
  2456. /**
  2457. * Set the associated products
  2458. *
  2459. * @param array $productIds
  2460. * @return $this
  2461. * @since 101.0.2
  2462. */
  2463. public function setAssociatedProductIds(array $productIds)
  2464. {
  2465. $this->getExtensionAttributes()->setConfigurableProductLinks($productIds);
  2466. return $this;
  2467. }
  2468. /**
  2469. * Get quantity and stock status data
  2470. *
  2471. * @return array|null
  2472. *
  2473. * @deprecated 102.0.0 as Product model shouldn't be responsible for stock status
  2474. * @see StockItemInterface when you want to change the stock data
  2475. * @see StockStatusInterface when you want to read the stock data for representation layer (storefront)
  2476. * @see StockItemRepositoryInterface::save as extension point for customization of saving process
  2477. * @since 102.0.0
  2478. */
  2479. public function getQuantityAndStockStatus()
  2480. {
  2481. return $this->getData('quantity_and_stock_status');
  2482. }
  2483. /**
  2484. * Set quantity and stock status data
  2485. *
  2486. * @param array $quantityAndStockStatusData
  2487. * @return $this
  2488. *
  2489. * @deprecated 102.0.0 as Product model shouldn't be responsible for stock status
  2490. * @see StockItemInterface when you want to change the stock data
  2491. * @see StockStatusInterface when you want to read the stock data for representation layer (storefront)
  2492. * @see StockItemRepositoryInterface::save as extension point for customization of saving process
  2493. * @since 102.0.0
  2494. */
  2495. public function setQuantityAndStockStatus($quantityAndStockStatusData)
  2496. {
  2497. $this->setData('quantity_and_stock_status', $quantityAndStockStatusData);
  2498. return $this;
  2499. }
  2500. /**
  2501. * Get stock data
  2502. *
  2503. * @return array|null
  2504. *
  2505. * @deprecated 102.0.0 as Product model shouldn't be responsible for stock status
  2506. * @see StockItemInterface when you want to change the stock data
  2507. * @see StockStatusInterface when you want to read the stock data for representation layer (storefront)
  2508. * @see StockItemRepositoryInterface::save as extension point for customization of saving process
  2509. * @since 102.0.0
  2510. */
  2511. public function getStockData()
  2512. {
  2513. return $this->getData('stock_data');
  2514. }
  2515. /**
  2516. * Set stock data
  2517. *
  2518. * @param array $stockData
  2519. * @return $this
  2520. *
  2521. * @deprecated 102.0.0 as Product model shouldn't be responsible for stock status
  2522. * @see StockItemInterface when you want to change the stock data
  2523. * @see StockStatusInterface when you want to read the stock data for representation layer (storefront)
  2524. * @see StockItemRepositoryInterface::save as extension point for customization of saving process
  2525. * @since 102.0.0
  2526. */
  2527. public function setStockData($stockData)
  2528. {
  2529. $this->setData('stock_data', $stockData);
  2530. return $this;
  2531. }
  2532. }