/
AbstractAction.php
928 lines (854 loc) · 31.3 KB
/
AbstractAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Model\Indexer\Category\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Query\Generator as QueryGenerator;
use Magento\Framework\DB\Select;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Framework\ObjectManager\ResetAfterRequestInterface;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\Store;
// phpcs:disable Magento2.Classes.AbstractApi
/**
* Class AbstractAction
*
* @api
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
* phpcs:disable Magento2.Annotation.MethodAnnotationStructure.InvalidDeprecatedTagUsage
*/
abstract class AbstractAction implements ResetAfterRequestInterface
{
/**
* Chunk size
*/
public const RANGE_CATEGORY_STEP = 500;
/**
* Chunk size for product
*/
public const RANGE_PRODUCT_STEP = 1000000;
/**
* Catalog category index table name
*/
public const MAIN_INDEX_TABLE = 'catalog_category_product_index';
/**
* Suffix for table to show it is temporary
* @deprecated
* @see getIndexTable
*/
public const TEMPORARY_TABLE_SUFFIX = '_tmp';
/**
* Cached non anchor categories select by store id
*
* @var Select[]
*/
protected $nonAnchorSelects = [];
/**
* Cached anchor categories select by store id
*
* @var Select[]
*/
protected $anchorSelects = [];
/**
* Cached all product select by store id
*
* @var Select[]
*/
protected $productsSelects = [];
/**
* Category path by id
*
* @var string[]
*/
protected $categoryPath = [];
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $resource;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Magento\Catalog\Model\Config
*/
protected $config;
/**
* Whether to use main or temporary index table
*
* @var bool
*/
protected $useTempTable = true;
/**
* @var \Magento\Framework\DB\Adapter\AdapterInterface
*/
protected $connection;
/**
* @var MetadataPool
* @since 101.0.0
*/
protected $metadataPool;
/**
* @var TableMaintainer
* @since 102.0.5
*/
protected $tableMaintainer;
/**
* @var string
* @since 101.0.0
*/
protected $tempTreeIndexTableName;
/**
* @var QueryGenerator
*/
private $queryGenerator;
/**
* @var StoreInterface
*/
private $currentStore;
/**
* @param ResourceConnection $resource
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Config $config
* @param QueryGenerator $queryGenerator
* @param MetadataPool|null $metadataPool
* @param TableMaintainer|null $tableMaintainer
*/
public function __construct(
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Config $config,
QueryGenerator $queryGenerator = null,
MetadataPool $metadataPool = null,
TableMaintainer $tableMaintainer = null
) {
$this->resource = $resource;
$this->connection = $resource->getConnection();
$this->storeManager = $storeManager;
$this->config = $config;
$this->queryGenerator = $queryGenerator ?: ObjectManager::getInstance()->get(QueryGenerator::class);
$this->metadataPool = $metadataPool ?: ObjectManager::getInstance()->get(MetadataPool::class);
$this->tableMaintainer = $tableMaintainer ?: ObjectManager::getInstance()->get(TableMaintainer::class);
}
/**
* @inheritDoc
*/
public function _resetState(): void
{
$this->nonAnchorSelects = [];
$this->anchorSelects = [];
$this->productsSelects = [];
$this->categoryPath = [];
$this->useTempTable = true;
$this->tempTreeIndexTableName = null;
$this->currentStore = null;
}
/**
* Run full reindex
*
* @return $this
*/
abstract public function execute();
/**
* Run reindexation
*
* @return void
*/
protected function reindex()
{
foreach ($this->storeManager->getStores() as $store) {
if ($this->getPathFromCategoryId($store->getRootCategoryId())) {
$this->setCurrentStore($store);
$this->reindexRootCategory($store);
$this->reindexAnchorCategories($store);
$this->reindexNonAnchorCategories($store);
}
}
}
/**
* Set current store
*
* @param StoreInterface $store
* @return $this
*/
private function setCurrentStore(StoreInterface $store): self
{
$this->currentStore = $store;
return $this;
}
/**
* Get current store
*
* @return StoreInterface
*/
private function getCurrentStore(): StoreInterface
{
return $this->currentStore;
}
/**
* Return validated table name
*
* @param string|string[] $table
* @return string
*/
protected function getTable($table)
{
return $this->resource->getTableName($table);
}
/**
* Return main index table name
*
* This table should be used on frontend(clients)
* The name is switched between 'catalog_category_product_index' and 'catalog_category_product_index_replica'
*
* @return string
* @deprecated 102.0.5
*/
protected function getMainTable()
{
return $this->getTable(self::MAIN_INDEX_TABLE);
}
/**
* Return temporary index table name
*
* @return string
* @deprecated 102.0.5
*/
protected function getMainTmpTable()
{
return $this->useTempTable
? $this->getTable(self::MAIN_INDEX_TABLE . self::TEMPORARY_TABLE_SUFFIX)
: $this->getMainTable();
}
/**
* Return index table name
*
* @param int $storeId
* @return string
* @since 102.0.5
*/
protected function getIndexTable($storeId)
{
return $this->useTempTable
? $this->tableMaintainer->getMainReplicaTable($storeId)
: $this->tableMaintainer->getMainTable($storeId);
}
/**
* Return category path by id
*
* @param int $categoryId
* @return string
*/
protected function getPathFromCategoryId($categoryId)
{
if (!isset($this->categoryPath[$categoryId])) {
$this->categoryPath[$categoryId] = $this->connection->fetchOne(
$this->connection->select()->from(
$this->getTable('catalog_category_entity'),
['path']
)->where(
'entity_id = ?',
$categoryId
)
);
}
return $this->categoryPath[$categoryId];
}
/**
* Retrieve select for reindex products of non anchor categories
*
* @param Store $store
* @return Select
* @throws \Exception when metadata not found for ProductInterface
*/
protected function getNonAnchorCategoriesSelect(Store $store)
{
if (!isset($this->nonAnchorSelects[$store->getId()])) {
$statusAttributeId = $this->config->getAttribute(
Product::ENTITY,
'status'
)->getId();
$visibilityAttributeId = $this->config->getAttribute(
Product::ENTITY,
'visibility'
)->getId();
$rootPath = $this->getPathFromCategoryId($store->getRootCategoryId());
$metadata = $this->metadataPool->getMetadata(ProductInterface::class);
$linkField = $metadata->getLinkField();
$select = $this->connection->select()->from(
['cc' => $this->getTable('catalog_category_entity')],
[]
)->joinInner(
['ccp' => $this->getTable('catalog_category_product')],
'ccp.category_id = cc.entity_id',
[]
)->joinInner(
['cpw' => $this->getTable('catalog_product_website')],
'cpw.product_id = ccp.product_id',
[]
)->joinInner(
['cpe' => $this->getTable('catalog_product_entity')],
'ccp.product_id = cpe.entity_id',
[]
)->joinInner(
['cpsd' => $this->getTable('catalog_product_entity_int')],
'cpsd.' . $linkField . ' = cpe.' . $linkField . ' AND cpsd.store_id = 0' .
' AND cpsd.attribute_id = ' .
$statusAttributeId,
[]
)->joinLeft(
['cpss' => $this->getTable('catalog_product_entity_int')],
'cpss.' . $linkField . ' = cpe.' . $linkField . ' AND cpss.attribute_id = cpsd.attribute_id' .
' AND cpss.store_id = ' .
$store->getId(),
[]
)->joinInner(
['cpvd' => $this->getTable('catalog_product_entity_int')],
'cpvd.' . $linkField . ' = cpe.' . $linkField . ' AND cpvd.store_id = 0' .
' AND cpvd.attribute_id = ' .
$visibilityAttributeId,
[]
)->joinLeft(
['cpvs' => $this->getTable('catalog_product_entity_int')],
'cpvs.' . $linkField . ' = cpe.' . $linkField . ' AND cpvs.attribute_id = cpvd.attribute_id' .
' AND cpvs.store_id = ' .
$store->getId(),
[]
)->where(
'cc.path LIKE ' . $this->connection->quote($rootPath . '/%')
)->where(
'cpw.website_id = ?',
$store->getWebsiteId()
)->where(
$this->connection->getIfNullSql('cpss.value', 'cpsd.value') . ' = ?',
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
)->where(
$this->connection->getIfNullSql('cpvs.value', 'cpvd.value') . ' IN (?)',
[
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_CATALOG,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_SEARCH,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
]
)->columns(
[
'category_id' => 'cc.entity_id',
'product_id' => 'ccp.product_id',
'position' => 'ccp.position',
'is_parent' => new \Zend_Db_Expr('1'),
'store_id' => new \Zend_Db_Expr($store->getId()),
'visibility' => new \Zend_Db_Expr(
$this->connection->getIfNullSql('cpvs.value', 'cpvd.value')
),
]
);
$this->addFilteringByChildProductsToSelect($select, $store);
$this->nonAnchorSelects[$store->getId()] = $select;
}
return $this->nonAnchorSelects[$store->getId()];
}
/**
* Add filtering by child products to select
*
* It's used for correct handling of composite products.
* This method makes assumption that select already joins `catalog_product_entity` as `cpe`.
*
* @param Select $select
* @param Store $store
* @return void
* @throws \Exception when metadata not found for ProductInterface
*/
private function addFilteringByChildProductsToSelect(Select $select, Store $store)
{
$metadata = $this->metadataPool->getMetadata(ProductInterface::class);
$linkField = $metadata->getLinkField();
$statusAttributeId = $this->config->getAttribute(Product::ENTITY, 'status')->getId();
$select->joinLeft(
['relation' => $this->getTable('catalog_product_relation')],
'cpe.' . $linkField . ' = relation.parent_id',
[]
)->joinLeft(
['relation_product_entity' => $this->getTable('catalog_product_entity')],
'relation.child_id = relation_product_entity.entity_id',
[]
)->joinLeft(
['child_cpsd' => $this->getTable('catalog_product_entity_int')],
'child_cpsd.' . $linkField . ' = '. 'relation_product_entity.' . $linkField
. ' AND child_cpsd.store_id = 0'
. ' AND child_cpsd.attribute_id = ' . $statusAttributeId,
[]
)->joinLeft(
['child_cpss' => $this->getTable('catalog_product_entity_int')],
'child_cpss.' . $linkField . ' = '. 'relation_product_entity.' . $linkField . ''
. ' AND child_cpss.attribute_id = child_cpsd.attribute_id'
. ' AND child_cpss.store_id = ' . $store->getId(),
[]
)->where(
'relation.child_id IS NULL OR '
. $this->connection->getIfNullSql('child_cpss.value', 'child_cpsd.value') . ' = ?',
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
)->group(
[
'cc.entity_id',
'ccp.product_id',
'visibility',
]
);
}
/**
* Check whether select ranging is needed
*
* @return bool
*/
protected function isRangingNeeded()
{
return true;
}
/**
* Return selects cut by min and max
*
* @param Select $select
* @param string $field
* @param int $range
* @return Select[]
*/
protected function prepareSelectsByRange(
Select $select,
string $field,
int $range = self::RANGE_CATEGORY_STEP
) {
if ($this->isRangingNeeded()) {
$iterator = $this->queryGenerator->generate(
$field,
$select,
$range,
\Magento\Framework\DB\Query\BatchIteratorInterface::UNIQUE_FIELD_ITERATOR
);
$queries = [];
foreach ($iterator as $query) {
$queries[] = $query;
}
return $queries;
}
return [$select];
}
/**
* Reindex products of non anchor categories
*
* @param Store $store
* @return void
*/
protected function reindexNonAnchorCategories(Store $store)
{
$selects = $this->prepareSelectsByRange($this->getNonAnchorCategoriesSelect($store), 'entity_id');
foreach ($selects as $select) {
$this->connection->query(
$this->connection->insertFromSelect(
$select,
$this->getIndexTable($store->getId()),
['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
\Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE
)
);
}
}
/**
* Check if anchor select isset
*
* @param Store $store
* @return bool
*/
protected function hasAnchorSelect(Store $store)
{
return isset($this->anchorSelects[$store->getId()]);
}
/**
* Create anchor select
*
* @param Store $store
* @return Select
* @throws \Exception when metadata not found for ProductInterface or CategoryInterface
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function createAnchorSelect(Store $store)
{
$this->setCurrentStore($store);
$isAnchorAttributeId = $this->config->getAttribute(
\Magento\Catalog\Model\Category::ENTITY,
'is_anchor'
)->getId();
$statusAttributeId = $this->config->getAttribute(Product::ENTITY, 'status')->getId();
$visibilityAttributeId = $this->config->getAttribute(Product::ENTITY, 'visibility')->getId();
$rootCatIds = explode('/', $this->getPathFromCategoryId($store->getRootCategoryId()));
array_pop($rootCatIds);
$temporaryTreeTable = $this->makeTempCategoryTreeIndex();
$productMetadata = $this->metadataPool->getMetadata(ProductInterface::class);
$categoryMetadata = $this->metadataPool->getMetadata(\Magento\Catalog\Api\Data\CategoryInterface::class);
$productLinkField = $productMetadata->getLinkField();
$categoryLinkField = $categoryMetadata->getLinkField();
$select = $this->connection->select()->from(
['cc' => $this->getTable('catalog_category_entity')],
[]
)->joinInner(
['cc2' => $temporaryTreeTable],
$this->connection->quoteInto(
'cc2.parent_id = cc.entity_id AND cc.entity_id NOT IN (?)',
$rootCatIds,
\Zend_Db::INT_TYPE
),
[]
)->joinInner(
['ccp' => $this->getTable('catalog_category_product')],
'ccp.category_id = cc2.child_id',
[]
)->joinLeft(
['ccp2' => $this->getTable('catalog_category_product')],
'ccp2.category_id = cc2.parent_id AND ccp.product_id = ccp2.product_id',
[]
)->joinInner(
['cpe' => $this->getTable('catalog_product_entity')],
'ccp.product_id = cpe.entity_id',
[]
)->joinInner(
['cpw' => $this->getTable('catalog_product_website')],
'cpw.product_id = ccp.product_id',
[]
)->joinInner(
['cpsd' => $this->getTable('catalog_product_entity_int')],
'cpsd.' . $productLinkField . ' = cpe.' . $productLinkField . ' AND cpsd.store_id = 0'
. ' AND cpsd.attribute_id = ' . $statusAttributeId,
[]
)->joinLeft(
['cpss' => $this->getTable('catalog_product_entity_int')],
'cpss.' . $productLinkField . ' = cpe.' . $productLinkField . ' AND cpss.attribute_id = cpsd.attribute_id' .
' AND cpss.store_id = ' .
$store->getId(),
[]
)->joinInner(
['cpvd' => $this->getTable('catalog_product_entity_int')],
'cpvd.' . $productLinkField . ' = cpe. ' . $productLinkField . ' AND cpvd.store_id = 0' .
' AND cpvd.attribute_id = ' .
$visibilityAttributeId,
[]
)->joinLeft(
['cpvs' => $this->getTable('catalog_product_entity_int')],
'cpvs.' . $productLinkField . ' = cpe.' . $productLinkField .
' AND cpvs.attribute_id = cpvd.attribute_id ' . 'AND cpvs.store_id = ' .
$store->getId(),
[]
)->joinInner(
['ccad' => $this->getTable('catalog_category_entity_int')],
'ccad.' . $categoryLinkField . ' = cc.' . $categoryLinkField . ' AND ccad.store_id = 0' .
' AND ccad.attribute_id = ' . $isAnchorAttributeId,
[]
)->joinLeft(
['ccas' => $this->getTable('catalog_category_entity_int')],
'ccas.' . $categoryLinkField . ' = cc.' . $categoryLinkField
. ' AND ccas.attribute_id = ccad.attribute_id AND ccas.store_id = ' .
$store->getId(),
[]
)->where(
'cpw.website_id = ?',
$store->getWebsiteId()
)->where(
$this->connection->getIfNullSql('cpss.value', 'cpsd.value') . ' = ?',
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
)->where(
$this->connection->getIfNullSql('cpvs.value', 'cpvd.value') . ' IN (?)',
[
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_CATALOG,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_SEARCH,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
]
)->where(
$this->connection->getIfNullSql('ccas.value', 'ccad.value') . ' = ?',
1
)->columns(
[
'category_id' => 'cc.entity_id',
'product_id' => 'ccp.product_id',
'position' => new \Zend_Db_Expr(
$this->connection->getIfNullSql('ccp2.position', 'MIN(ccp.position) + 10000')
),
'is_parent' => new \Zend_Db_Expr('0'),
'store_id' => new \Zend_Db_Expr($store->getId()),
'visibility' => new \Zend_Db_Expr($this->connection->getIfNullSql('cpvs.value', 'cpvd.value')),
]
);
$this->addFilteringByChildProductsToSelect($select, $store);
return $select;
}
/**
* Get temporary table name
*
* Get temporary table name for concurrent indexing in persistent connection
* Temp table name is NOT shared between action instances and each action has it's own temp tree index
*
* @return string
* @since 101.0.0
*/
protected function getTemporaryTreeIndexTableName()
{
if (empty($this->tempTreeIndexTableName)) {
$this->tempTreeIndexTableName = $this->connection->getTableName('temp_catalog_category_tree_index')
. '_'
. substr(sha1(time() . random_int(0, 999999999)), 0, 8);
}
return $this->tempTreeIndexTableName;
}
/**
* Build and populate the temporary category tree index table
*
* Returns the name of the temporary table to use in queries.
*
* @return string
* @since 101.0.0
*/
protected function makeTempCategoryTreeIndex()
{
// Note: this temporary table is per-connection, so won't conflict by prefix.
$temporaryName = $this->getTemporaryTreeIndexTableName();
$temporaryTable = $this->connection->newTable($temporaryName);
$temporaryTable->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'unsigned' => true]
);
$temporaryTable->addColumn(
'child_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'unsigned' => true]
);
// Each entry will be unique.
$temporaryTable->addIndex(
'idx_primary',
['parent_id', 'child_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_PRIMARY]
);
$temporaryTable->addIndex(
'child_id',
['child_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_INDEX]
);
// Drop the temporary table in case it already exists on this (persistent?) connection.
$this->connection->dropTemporaryTable($temporaryName);
$this->connection->createTemporaryTable($temporaryTable);
$this->fillTempCategoryTreeIndex($temporaryName);
return $temporaryName;
}
/**
* Populate the temporary category tree index table
*
* @param string $temporaryName
* @since 101.0.0
*/
protected function fillTempCategoryTreeIndex($temporaryName)
{
$isActiveAttributeId = $this->config->getAttribute(
\Magento\Catalog\Model\Category::ENTITY,
'is_active'
)->getId();
$categoryMetadata = $this->metadataPool->getMetadata(\Magento\Catalog\Api\Data\CategoryInterface::class);
$categoryLinkField = $categoryMetadata->getLinkField();
$selects = $this->prepareSelectsByRange(
$this->connection->select()
->from(
['c' => $this->getTable('catalog_category_entity')],
['entity_id', 'path']
)->joinInner(
['ccacd' => $this->getTable('catalog_category_entity_int')],
'ccacd.' . $categoryLinkField . ' = c.' . $categoryLinkField . ' AND ccacd.store_id = 0' .
' AND ccacd.attribute_id = ' . $isActiveAttributeId,
[]
)->joinLeft(
['ccacs' => $this->getTable('catalog_category_entity_int')],
'ccacs.' . $categoryLinkField . ' = c.' . $categoryLinkField
. ' AND ccacs.attribute_id = ccacd.attribute_id AND ccacs.store_id = ' .
$this->getCurrentStore()->getId(),
[]
)->where(
$this->connection->getIfNullSql('ccacs.value', 'ccacd.value') . ' = ?',
1
),
'entity_id'
);
foreach ($selects as $select) {
$values = [];
$categories = $this->connection->fetchAll($select);
foreach ($categories as $category) {
$categoriesTree = explode('/', $category['path']);
foreach ($categoriesTree as $parentId) {
if (!in_array($this->getCurrentStore()->getRootCategoryId(), $categoriesTree, true)) {
break;
}
if ($parentId !== $category['entity_id']) {
$values[] = [$parentId, $category['entity_id']];
}
}
}
if (count($values) > 0) {
$this->connection->insertArray($temporaryName, ['parent_id', 'child_id'], $values);
}
}
}
/**
* Retrieve select for reindex products of anchor categories
*
* @param Store $store
* @return Select
*/
protected function getAnchorCategoriesSelect(Store $store)
{
if (!$this->hasAnchorSelect($store)) {
$this->anchorSelects[$store->getId()] = $this->createAnchorSelect($store);
}
return $this->anchorSelects[$store->getId()];
}
/**
* Reindex products of anchor categories
*
* @param Store $store
* @return void
*/
protected function reindexAnchorCategories(Store $store)
{
$selects = $this->prepareSelectsByRange($this->getAnchorCategoriesSelect($store), 'entity_id');
foreach ($selects as $select) {
$this->connection->query(
$this->connection->insertFromSelect(
$select,
$this->getIndexTable($store->getId()),
['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
\Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE
)
);
}
}
/**
* Get select for all products
*
* @param Store $store
* @return Select
* @throws \Exception when metadata not found for ProductInterface
*/
protected function getAllProducts(Store $store)
{
if (!isset($this->productsSelects[$store->getId()])) {
$statusAttributeId = $this->config->getAttribute(Product::ENTITY, 'status')->getId();
$visibilityAttributeId = $this->config->getAttribute(Product::ENTITY, 'visibility')->getId();
$metadata = $this->metadataPool->getMetadata(ProductInterface::class);
$linkField = $metadata->getLinkField();
$select = $this->connection->select()->from(
['cp' => $this->getTable('catalog_product_entity')],
[]
)->joinInner(
['cpw' => $this->getTable('catalog_product_website')],
'cpw.product_id = cp.entity_id',
[]
)->joinInner(
['cpsd' => $this->getTable('catalog_product_entity_int')],
'cpsd.' . $linkField . ' = cp.' . $linkField . ' AND cpsd.store_id = 0' .
' AND cpsd.attribute_id = ' .
$statusAttributeId,
[]
)->joinLeft(
['cpss' => $this->getTable('catalog_product_entity_int')],
'cpss.' . $linkField . ' = cp.' . $linkField . ' AND cpss.attribute_id = cpsd.attribute_id' .
' AND cpss.store_id = ' .
$store->getId(),
[]
)->joinInner(
['cpvd' => $this->getTable('catalog_product_entity_int')],
'cpvd.' . $linkField . ' = cp.' . $linkField . ' AND cpvd.store_id = 0' .
' AND cpvd.attribute_id = ' .
$visibilityAttributeId,
[]
)->joinLeft(
['cpvs' => $this->getTable('catalog_product_entity_int')],
'cpvs.' . $linkField . ' = cp.' . $linkField . ' AND cpvs.attribute_id = cpvd.attribute_id ' .
' AND cpvs.store_id = ' .
$store->getId(),
[]
)->joinLeft(
['ccp' => $this->getTable('catalog_category_product')],
'ccp.product_id = cp.entity_id',
[]
)->where(
'cpw.website_id = ?',
$store->getWebsiteId()
)->where(
$this->connection->getIfNullSql('cpss.value', 'cpsd.value') . ' = ?',
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
)->where(
$this->connection->getIfNullSql('cpvs.value', 'cpvd.value') . ' IN (?)',
[
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_CATALOG,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_SEARCH,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
]
)->group(
'cp.entity_id'
)->columns(
[
'category_id' => new \Zend_Db_Expr($store->getRootCategoryId()),
'product_id' => 'cp.entity_id',
'position' => new \Zend_Db_Expr(
$this->connection->getCheckSql('ccp.product_id IS NOT NULL', 'MIN(ccp.position)', '10000')
),
'is_parent' => new \Zend_Db_Expr(
$this->connection->getCheckSql('ccp.product_id IS NOT NULL', '1', '0')
),
'store_id' => new \Zend_Db_Expr($store->getId()),
'visibility' => new \Zend_Db_Expr(
$this->connection->getIfNullSql('cpvs.value', 'cpvd.value')
),
]
);
$this->productsSelects[$store->getId()] = $select;
}
return $this->productsSelects[$store->getId()];
}
/**
* Check whether indexation of root category is needed
*
* @return bool
*/
protected function isIndexRootCategoryNeeded()
{
return true;
}
/**
* Reindex all products to root category
*
* @param Store $store
* @return void
*/
protected function reindexRootCategory(Store $store)
{
if ($this->isIndexRootCategoryNeeded()) {
$selects = $this->prepareSelectsByRange(
$this->getAllProducts($store),
'entity_id',
self::RANGE_PRODUCT_STEP
);
foreach ($selects as $select) {
$this->connection->query(
$this->connection->insertFromSelect(
$select,
$this->getIndexTable($store->getId()),
['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
\Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE
)
);
}
}
}
}