-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathImport.php
954 lines (866 loc) · 29.2 KB
/
Import.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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
<?php
/**
* Copyright 2011 Adobe
* All Rights Reserved.
*/
namespace Magento\ImportExport\Model;
use Magento\Eav\Model\Entity\Attribute;
use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\ValidatorException;
use Magento\Framework\Filesystem;
use Magento\Framework\HTTP\Adapter\FileTransferFactory;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Framework\Math\Random;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\ImportExport\Helper\Data as DataHelper;
use Magento\ImportExport\Model\Export\Adapter\CsvFactory;
use Magento\ImportExport\Model\Import\AbstractEntity as ImportAbstractEntity;
use Magento\ImportExport\Model\Import\AbstractSource;
use Magento\ImportExport\Model\Import\Adapter;
use Magento\ImportExport\Model\Import\ConfigInterface;
use Magento\ImportExport\Model\Import\Entity\AbstractEntity;
use Magento\ImportExport\Model\Import\Entity\Factory;
use Magento\ImportExport\Model\Import\EntityInterface;
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError;
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
use Magento\ImportExport\Model\ResourceModel\Import\Data;
use Magento\ImportExport\Model\Source\Import\AbstractBehavior;
use Magento\ImportExport\Model\Source\Import\Behavior\Factory as BehaviorFactory;
use Magento\ImportExport\Model\Source\Upload;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Psr\Log\LoggerInterface;
/**
* Import model
*
* @api
*
* @method string getBehavior() getBehavior()
* @method self setEntity() setEntity(string $value)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.TooManyFields)
* @since 100.0.2
*/
class Import extends AbstractModel
{
public const BEHAVIOR_APPEND = 'append';
public const BEHAVIOR_ADD_UPDATE = 'add_update';
public const BEHAVIOR_REPLACE = 'replace';
public const BEHAVIOR_DELETE = 'delete';
public const BEHAVIOR_CUSTOM = 'custom';
/**
* Import source file.
*/
public const FIELD_NAME_SOURCE_FILE = 'import_file';
/**
* Import image archive.
*/
public const FIELD_NAME_IMG_ARCHIVE_FILE = 'import_image_archive';
/**
* Import images file directory.
*/
public const FIELD_NAME_IMG_FILE_DIR = 'import_images_file_dir';
/**
* Allowed errors count field name
*/
public const FIELD_NAME_ALLOWED_ERROR_COUNT = 'allowed_error_count';
/**
* Validation strategy field name
*/
public const FIELD_NAME_VALIDATION_STRATEGY = 'validation_strategy';
/**
* Import field separator.
*/
public const FIELD_FIELD_SEPARATOR = '_import_field_separator';
/**
* Import multiple value separator.
*/
public const FIELD_FIELD_MULTIPLE_VALUE_SEPARATOR = '_import_multiple_value_separator';
/**
* Import empty attribute value constant.
*/
public const FIELD_EMPTY_ATTRIBUTE_VALUE_CONSTANT = '_import_empty_attribute_value_constant';
/**
* Id of the `importexport_importdata` row after validation.
*/
public const FIELD_IMPORT_IDS = '_import_ids';
/**
* Allow multiple values wrapping in double quotes for additional attributes.
*/
public const FIELDS_ENCLOSURE = 'fields_enclosure';
/**
* default delimiter for several values in one cell as default for FIELD_FIELD_MULTIPLE_VALUE_SEPARATOR
*/
public const DEFAULT_GLOBAL_MULTI_VALUE_SEPARATOR = ',';
/**
* Import empty attribute default value
*/
public const DEFAULT_EMPTY_ATTRIBUTE_VALUE_CONSTANT = '__EMPTY__VALUE__';
public const DEFAULT_SIZE = 50;
public const MAX_IMPORT_CHUNKS = 4;
public const IMPORT_HISTORY_DIR = 'import_history/';
public const IMPORT_DIR = 'import/';
/**
* @var EntityInterface
*/
protected $_entityAdapter;
/**
* @Deprecated Property isn't used
* @var DataHelper
*/
protected $_importExportData = null;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $_coreConfig;
/**
* @var ConfigInterface
*/
protected $_importConfig;
/**
* @var Factory
*/
protected $_entityFactory;
/**
* @var Data
*/
protected $_importData;
/**
* @var CsvFactory
*/
protected $_csvFactory;
/**
* @Deprecated Property isn't used
* @var FileTransferFactory
*/
protected $_httpFactory;
/**
* @var UploaderFactory
*/
protected $_uploaderFactory;
/**
* @var IndexerRegistry
*/
protected $indexerRegistry;
/**
* @var BehaviorFactory
*/
protected $_behaviorFactory;
/**
* @var Filesystem
*/
protected $_filesystem;
/**
* @var History
*/
private $importHistoryModel;
/**
* @var DateTime
*/
private $localeDate;
/**
* @var ManagerInterface
*/
private $messageManager;
/**
* @Deprecated Property isn't used
* @var Random
*/
private $random;
/**
* @var Upload
*/
private $upload;
/**
* @var LocaleEmulatorInterface
*/
private $localeEmulator;
/**
* @param LoggerInterface $logger
* @param Filesystem $filesystem
* @param DataHelper $importExportData
* @param ScopeConfigInterface $coreConfig
* @param ConfigInterface $importConfig
* @param Factory $entityFactory
* @param Data $importData
* @param CsvFactory $csvFactory
* @param FileTransferFactory $httpFactory
* @param UploaderFactory $uploaderFactory
* @param Factory $behaviorFactory
* @param IndexerRegistry $indexerRegistry
* @param History $importHistoryModel
* @param DateTime $localeDate
* @param array $data
* @param ManagerInterface|null $messageManager
* @param Random|null $random
* @param Upload|null $upload
* @param LocaleEmulatorInterface|null $localeEmulator
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
LoggerInterface $logger,
Filesystem $filesystem,
DataHelper $importExportData,
ScopeConfigInterface $coreConfig,
ConfigInterface $importConfig,
Factory $entityFactory,
Data $importData,
CsvFactory $csvFactory,
FileTransferFactory $httpFactory,
UploaderFactory $uploaderFactory,
BehaviorFactory $behaviorFactory,
IndexerRegistry $indexerRegistry,
History $importHistoryModel,
DateTime $localeDate,
array $data = [],
?ManagerInterface $messageManager = null,
?Random $random = null,
?Upload $upload = null,
?LocaleEmulatorInterface $localeEmulator = null
) {
$this->_importExportData = $importExportData;
$this->_coreConfig = $coreConfig;
$this->_importConfig = $importConfig;
$this->_entityFactory = $entityFactory;
$this->_importData = $importData;
$this->_csvFactory = $csvFactory;
$this->_httpFactory = $httpFactory;
$this->_uploaderFactory = $uploaderFactory;
$this->indexerRegistry = $indexerRegistry;
$this->_behaviorFactory = $behaviorFactory;
$this->_filesystem = $filesystem;
$this->importHistoryModel = $importHistoryModel;
$this->localeDate = $localeDate;
$this->messageManager = $messageManager ?: ObjectManager::getInstance()
->get(ManagerInterface::class);
$this->random = $random ?: ObjectManager::getInstance()
->get(Random::class);
$this->upload = $upload ?: ObjectManager::getInstance()
->get(Upload::class);
$this->localeEmulator = $localeEmulator ?: ObjectManager::getInstance()
->get(LocaleEmulatorInterface::class);
parent::__construct($logger, $filesystem, $data);
}
/**
* Returns or create existing instance of entity adapter
*
* @throws LocalizedException
* @return EntityInterface
*/
protected function _getEntityAdapter()
{
if (!$this->_entityAdapter) {
$this->_entityAdapter = $this->localeEmulator->emulate(
$this->createEntityAdapter(...),
$this->getData('locale') ?: null
);
}
return $this->_entityAdapter;
}
/**
* Create instance of entity adapter and return it
*
* @throws LocalizedException
* @return EntityInterface
*/
private function createEntityAdapter()
{
if (!$this->_entityAdapter) {
$entities = $this->_importConfig->getEntities();
if (isset($entities[$this->getEntity()])) {
try {
$this->_entityAdapter = $this->_entityFactory->create($entities[$this->getEntity()]['model']);
} catch (\Exception $e) {
$this->_logger->critical($e);
throw new LocalizedException(
__('Please enter a correct entity model.')
);
}
if (!$this->_entityAdapter instanceof AbstractEntity &&
!$this->_entityAdapter instanceof ImportAbstractEntity
) {
throw new LocalizedException(
__(
'The entity adapter object must be an instance of %1 or %2.',
AbstractEntity::class,
ImportAbstractEntity::class
)
);
}
// check for entity codes integrity
if ($this->getEntity() != $this->_entityAdapter->getEntityTypeCode()) {
throw new LocalizedException(
__('The input entity code is not equal to entity adapter code.')
);
}
} else {
throw new LocalizedException(__('Please enter a correct entity.'));
}
$this->_entityAdapter->setParameters($this->getData());
}
return $this->_entityAdapter;
}
/**
* Returns source adapter object.
*
* @Deprecated
* @see \Magento\ImportExport\Model\Import\Source\Factory::create()
* @param string $sourceFile Full path to source file
* @return AbstractSource
* @throws FileSystemException
*/
protected function _getSourceAdapter($sourceFile)
{
return Adapter::findAdapterFor(
$sourceFile,
$this->_filesystem->getDirectoryWrite(DirectoryList::ROOT),
$this->getData(self::FIELD_FIELD_SEPARATOR)
);
}
/**
* Return operation result messages
*
* @param ProcessingErrorAggregatorInterface $validationResult
* @return string[]
* @throws LocalizedException
*/
public function getOperationResultMessages(ProcessingErrorAggregatorInterface $validationResult)
{
$messages = [];
if ($this->getProcessedRowsCount()) {
if ($validationResult->isErrorLimitExceeded()) {
$messages[] = __('Data validation failed. Please fix the following errors and upload the file again.');
// errors info
foreach ($validationResult->getRowsGroupedByErrorCode() as $errorMessage => $rows) {
$error = $errorMessage . ' ' . __('in row(s)') . ': ' . implode(', ', $rows);
$messages[] = $error;
}
} else {
if ($this->isImportAllowed()) {
$messages[] = __('The validation is complete.');
} else {
$messages[] = __('The file is valid, but we can\'t import it for some reason.');
}
}
$messages[] = __(
'Checked rows: %1, checked entities: %2, invalid rows: %3, total errors: %4',
$this->getProcessedRowsCount(),
$this->getProcessedEntitiesCount(),
$validationResult->getInvalidRowsCount(),
$validationResult->getErrorsCount(
[
ProcessingError::ERROR_LEVEL_CRITICAL,
ProcessingError::ERROR_LEVEL_NOT_CRITICAL
]
)
);
} else {
$messages[] = __('This file does not contain any data.');
}
return $messages;
}
/**
* Get attribute type for upcoming validation.
*
* @param AbstractAttribute|Attribute $attribute
* @return string
* phpcs:disable Magento2.Functions.StaticFunction
*/
public static function getAttributeType(AbstractAttribute $attribute)
{
$frontendInput = $attribute->getFrontendInput();
if ($attribute->usesSource() && in_array($frontendInput, ['select', 'multiselect', 'boolean'])) {
return $frontendInput;
} elseif ($attribute->isStatic()) {
return $frontendInput == 'date' ? 'datetime' : 'varchar';
} else {
return $attribute->getBackendType();
}
}
/**
* DB data source model getter.
*
* @return Data
*/
public function getDataSourceModel()
{
return $this->_importData;
}
/**
* Default import behavior getter.
*
* @static
* @return string
*/
public static function getDefaultBehavior()
{
return self::BEHAVIOR_APPEND;
}
/**
* Override standard entity getter.
*
* @throws LocalizedException
* @return string
*/
public function getEntity()
{
$entities = $this->_importConfig->getEntities();
if (empty($this->_data['entity'])
|| !empty($this->_data['entity']) && !isset($entities[$this->_data['entity']])
) {
throw new LocalizedException(__('Entity is unknown'));
}
return $this->_data['entity'];
}
/**
* Returns number of checked entities.
*
* @return int
* @throws LocalizedException
*/
public function getProcessedEntitiesCount()
{
return $this->_getEntityAdapter()->getProcessedEntitiesCount();
}
/**
* Returns number of checked rows.
*
* @return int
* @throws LocalizedException
*/
public function getProcessedRowsCount()
{
return $this->_getEntityAdapter()->getProcessedRowsCount();
}
/**
* Import/Export working directory (source files, result files, lock files etc.).
*
* @return string
*/
public function getWorkingDir()
{
return $this->_varDirectory->getAbsolutePath('importexport/');
}
/**
* Import source file structure to DB.
*
* @return bool
* @throws LocalizedException
*/
public function importSource()
{
return $this->localeEmulator->emulate(
$this->importSourceCallback(...),
$this->getData('locale') ?: null
);
}
/**
* Import source file structure to DB.
*
* @return bool
* @throws LocalizedException
*/
private function importSourceCallback()
{
$ids = $this->getImportIds();
$this->_getEntityAdapter()->setIds($ids);
//Validating images temporary directory path if the constraint has been provided
if ($this->hasData('images_base_directory')
&& $this->getData('images_base_directory') instanceof Filesystem\Directory\ReadInterface
) {
/** @var Filesystem\Directory\ReadInterface $imagesDirectory */
$imagesDirectory = $this->getData('images_base_directory');
if (!$imagesDirectory->isReadable()) {
$rootWrite = $this->_filesystem->getDirectoryWrite(DirectoryList::ROOT);
$rootWrite->create($imagesDirectory->getAbsolutePath());
}
try {
$this->setData(
self::FIELD_NAME_IMG_FILE_DIR,
$imagesDirectory->getAbsolutePath($this->getData(self::FIELD_NAME_IMG_FILE_DIR))
);
$this->_getEntityAdapter()->setParameters($this->getData());
} catch (ValidatorException $exception) {
throw new LocalizedException(__('Images file directory is outside required directory'), $exception);
}
}
$this->importHistoryModel->updateReport($this);
$this->addLogComment(__('Begin import of "%1" with "%2" behavior', $this->getEntity(), $this->getBehavior()));
$result = $this->processImport();
$this->getDataSourceModel()->markProcessedBunches($ids);
if ($result) {
$logComments = [
__(
'Checked rows: %1, checked entities: %2, invalid rows: %3, total errors: %4',
$this->getProcessedRowsCount(),
$this->getProcessedEntitiesCount(),
$this->getErrorAggregator()->getInvalidRowsCount(),
$this->getErrorAggregator()->getErrorsCount()
)
];
foreach ($this->getErrorAggregator()->getAllErrors() as $error) {
$logComments[] = $error->getErrorMessage();
}
$logComments[] = $this->getForceImport() == '0' && $this->getErrorAggregator()->getErrorsCount() > 0 ?
__('The import was not successful.') : __('The import was successful.');
$this->addLogComment($logComments);
$this->importHistoryModel->updateReport($this, true);
} else {
$this->importHistoryModel->invalidateReport($this);
}
return $result;
}
/**
* Get entity import ids
*
* @return array
* @throws LocalizedException
*/
private function getImportIds(): array
{
$ids = $this->_getEntityAdapter()->getIds();
if (empty($ids)) {
$idsFromPostData = $this->getData(self::FIELD_IMPORT_IDS);
if (null !== $idsFromPostData && '' !== $idsFromPostData) {
$ids = explode(",", $idsFromPostData);
}
}
return $ids;
}
/**
* Process import.
*
* @return bool
* @throws LocalizedException
*/
protected function processImport()
{
return $this->_getEntityAdapter()->importData();
}
/**
* Import possibility getter.
*
* @return bool
* @throws LocalizedException
*/
public function isImportAllowed()
{
return $this->_getEntityAdapter()->isImportAllowed();
}
/**
* Get error aggregator instance.
*
* @return ProcessingErrorAggregatorInterface
* @throws LocalizedException
*/
public function getErrorAggregator()
{
return $this->_getEntityAdapter()->getErrorAggregator();
}
/**
* Move uploaded file.
*
* @throws LocalizedException
* @return string Source file path
*/
public function uploadSource()
{
$entity = $this->getEntity();
$result = $this->upload->uploadSource($entity);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$extension = pathinfo($result['file'], PATHINFO_EXTENSION);
$sourceFile = $this->getWorkingDir() . $entity . '.' . $extension;
$sourceFileRelative = $this->_varDirectory->getRelativePath($sourceFile);
$this->_removeBom($sourceFile);
$this->createHistoryReport($sourceFileRelative, $entity, $extension, $result);
return $sourceFile;
}
/**
* Move uploaded file and provide source instance.
*
* @return Import\AbstractSource
* @throws LocalizedException
* @since 100.2.7
*/
public function uploadFileAndGetSource()
{
$sourceFile = $this->uploadSource();
try {
$source = $this->_getSourceAdapter($sourceFile);
} catch (\Exception $e) {
$this->_varDirectory->delete($this->_varDirectory->getRelativePath($sourceFile));
throw new LocalizedException(__($e->getMessage()));
}
return $source;
}
/**
* Remove BOM from a file
*
* @param string $sourceFile
* @return $this
* @throws FileSystemException
*/
protected function _removeBom($sourceFile)
{
$driver = $this->_varDirectory->getDriver();
$string = $driver->fileGetContents($this->_varDirectory->getAbsolutePath($sourceFile));
if ($string !== false && substr($string, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
$string = substr($string, 3);
$driver->filePutContents($this->_varDirectory->getAbsolutePath($sourceFile), $string);
}
return $this;
}
/**
* Validates source file and returns validation result
*
* @param AbstractSource $source
* @return bool
* @throws LocalizedException
*/
public function validateSource(AbstractSource $source)
{
return $this->localeEmulator->emulate(
fn () => $this->validateSourceCallback($source),
$this->getData('locale') ?: null
);
}
/**
* Validates source file and returns validation result
*
* Before validate data the method requires to initialize error aggregator (ProcessingErrorAggregatorInterface)
* with 'validation strategy' and 'allowed error count' values to allow using this parameters in validation process.
*
* @param AbstractSource $source
* @return bool
* @throws LocalizedException
*/
private function validateSourceCallback(AbstractSource $source)
{
$this->addLogComment(__('Begin data validation'));
$errorAggregator = $this->getErrorAggregator();
$errorAggregator->initValidationStrategy(
$this->getData(self::FIELD_NAME_VALIDATION_STRATEGY),
$this->getData(self::FIELD_NAME_ALLOWED_ERROR_COUNT)
);
try {
$adapter = $this->_getEntityAdapter()->setSource($source);
$adapter->validateData();
} catch (\Exception $e) {
$errorAggregator->addError(
AbstractEntity::ERROR_CODE_SYSTEM_EXCEPTION,
ProcessingError::ERROR_LEVEL_CRITICAL,
null,
null,
$e->getMessage()
);
}
$messages = $this->getOperationResultMessages($errorAggregator);
$this->addLogComment($messages);
if ($errorAggregator->isErrorLimitExceeded()) {
return false;
}
if ($this->getProcessedRowsCount() <= $errorAggregator->getInvalidRowsCount()) {
$this->addLogComment(__('There are no valid rows to import.'));
return false;
}
$this->addLogComment(__('Import data validation is complete.'));
return true;
}
/**
* Invalidate indexes by process codes.
*
* @return $this
* @throws LocalizedException
*/
public function invalidateIndex()
{
$relatedIndexers = $this->_importConfig->getRelatedIndexers($this->getEntity());
if (empty($relatedIndexers)) {
return $this;
}
foreach (array_keys($relatedIndexers) as $indexerId) {
try {
$indexer = $this->indexerRegistry->get($indexerId);
if (!$indexer->isScheduled()) {
$indexer->invalidate();
}
// phpcs:disable Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
} catch (\InvalidArgumentException $e) {
}
}
return $this;
}
/**
* Gets array of entities and appropriate behaviours
* array(
* <entity_code> => array(
* 'token' => <behavior_class_name>,
* 'code' => <behavior_model_code>,
* ),
* ...
* )
*
* @return array
* @throws LocalizedException
*/
public function getEntityBehaviors()
{
$behaviourData = [];
$entities = $this->_importConfig->getEntities();
foreach ($entities as $entityCode => $entityData) {
$behaviorClassName = isset($entityData['behaviorModel']) ? $entityData['behaviorModel'] : null;
if ($behaviorClassName && class_exists($behaviorClassName)) {
/** @var $behavior AbstractBehavior */
$behavior = $this->_behaviorFactory->create($behaviorClassName);
$behaviourData[$entityCode] = [
'token' => $behaviorClassName,
'code' => $behavior->getCode() . '_behavior',
'notes' => $behavior->getNotes($entityCode),
];
} else {
throw new LocalizedException(
__('The behavior token for %1 is invalid.', $entityCode)
);
}
}
return $behaviourData;
}
/**
* Get array of unique entity behaviors
* array(
* <behavior_model_code> => <behavior_class_name>,
* ...
* )
*
* @return array
* @throws LocalizedException
*/
public function getUniqueEntityBehaviors()
{
$uniqueBehaviors = [];
$behaviourData = $this->getEntityBehaviors();
foreach ($behaviourData as $behavior) {
$behaviorCode = $behavior['code'];
if (!isset($uniqueBehaviors[$behaviorCode])) {
$uniqueBehaviors[$behaviorCode] = $behavior['token'];
}
}
return $uniqueBehaviors;
}
/**
* Retrieve processed reports entity types
*
* @param string|null $entity
* @return bool
* @throws LocalizedException
*/
public function isReportEntityType($entity = null)
{
$result = false;
if (!$entity) {
$entity = $this->getEntity();
}
if ($entity !== null && $this->_getEntityAdapter()->getEntityTypeCode() != $entity) {
$entities = $this->_importConfig->getEntities();
if (isset($entities[$entity])) {
try {
$result = $this->_getEntityAdapter()->isNeedToLogInHistory();
} catch (\Exception $e) {
throw new LocalizedException(
__('Please enter a correct entity model')
);
}
} else {
throw new LocalizedException(__('Please enter a correct entity model'));
}
} else {
$result = $this->_getEntityAdapter()->isNeedToLogInHistory();
}
return $result;
}
/**
* Create history report
*
* @param string $sourceFileRelative
* @param string $entity
* @param string $extension
* @param array $result
* @return $this
* @throws LocalizedException
*/
protected function createHistoryReport($sourceFileRelative, $entity, $extension = null, $result = null)
{
if ($this->isReportEntityType($entity)) {
if (is_array($sourceFileRelative)) {
$fileName = $sourceFileRelative['file_name'];
$sourceFileRelative = $this->_varDirectory->getRelativePath(self::IMPORT_DIR . $fileName);
} elseif (isset($result['name'])) {
$fileName = $result['name'];
} elseif ($extension !== null) {
$fileName = $entity . $extension;
} else {
// phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
$fileName = basename($sourceFileRelative);
}
$copyName = $this->localeDate->gmtTimestamp() . '_' . $fileName;
$copyFile = self::IMPORT_HISTORY_DIR . $copyName;
try {
if ($this->_varDirectory->isExist($sourceFileRelative)) {
$this->_varDirectory->copyFile($sourceFileRelative, $copyFile);
} else {
$content = $this->_varDirectory->getDriver()->fileGetContents($sourceFileRelative);
$this->_varDirectory->writeFile($copyFile, $content);
}
} catch (FileSystemException $e) {
throw new LocalizedException(__('Source file copying failed'));
}
$this->importHistoryModel->addReport($copyName);
}
return $this;
}
/**
* Get count of created items
*
* @return int
* @throws LocalizedException
*/
public function getCreatedItemsCount()
{
return $this->_getEntityAdapter()->getCreatedItemsCount();
}
/**
* Get count of updated items
*
* @return int
* @throws LocalizedException
*/
public function getUpdatedItemsCount()
{
return $this->_getEntityAdapter()->getUpdatedItemsCount();
}
/**
* Get count of deleted items
*
* @return int
* @throws LocalizedException
*/
public function getDeletedItemsCount()
{
return $this->_getEntityAdapter()->getDeletedItemsCount();
}
/**
* Retrieve Ids of Validated Rows
*
* @return int[]
*/
public function getValidatedIds() : array
{
return $this->_getEntityAdapter()->getIds() ?? [];
}
}