src/EventListener/ExcelUploadListener.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Exception;
  4. use Pimcore\Model\Element\ValidationException;
  5. use Pimcore\Event\Model\ElementEventInterface;
  6. use Pimcore\Event\Model\DataObjectEvent;
  7. use Pimcore\Event\Model\AssetEvent;
  8. use Pimcore\Db;
  9. use Pimcore\Model\DataObject\ExcelUpload;
  10. use Pimcore\Log\ApplicationLogger;
  11. use App\Services\BackgroundProcessService;
  12. use PhpOffice\PhpSpreadsheet\IOFactory;
  13. class ExcelUploadListener
  14. {
  15.     public function __construct(private ApplicationLogger $applicationLogger, private BackgroundProcessService $backgroundProcessService)
  16.     {
  17.     }
  18.     /**
  19.      * @param ElementEventInterface $event
  20.      */
  21.     public function onPreAdd(ElementEventInterface $event)
  22.     {
  23.         if ($event instanceof DataObjectEvent) {
  24.            $object $event->getObject();
  25.            if (!$object instanceof ExcelUpload) {
  26.                return;
  27.            }
  28.            $count ExcelUpload::getList()->count();
  29.            if ($count >= 1) {
  30.                throw new ValidationException('We\'re not allowing to create object more than one of this class.');
  31.            }
  32.         }
  33.     }
  34.     public function onPreAssetAdd(AssetEvent $event)
  35.     {
  36.         if ($event instanceof AssetEvent) {
  37.             // $excelMimes = array('text/xls', 'text/xlsx', 'application/excel', 'application/vnd.msexcel', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  38.             // if (!in_array($event->getAsset()->getMimeType(), $excelMimes)) {
  39.             //     $event->getAsset()->delete();
  40.             //     throw new Exception('Please upload excel file.');
  41.             // }
  42.             // if ($event->getAsset()->getFileSize() > 10485760) {
  43.             //     $event->getAsset()->delete();
  44.             //     throw new Exception('Maximum file size should be 10MB');
  45.             // }
  46.         }
  47.     }
  48.     /**
  49.      * @param ElementEventInterface $event
  50.      */
  51.     public function onPreUpdate(ElementEventInterface $event)
  52.     {
  53.         if ($event instanceof DataObjectEvent) {
  54.             $object $event->getObject();
  55.             if ($object instanceof ExcelUpload) {
  56.                 // Perform mandatory validation
  57.                 $this->mandatoryValidation($object);
  58.             }
  59.         }
  60.     }
  61.     /**
  62.      * @param ElementEventInterface $event
  63.      */
  64.     public function onPostUpdate(ElementEventInterface $event)
  65.     {
  66.         if ($event instanceof DataObjectEvent) {
  67.             $object $event->getObject();
  68.             if (!$object instanceof ExcelUpload) {
  69.                 return;
  70.             }
  71.             if (!empty($object->getExcelFile())) {
  72.                 // Execute command
  73.                 $command 'bulk:enrichment';
  74.                 $errorLog $command ' command is executed to enrich bulk data by Excel File.';
  75.                 $this->backgroundProcessService->execute($command$errorLog);
  76.             }
  77.         }
  78.     }
  79.     /**
  80.      * @param object $object
  81.      */
  82.     public function mandatoryValidation($object)
  83.     {
  84.         if (empty($object->getExcelFile())) {
  85.             throw new ValidationException('Please upload enriched excel file.');
  86.         } else {
  87.             $excelMimes = array('text/xls''text/xlsx''application/excel''application/vnd.msexcel''application/vnd.ms-excel''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  88.             
  89.             if (!in_array($object->getExcelFile()->getMimeType(), $excelMimes)) {
  90.                 $object->getExcelFile()->delete();
  91.                 throw new ValidationException('Please upload excel file.');
  92.             }
  93.             if ($object->getExcelFile()->getFileSize() > 10485760) {
  94.                 $object->getExcelFile()->delete();
  95.                 throw new ValidationException('Maximum file size should be 10MB.');
  96.             }
  97.             $excelFile $object->getExcelFile();
  98.             $filePath $excelFile->getLocalFile();
  99.             $expectedColumns = [
  100.                 "Name""Part Number""Mfg Part Number""Brand""Compatible Brands""Category""GRP Price""MSRP",
  101.                 "Core Price""Channel""Channel Price""Distributor""Vendor Price""Store",
  102.                 "Store GRP Price""Store Msrp Price""Store Core Price""UPC""ASIN""PID""CaliforniaProp65""Competitor SKU""Hazardous",
  103.                 "Oversize""Obsolete""Substitute""Substitute Part Number""Saleable In",
  104.                 "Is Returnable""Description""Long Description""Height""Width""Length""Weight",
  105.                 "Box Height""Box Width""Box Length""Spin Image Url""Main Image Url",
  106.                 "Additional Image Url""Subscription Flag""Subscription Term""Required Shipping"
  107.             ];
  108.             $actualColumns $this->readExcelFile($filePath);
  109.             $normalizedActualColumns array_map(fn($columnName) => trim(strtolower(preg_replace('/\(.*\)/'''$columnName))), $actualColumns);
  110.             $normalizedExpectedColumns array_map('strtolower'$expectedColumns);
  111.             $extraColumns array_diff($normalizedActualColumns$normalizedExpectedColumns);
  112.             $missingColumns array_diff($normalizedExpectedColumns$normalizedActualColumns);
  113.             if (count($actualColumns) !== count($expectedColumns) || !empty($extraColumns) || !empty($missingColumns)) {
  114.                 $countMismatchMsg = (count($actualColumns) !== count($expectedColumns)) ? "Count of columns does not match. Expected: " count($expectedColumns) . ", Actual: " count($actualColumns) : '';
  115.                 $extraColumnsMsg = (!empty($extraColumns) ? ", Extra Column Name: " implode(', '$extraColumns) . ',' '');
  116.                 $missingColumnsMsg = (!empty($missingColumns) ? ", Missing Column Name: " implode(', '$missingColumns) : '');
  117.                 $logs $countMismatchMsg $extraColumnsMsg $missingColumnsMsg;
  118.                 $errorMessage rtrim($logs',');
  119.                 throw new ValidationException($errorMessage);
  120.             }
  121.         }
  122.     }
  123.     private function readExcelFile($filePath)
  124.     {
  125.         $spreadsheet IOFactory::load($filePath);
  126.         $excelData $spreadsheet->getActiveSheet()->rangeToArray('A1:' $spreadsheet->getActiveSheet()->getHighestColumn() . '1'NULLTRUEFALSE)[0];
  127.         return $excelData;
  128.     }
  129. }