UpgradeWebsiteAttributes.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Catalog\Setup\Patch\Data;
  7. use Magento\Catalog\Api\Data\CategoryInterface;
  8. use Magento\Catalog\Api\Data\ProductInterface;
  9. use Magento\Framework\DB\Query\Generator;
  10. use Magento\Framework\EntityManager\MetadataPool;
  11. use Magento\Framework\Exception\LocalizedException;
  12. use Magento\Framework\Setup\ModuleDataSetupInterface;
  13. use Magento\Framework\Setup\Patch\DataPatchInterface;
  14. use Magento\Framework\Setup\Patch\PatchVersionInterface;
  15. /**
  16. * Class UpgradeWebsiteAttributes
  17. * @package Magento\Catalog\Setup\Patch
  18. *
  19. * IMPORTANT: This class const/methods can not be reused because it needs to be isolated
  20. */
  21. class UpgradeWebsiteAttributes implements DataPatchInterface, PatchVersionInterface
  22. {
  23. /**
  24. * ATTENTION: These constants must not be reused anywhere outside
  25. */
  26. const ATTRIBUTE_WEBSITE = 2;
  27. const GLOBAL_STORE_VIEW_ID = 0;
  28. const MASK_ATTRIBUTE_VALUE = '%d_%d_%d';
  29. /**
  30. * Map table names to metadata classes where link field might be found
  31. */
  32. private $tableMetaDataClass = [
  33. 'catalog_category_entity_datetime' => CategoryInterface::class,
  34. 'catalog_category_entity_decimal' => CategoryInterface::class,
  35. 'catalog_category_entity_int' => CategoryInterface::class,
  36. 'catalog_category_entity_text' => CategoryInterface::class,
  37. 'catalog_category_entity_varchar' => CategoryInterface::class,
  38. 'catalog_product_entity_datetime' => ProductInterface::class,
  39. 'catalog_product_entity_decimal' => ProductInterface::class,
  40. 'catalog_product_entity_int' => ProductInterface::class,
  41. 'catalog_product_entity_text' => ProductInterface::class,
  42. 'catalog_product_entity_varchar' => ProductInterface::class,
  43. ];
  44. /**
  45. * Internal format :
  46. * [
  47. * website_id => [
  48. * store_view_id_1,
  49. * store_view_id_2,
  50. * ...
  51. * ]
  52. * ]
  53. *
  54. * @var array
  55. */
  56. private $groupedStoreViews = [];
  57. /**
  58. * @var array
  59. */
  60. private $processedAttributeValues = [];
  61. /**
  62. * @var Generator
  63. */
  64. private $batchQueryGenerator;
  65. /**
  66. * @var MetadataPool
  67. */
  68. private $metaDataPool;
  69. /**
  70. * @var array
  71. */
  72. private $linkFields = [];
  73. /**
  74. * @var ModuleDataSetupInterface
  75. */
  76. private $moduleDataSetup;
  77. /**
  78. * UpgradeWebsiteAttributes constructor.
  79. * @param Generator $batchQueryGenerator
  80. * @param MetadataPool $metadataPool
  81. * @param ModuleDataSetupInterface $moduleDataSetup
  82. */
  83. public function __construct(
  84. Generator $batchQueryGenerator,
  85. MetadataPool $metadataPool,
  86. ModuleDataSetupInterface $moduleDataSetup
  87. ) {
  88. $this->batchQueryGenerator = $batchQueryGenerator;
  89. $this->metaDataPool = $metadataPool;
  90. $this->moduleDataSetup = $moduleDataSetup;
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function apply()
  96. {
  97. foreach (array_keys($this->tableMetaDataClass) as $tableName) {
  98. $this->upgradeTable($tableName);
  99. }
  100. }
  101. /**
  102. * @param string $tableName
  103. * @return void
  104. */
  105. private function upgradeTable($tableName)
  106. {
  107. foreach ($this->fetchAttributeValues($tableName) as $attributeValueItems) {
  108. $this->processAttributeValues($attributeValueItems, $tableName);
  109. }
  110. }
  111. /**
  112. * Aligns website attribute values
  113. * @param array $attributeValueItems
  114. * @param string $tableName
  115. * @return void
  116. */
  117. private function processAttributeValues(array $attributeValueItems, $tableName)
  118. {
  119. $this->resetProcessedAttributeValues();
  120. foreach ($attributeValueItems as $attributeValueItem) {
  121. if ($this->isProcessedAttributeValue($attributeValueItem, $tableName)) {
  122. continue;
  123. }
  124. $insertions = $this->generateAttributeValueInsertions($attributeValueItem, $tableName);
  125. if (!empty($insertions)) {
  126. $this->executeInsertions($insertions, $tableName);
  127. }
  128. $this->markAttributeValueProcessed($attributeValueItem, $tableName);
  129. }
  130. }
  131. /**
  132. * Yields batch of AttributeValues
  133. *
  134. * @param string $tableName
  135. * @yield array
  136. * @return \Generator
  137. */
  138. private function fetchAttributeValues($tableName)
  139. {
  140. //filter store groups which have more than 1 store
  141. $multipleStoresInWebsite = array_values(
  142. array_reduce(
  143. array_filter($this->getGroupedStoreViews(), function ($storeViews) {
  144. return is_array($storeViews) && count($storeViews) > 1;
  145. }),
  146. 'array_merge',
  147. []
  148. )
  149. );
  150. if (count($multipleStoresInWebsite) < 1) {
  151. return [];
  152. }
  153. $connection = $this->moduleDataSetup->getConnection();
  154. $batchSelectIterator = $this->batchQueryGenerator->generate(
  155. 'value_id',
  156. $connection
  157. ->select()
  158. ->from(
  159. ['cpei' => $this->moduleDataSetup->getTable($tableName)],
  160. '*'
  161. )
  162. ->join(
  163. [
  164. 'cea' => $this->moduleDataSetup->getTable('catalog_eav_attribute'),
  165. ],
  166. 'cpei.attribute_id = cea.attribute_id',
  167. ''
  168. )
  169. ->join(
  170. [
  171. 'st' => $this->moduleDataSetup->getTable('store'),
  172. ],
  173. 'st.store_id = cpei.store_id',
  174. 'st.website_id'
  175. )
  176. ->where(
  177. 'cea.is_global = ?',
  178. self::ATTRIBUTE_WEBSITE
  179. )
  180. ->where(
  181. 'cpei.store_id IN (?)',
  182. $multipleStoresInWebsite
  183. ),
  184. 1000
  185. );
  186. foreach ($batchSelectIterator as $select) {
  187. yield $connection->fetchAll($select);
  188. }
  189. }
  190. /**
  191. * @return array
  192. */
  193. private function getGroupedStoreViews()
  194. {
  195. if (!empty($this->groupedStoreViews)) {
  196. return $this->groupedStoreViews;
  197. }
  198. $connection = $this->moduleDataSetup->getConnection();
  199. $query = $connection
  200. ->select()
  201. ->from(
  202. $this->moduleDataSetup->getTable('store'),
  203. '*'
  204. );
  205. $storeViews = $connection->fetchAll($query);
  206. $this->groupedStoreViews = [];
  207. foreach ($storeViews as $storeView) {
  208. if ($storeView['store_id'] != 0) {
  209. $this->groupedStoreViews[$storeView['website_id']][] = $storeView['store_id'];
  210. }
  211. }
  212. return $this->groupedStoreViews;
  213. }
  214. /**
  215. * @param array $attributeValue
  216. * @param string $tableName
  217. * @return bool
  218. */
  219. private function isProcessedAttributeValue(array $attributeValue, $tableName)
  220. {
  221. return in_array(
  222. $this->getAttributeValueKey(
  223. $attributeValue[$this->getTableLinkField($tableName)],
  224. $attributeValue['attribute_id'],
  225. $attributeValue['website_id']
  226. ),
  227. $this->processedAttributeValues
  228. );
  229. }
  230. /**
  231. * Resets processed attribute values
  232. * @return void
  233. */
  234. private function resetProcessedAttributeValues()
  235. {
  236. $this->processedAttributeValues = [];
  237. }
  238. /**
  239. * @param array $attributeValue
  240. * @param string $tableName
  241. * @return void
  242. */
  243. private function markAttributeValueProcessed(array $attributeValue, $tableName)
  244. {
  245. $this->processedAttributeValues[] = $this->getAttributeValueKey(
  246. $attributeValue[$this->getTableLinkField($tableName)],
  247. $attributeValue['attribute_id'],
  248. $attributeValue['website_id']
  249. );
  250. }
  251. /**
  252. * @param int $entityId
  253. * @param int $attributeId
  254. * @param int $websiteId
  255. * @return string
  256. */
  257. private function getAttributeValueKey($entityId, $attributeId, $websiteId)
  258. {
  259. return sprintf(
  260. self::MASK_ATTRIBUTE_VALUE,
  261. $entityId,
  262. $attributeId,
  263. $websiteId
  264. );
  265. }
  266. /**
  267. * @param array $attributeValue
  268. * @param string $tableName
  269. * @return array|null
  270. */
  271. private function generateAttributeValueInsertions(
  272. array $attributeValue,
  273. $tableName
  274. ) {
  275. $groupedStoreViews = $this->getGroupedStoreViews();
  276. if (empty($groupedStoreViews[$attributeValue['website_id']])) {
  277. return null;
  278. }
  279. $currentStoreViewIds = $groupedStoreViews[$attributeValue['website_id']];
  280. $insertions = [];
  281. foreach ($currentStoreViewIds as $index => $storeViewId) {
  282. $insertions[] = [
  283. ':attribute_id' . $index => $attributeValue['attribute_id'],
  284. ':store_id' . $index => $storeViewId,
  285. ':entity_id' . $index => $attributeValue[$this->getTableLinkField($tableName)],
  286. ':value' . $index => $attributeValue['value'],
  287. ];
  288. }
  289. return $insertions;
  290. }
  291. /**
  292. * @param array $insertions
  293. * @param string $tableName
  294. * @return void
  295. */
  296. private function executeInsertions(array $insertions, $tableName)
  297. {
  298. $rawQuery = sprintf(
  299. 'INSERT INTO
  300. %s(attribute_id, store_id, %s, `value`)
  301. VALUES
  302. %s
  303. ON duplicate KEY UPDATE `value` = VALUES(`value`)',
  304. $this->moduleDataSetup->getTable($tableName),
  305. $this->getTableLinkField($tableName),
  306. $this->prepareInsertValuesStatement($insertions)
  307. );
  308. $this->moduleDataSetup->getConnection()->query($rawQuery, $this->getPlaceholderValues($insertions));
  309. }
  310. /**
  311. * Maps $insertions hierarchy to single-level $placeholder => $value array
  312. *
  313. * @param array $insertions
  314. * @return array
  315. */
  316. private function getPlaceholderValues(array $insertions)
  317. {
  318. $placeholderValues = [];
  319. foreach ($insertions as $insertion) {
  320. $placeholderValues = array_merge(
  321. $placeholderValues,
  322. $insertion
  323. );
  324. }
  325. return $placeholderValues;
  326. }
  327. /**
  328. * Extracts from $insertions values placeholders and turns it into query statement view
  329. *
  330. * @param array $insertions
  331. * @return string
  332. */
  333. private function prepareInsertValuesStatement(array $insertions)
  334. {
  335. $statement = '';
  336. foreach ($insertions as $insertion) {
  337. $statement .= sprintf('(%s),', implode(',', array_keys($insertion)));
  338. }
  339. return rtrim($statement, ',');
  340. }
  341. /**
  342. * @param string $tableName
  343. * @return string
  344. * @throws LocalizedException
  345. */
  346. private function getTableLinkField($tableName)
  347. {
  348. if (!isset($this->tableMetaDataClass[$tableName])) {
  349. throw new LocalizedException(
  350. sprintf(
  351. 'Specified table: %s is not defined in tables list',
  352. $tableName
  353. )
  354. );
  355. }
  356. if (!isset($this->linkFields[$tableName])) {
  357. $this->linkFields[$tableName] = $this->metaDataPool
  358. ->getMetadata($this->tableMetaDataClass[$tableName])
  359. ->getLinkField();
  360. }
  361. return $this->linkFields[$tableName];
  362. }
  363. /**
  364. * {@inheritdoc}
  365. */
  366. public static function getDependencies()
  367. {
  368. return [
  369. UpgradeWidgetData::class,
  370. ];
  371. }
  372. /**
  373. * {@inheritdoc}
  374. */
  375. public static function getVersion()
  376. {
  377. return '2.2.2';
  378. }
  379. /**
  380. * {@inheritdoc}
  381. */
  382. public function getAliases()
  383. {
  384. return [];
  385. }
  386. }