vendor/pimcore/data-importer/src/Controller/ConfigDataObjectController.php line 47

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Bundle\DataImporterBundle\Controller;
  15. use Cron\CronExpression;
  16. use Exception;
  17. use League\Flysystem\FilesystemOperator;
  18. use Pimcore\Bundle\AdminBundle\Helper\QueryParams;
  19. use Pimcore\Bundle\DataHubBundle\Configuration\Dao;
  20. use Pimcore\Bundle\DataImporterBundle\DataSource\Interpreter\InterpreterFactory;
  21. use Pimcore\Bundle\DataImporterBundle\DataSource\Loader\DataLoaderFactory;
  22. use Pimcore\Bundle\DataImporterBundle\DataSource\Loader\PushLoader;
  23. use Pimcore\Bundle\DataImporterBundle\Exception\InvalidConfigurationException;
  24. use Pimcore\Bundle\DataImporterBundle\Mapping\MappingConfigurationFactory;
  25. use Pimcore\Bundle\DataImporterBundle\Mapping\Type\ClassificationStoreDataTypeService;
  26. use Pimcore\Bundle\DataImporterBundle\Mapping\Type\TransformationDataTypeService;
  27. use Pimcore\Bundle\DataImporterBundle\Preview\PreviewService;
  28. use Pimcore\Bundle\DataImporterBundle\Processing\ImportPreparationService;
  29. use Pimcore\Bundle\DataImporterBundle\Processing\ImportProcessingService;
  30. use Pimcore\Bundle\DataImporterBundle\Settings\ConfigurationPreparationService;
  31. use Pimcore\Controller\Traits\JsonHelperTrait;
  32. use Pimcore\Controller\UserAwareController;
  33. use Pimcore\Logger;
  34. use Pimcore\Model\DataObject;
  35. use Pimcore\Model\DataObject\QuantityValue\Unit;
  36. use Pimcore\Translation\Translator;
  37. use Symfony\Component\HttpFoundation\JsonResponse;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. /**
  41.  * @Route("/admin/pimcoredataimporter/dataobject/config")
  42.  */
  43. class ConfigDataObjectController extends UserAwareController
  44. {
  45.     use JsonHelperTrait;
  46.     public const CONFIG_NAME 'plugin_datahub_config';
  47.     /**
  48.      * @var PreviewService
  49.      */
  50.     protected $previewService;
  51.     /**
  52.      * ConfigDataObjectController constructor.
  53.      *
  54.      * @param PreviewService $previewService
  55.      */
  56.     public function __construct(PreviewService $previewService)
  57.     {
  58.         $this->previewService $previewService;
  59.     }
  60.     /**
  61.      * @Route("/save")
  62.      *
  63.      * @throws Exception
  64.      */
  65.     public function saveAction(Request $request): ?JsonResponse
  66.     {
  67.         $this->checkPermission(self::CONFIG_NAME);
  68.         try {
  69.             $data $request->request->get('data');
  70.             $modificationDate $request->request->getInt('modificationDate');
  71.             if ($modificationDate Dao::getConfigModificationDate()) {
  72.                 throw new Exception('The configuration was modified during editing, please reload the configuration and make your changes again');
  73.             }
  74.             $dataDecoded json_decode($datatrue);
  75.             $name $dataDecoded['general']['name'];
  76.             $dataDecoded['general']['active'] = $dataDecoded['general']['active'] ?? false;
  77.             $config Dao::getByName($name);
  78.             if (!$config->isAllowed('update')) {
  79.                 throw $this->createAccessDeniedHttpException();
  80.             }
  81.             $config->setConfiguration($dataDecoded);
  82.             // @phpstan-ignore-next-line isAllowed return can changed now
  83.             if ($config->isAllowed('read') && $config->isAllowed('update')) {
  84.                 $config->save();
  85.                 return $this->json(['success' => true'modificationDate' => Dao::getConfigModificationDate()]);
  86.             } else {
  87.                 return $this->json(['success' => false'permissionError' => true]);
  88.             }
  89.         } catch (Exception $e) {
  90.             return $this->json(['success' => false'message' => $e->getMessage()]);
  91.         }
  92.     }
  93.     /**
  94.      * @param string $configName
  95.      * @param array $config
  96.      * @param InterpreterFactory $interpreterFactory
  97.      *
  98.      * @return array
  99.      */
  100.     protected function loadAvailableColumnHeaders(
  101.         string $configName,
  102.         array $config,
  103.         InterpreterFactory $interpreterFactory
  104.     ) {
  105.         $previewFilePath $this->previewService->getLocalPreviewFile($configName$this->getPimcoreUser());
  106.         if (is_file($previewFilePath)) {
  107.             try {
  108.                 $interpreter $interpreterFactory->loadInterpreter($configName$config['interpreterConfig'], $config['processingConfig']);
  109.                 $dataPreview $interpreter->previewData($previewFilePath);
  110.                 $columnHeaders $dataPreview->getDataColumnHeaders();
  111.                 // Validate if the column headers are valid JSON. Otherwise take care of the preview file to be deleted.
  112.                 if (!$this->isValidJson($columnHeaders)) {
  113.                     throw new \Exception('Invalid column headers.');
  114.                 }
  115.                 return $columnHeaders;
  116.             } catch (Exception $e) {
  117.                 Logger::warning($e);
  118.             }
  119.         }
  120.         return [];
  121.     }
  122.     protected function isValidJson(array $array): bool
  123.     {
  124.         json_encode($array);
  125.         return json_last_error() === \JSON_ERROR_NONE;
  126.     }
  127.     /**
  128.      * @Route("/get")
  129.      *
  130.      * @param Request $request
  131.      * @param ConfigurationPreparationService $configurationPreparationService
  132.      * @param InterpreterFactory $interpreterFactory
  133.      *
  134.      * @return JsonResponse
  135.      *
  136.      * @throws Exception
  137.      */
  138.     public function getAction(
  139.         Request $request,
  140.         ConfigurationPreparationService $configurationPreparationService,
  141.         InterpreterFactory $interpreterFactory
  142.     ): JsonResponse {
  143.         $this->checkPermission(self::CONFIG_NAME);
  144.         $name $request->query->get('name');
  145.         $config $configurationPreparationService->prepareConfiguration($name);
  146.         return new JsonResponse(
  147.             [
  148.                 'name' => $name,
  149.                 'configuration' => $config,
  150.                 'userPermissions' => $config['userPermissions'],
  151.                 'modificationDate' => Dao::getConfigModificationDate(),
  152.                 'columnHeaders' => $this->loadAvailableColumnHeaders($name$config$interpreterFactory)
  153.             ]
  154.         );
  155.     }
  156.     /**
  157.      * @Route("/upload-preview", methods={"POST"})
  158.      *
  159.      * @param Request $request
  160.      *
  161.      * @return JsonResponse
  162.      *
  163.      * @throws Exception
  164.      */
  165.     public function uploadPreviewDataAction(Request $request)
  166.     {
  167.         try {
  168.             if (array_key_exists('Filedata'$_FILES)) {
  169.                 $filename $_FILES['Filedata']['name'];
  170.                 $sourcePath $_FILES['Filedata']['tmp_name'];
  171.             } else {
  172.                 throw new Exception('The filename of the preview data is empty');
  173.             }
  174.             if (is_file($sourcePath) && filesize($sourcePath) < 1) {
  175.                 throw new Exception('File is empty!');
  176.             } elseif (!is_file($sourcePath)) {
  177.                 throw new Exception('Something went wrong, please check upload_max_filesize and post_max_size in your php.ini and write permissions of your temporary directories.');
  178.             }
  179.             if (filesize($sourcePath) > 10485760) { //10 MB
  180.                 throw new Exception('File it too big for preview file, please create a smaller one');
  181.             }
  182.             $this->previewService->writePreviewFile($request->query->get('config_name'), $sourcePath$this->getPimcoreUser());
  183.             @unlink($sourcePath);
  184.             return new JsonResponse(['success' => true]);
  185.         } catch (Exception $e) {
  186.             Logger::error($e);
  187.             return $this->jsonResponse([
  188.                 'success' => false,
  189.                 'message' => $e->getMessage(),
  190.             ]);
  191.         }
  192.     }
  193.     /**
  194.      * @Route("/copy-preview", methods={"POST"})
  195.      *
  196.      * @param Request $request
  197.      * @param ConfigurationPreparationService $configurationPreparationService
  198.      * @param DataLoaderFactory $dataLoaderFactory
  199.      *
  200.      * @return JsonResponse
  201.      *
  202.      * @throws Exception
  203.      */
  204.     public function copyPreviewDataAction(
  205.         Request $request,
  206.         ConfigurationPreparationService $configurationPreparationService,
  207.         DataLoaderFactory $dataLoaderFactory
  208.     ) {
  209.         try {
  210.             $configName $request->request->get('config_name');
  211.             $currentConfig $request->request->get('current_config');
  212.             $config $configurationPreparationService->prepareConfiguration($configName$currentConfig);
  213.             $loader $dataLoaderFactory->loadDataLoader($config['loaderConfig']);
  214.             if ($loader instanceof PushLoader) {
  215.                 throw new Exception('Cannot copy data from push loader for preview.');
  216.             }
  217.             $sourcePath $loader->loadData();
  218.             if (is_file($sourcePath) && filesize($sourcePath) < 1) {
  219.                 throw new Exception('File is empty!');
  220.             } elseif (!is_file($sourcePath)) {
  221.                 throw new Exception('Something went wrong, please check upload_max_filesize and post_max_size in your php.ini and write permissions of your temporary directories.');
  222.             }
  223.             if (filesize($sourcePath) > 10485760) { //10 MB
  224.                 throw new Exception('File it too big for preview file, please create a smaller one');
  225.             }
  226.             $this->previewService->writePreviewFile($configName$sourcePath$this->getPimcoreUser());
  227.             $loader->cleanup();
  228.             return new JsonResponse(['success' => true]);
  229.         } catch (Exception $e) {
  230.             Logger::error($e);
  231.             return $this->jsonResponse([
  232.                 'success' => false,
  233.                 'message' => $e->getMessage(),
  234.             ]);
  235.         }
  236.     }
  237.     /**
  238.      * @Route("/load-preview-data", methods={"POST"})
  239.      *
  240.      * @param Request $request
  241.      * @param ConfigurationPreparationService $configurationPreparationService
  242.      * @param InterpreterFactory $interpreterFactory
  243.      * @param Translator $translator
  244.      *
  245.      * @return JsonResponse
  246.      *
  247.      * @throws Exception
  248.      */
  249.     public function loadDataPreviewAction(
  250.         Request $request,
  251.         ConfigurationPreparationService $configurationPreparationService,
  252.         InterpreterFactory $interpreterFactory,
  253.         Translator $translator
  254.     ) {
  255.         $configName $request->request->get('config_name');
  256.         $currentConfig $request->request->get('current_config');
  257.         $recordNumber $request->request->getInt('record_number');
  258.         $dataPreview null;
  259.         $hasData false;
  260.         $errorMessage '';
  261.         $previewFilePath $this->previewService->getLocalPreviewFile($configName$this->getPimcoreUser());
  262.         $dataPreviewData = [];
  263.         if (is_file($previewFilePath)) {
  264.             $config $configurationPreparationService->prepareConfiguration($configName$currentConfig);
  265.             $mappedColumns = [];
  266.             foreach (($config['mappingConfig'] ?? []) as $mapping) {
  267.                 if (isset($mapping['dataSourceIndex']) && is_array($mapping['dataSourceIndex'])) {
  268.                     $mappedColumns array_merge($mappedColumns$mapping['dataSourceIndex']);
  269.                 }
  270.             }
  271.             $mappedColumns array_unique($mappedColumns);
  272.             try {
  273.                 $interpreter $interpreterFactory->loadInterpreter($configName$config['interpreterConfig'], $config['processingConfig']);
  274.                 if ($interpreter->fileValid($previewFilePath)) {
  275.                     $dataPreview $interpreter->previewData($previewFilePath$recordNumber$mappedColumns);
  276.                     $hasData true;
  277.                     $preview $dataPreview->getDataPreview();
  278.                     if (!$this->isValidJson($preview)) {
  279.                         unlink($previewFilePath);
  280.                         throw new \Exception('Invalid data preview. Deleted preview data.');
  281.                     }
  282.                     $dataPreviewData $preview;
  283.                 } else {
  284.                     $errorMessage $translator->trans('plugin_pimcore_datahub_data_importer_configpanel_preview_error_invalid_file', [], 'admin');
  285.                 }
  286.             } catch (Exception $e) {
  287.                 Logger::error($e);
  288.                 $errorMessage $translator->trans('plugin_pimcore_datahub_data_importer_configpanel_preview_error_prefix', [], 'admin') . ': ' $e->getMessage();
  289.             }
  290.         }
  291.         return new JsonResponse([
  292.             'dataPreview' => $dataPreviewData,
  293.             'previewRecordIndex' => $dataPreview $dataPreview->getRecordNumber() : 0,
  294.             'hasData' => $hasData,
  295.             'errorMessage' => $errorMessage
  296.         ]);
  297.     }
  298.     /**
  299.      * @Route("/load-column-headers", methods={"POST"})
  300.      *
  301.      * @param Request $request
  302.      * @param ConfigurationPreparationService $configurationPreparationService
  303.      * @param InterpreterFactory $interpreterFactory
  304.      *
  305.      * @return JsonResponse
  306.      *
  307.      * @throws Exception
  308.      */
  309.     public function loadAvailableColumnHeadersAction(
  310.         Request $request,
  311.         ConfigurationPreparationService $configurationPreparationService,
  312.         InterpreterFactory $interpreterFactory
  313.     ) {
  314.         $configName $request->request->get('config_name');
  315.         $currentConfig $request->request->get('current_config');
  316.         $config $configurationPreparationService->prepareConfiguration($configName$currentConfig);
  317.         return new JsonResponse([
  318.             'columnHeaders' => $this->loadAvailableColumnHeaders($configName$config$interpreterFactory)
  319.         ]);
  320.     }
  321.     /**
  322.      * @Route("/load-transformation-result", methods={"POST"})
  323.      *
  324.      * @param Request $request
  325.      * @param ConfigurationPreparationService $configurationPreparationService
  326.      * @param MappingConfigurationFactory $factory
  327.      * @param InterpreterFactory $interpreterFactory
  328.      * @param ImportProcessingService $importProcessingService
  329.      *
  330.      * @return JsonResponse
  331.      *
  332.      * @throws InvalidConfigurationException|Exception
  333.      */
  334.     public function loadTransformationResultPreviewsAction(
  335.         Request $request,
  336.         ConfigurationPreparationService $configurationPreparationService,
  337.         MappingConfigurationFactory $factory,
  338.         InterpreterFactory $interpreterFactory,
  339.         ImportProcessingService $importProcessingService
  340.     ) {
  341.         $configName $request->request->get('config_name');
  342.         $currentConfig $request->request->get('current_config');
  343.         $recordNumber $request->request->getInt('current_preview_record');
  344.         $config $configurationPreparationService->prepareConfiguration($configName$currentConfig);
  345.         $previewFilePath $this->previewService->getLocalPreviewFile($configName$this->getPimcoreUser());
  346.         $importDataRow = [];
  347.         $transformationResults = [];
  348.         $errorMessage '';
  349.         try {
  350.             if (is_file($previewFilePath)) {
  351.                 $interpreter $interpreterFactory->loadInterpreter($configName$config['interpreterConfig'], $config['processingConfig']);
  352.                 $dataPreview $interpreter->previewData($previewFilePath$recordNumber);
  353.                 $importDataRow $dataPreview->getRawData();
  354.             }
  355.             $mapping $factory->loadMappingConfiguration($configName$config['mappingConfig'], true);
  356.             foreach ($mapping as $index => $mappingConfiguration) {
  357.                 $transformationResults[] = $importProcessingService->generateTransformationResultPreview($importDataRow$mappingConfiguration);
  358.             }
  359.         } catch (Exception $e) {
  360.             Logger::error($e);
  361.             $errorMessage $e->getMessage();
  362.         }
  363.         return new JsonResponse([
  364.             'transformationResultPreviews' => $transformationResults,
  365.             'errorMessage' => $errorMessage
  366.         ]);
  367.     }
  368.     /**
  369.      * @Route("/calculate-transformation-result-type", methods={"POST"})
  370.      *
  371.      * @param Request $request
  372.      * @param MappingConfigurationFactory $factory
  373.      * @param ImportProcessingService $importProcessingService
  374.      *
  375.      * @return JsonResponse
  376.      */
  377.     public function calculateTransformationResultTypeAction(
  378.         Request $request,
  379.         MappingConfigurationFactory $factory,
  380.         ImportProcessingService $importProcessingService
  381.     ) {
  382.         try {
  383.             $currentConfig json_decode(
  384.                 $request->request->get('current_config'),
  385.                 true,
  386.                 512,
  387.                 JSON_THROW_ON_ERROR
  388.             );
  389.             $configName $request->request->get('config_name');
  390.             $mappingConfiguration $factory->loadMappingConfigurationItem($configName$currentConfigtrue);
  391.             return new JsonResponse($importProcessingService->evaluateTransformationResultDataType($mappingConfiguration));
  392.         } catch (Exception InvalidConfigurationException $e) {
  393.             return new JsonResponse('ERROR: ' $e->getMessage());
  394.         }
  395.     }
  396.     /**
  397.      * @Route("/load-class-attributes", methods={"GET"})
  398.      *
  399.      * @param Request $request
  400.      * @param TransformationDataTypeService $transformationDataTypeService
  401.      *
  402.      * @return JsonResponse
  403.      *
  404.      * @throws Exception
  405.      */
  406.     public function loadDataObjectAttributesAction(Request $requestTransformationDataTypeService $transformationDataTypeService)
  407.     {
  408.         $classId $request->query->get('class_id');
  409.         if (empty($classId)) {
  410.             return new JsonResponse([]);
  411.         }
  412.         $loadAdvancedRelations $request->query->getBoolean('load_advanced_relations');
  413.         $includeSystemRead $request->query->getBoolean('system_read');
  414.         $includeSystemWrite $request->query->getBoolean('system_write');
  415.         $transformationTargetType $request->query->get('transformation_result_type');
  416.         if (!$transformationTargetType) {
  417.             $transformationTargetType = [TransformationDataTypeService::DEFAULT_TYPETransformationDataTypeService::NUMERIC];
  418.         }
  419.         return new JsonResponse([
  420.             'attributes' => $transformationDataTypeService->getPimcoreDataTypes($classId$transformationTargetType$includeSystemRead$includeSystemWrite$loadAdvancedRelations)
  421.         ]);
  422.     }
  423.     /**
  424.      * @Route("/load-class-classificationstore-attributes", methods={"GET"})
  425.      *
  426.      * @param Request $request
  427.      * @param TransformationDataTypeService $transformationDataTypeService
  428.      *
  429.      * @return JsonResponse
  430.      */
  431.     public function loadDataObjectClassificationStoreAttributesAction(Request $requestTransformationDataTypeService $transformationDataTypeService)
  432.     {
  433.         $classId $request->query->get('class_id');
  434.         if (empty($classId)) {
  435.             return new JsonResponse([]);
  436.         }
  437.         return new JsonResponse([
  438.             'attributes' => $transformationDataTypeService->getClassificationStoreAttributes($classId)
  439.         ]);
  440.     }
  441.     /**
  442.      * @Route("/load-class-classificationstore-keys", methods={"GET"})
  443.      *
  444.      * @param Request $request
  445.      * @param ClassificationStoreDataTypeService $classificationStoreDataTypeService
  446.      *
  447.      * @return JsonResponse
  448.      *
  449.      * @throws Exception
  450.      */
  451.     public function loadDataObjectClassificationStoreKeysAction(Request $requestClassificationStoreDataTypeService $classificationStoreDataTypeService)
  452.     {
  453.         $sortParams QueryParams::extractSortingSettings(['sort' => $request->query->get('sort')]);
  454.         $list $classificationStoreDataTypeService->listClassificationStoreKeyList(
  455.             strip_tags($request->query->get('class_id')),
  456.             strip_tags($request->query->get('field_name')),
  457.             strip_tags($request->query->get('transformation_result_type')),
  458.             $sortParams['orderKey'] ?? 'name',
  459.             $sortParams['order'] ?? 'ASC',
  460.             $request->query->getInt('start'),
  461.             $request->query->getInt('limit'),
  462.             strip_tags($request->query->get('searchfilter')),
  463.             strip_tags($request->query->get('filter'))
  464.         );
  465.         $data = [];
  466.         foreach ($list as $config) {
  467.             $item = [
  468.                 'keyId' => $config->getKeyId(),
  469.                 'groupId' => $config->getGroupId(),
  470.                 'keyName' => $config->getName(),
  471.                 'keyDescription' => $config->getDescription(),
  472.                 'id' => $config->getGroupId() . '-' $config->getKeyId(),
  473.                 'sorter' => $config->getSorter(),
  474.             ];
  475.             $groupConfig DataObject\Classificationstore\GroupConfig::getById($config->getGroupId());
  476.             if ($groupConfig) {
  477.                 $item['groupName'] = $groupConfig->getName();
  478.             }
  479.             $data[] = $item;
  480.         }
  481.         return new JsonResponse([
  482.             'success' => true,
  483.             'data' => $data,
  484.             'total' => $list->getTotalCount()
  485.         ]);
  486.     }
  487.     /**
  488.      * @Route("/load-class-classificationstore-key-name", methods={"GET"})
  489.      *
  490.      * @param Request $request
  491.      *
  492.      * @return JsonResponse
  493.      *
  494.      * @throws Exception
  495.      */
  496.     public function loadDataObjectClassificationStoreKeyNameAction(Request $request)
  497.     {
  498.         $keyId $request->query->get('key_id');
  499.         $keyParts explode('-'$keyId);
  500.         if (count($keyParts) === 2) {
  501.             $keyGroupRelation DataObject\Classificationstore\KeyGroupRelation::getByGroupAndKeyId((int)$keyParts[0], (int)$keyParts[1]);
  502.             if ($keyGroupRelation) {
  503.                 $group DataObject\Classificationstore\GroupConfig::getById($keyGroupRelation->getGroupId());
  504.                 if ($group) {
  505.                     return new JsonResponse([
  506.                         'groupName' => $group->getName(),
  507.                         'keyName' => $keyGroupRelation->getName()
  508.                     ]);
  509.                 }
  510.             }
  511.         }
  512.         return new JsonResponse([
  513.             'keyId' => $keyId
  514.         ]);
  515.     }
  516.     /**
  517.      * @Route("/start-import", methods={"PUT"})
  518.      *
  519.      * @param Request $request
  520.      * @param ImportPreparationService $importPreparationService
  521.      *
  522.      * @return JsonResponse
  523.      */
  524.     public function startBatchImportAction(Request $requestImportPreparationService $importPreparationService)
  525.     {
  526.         $configName $request->request->get('config_name');
  527.         $success $importPreparationService->prepareImport($configNametrue);
  528.         return new JsonResponse([
  529.             'success' => $success
  530.         ]);
  531.     }
  532.     /**
  533.      * @Route("/check-import-progress", methods={"GET"})
  534.      *
  535.      * @param Request $request
  536.      * @param ImportProcessingService $importProcessingService
  537.      *
  538.      * @return JsonResponse
  539.      */
  540.     public function checkImportProgressAction(Request $requestImportProcessingService $importProcessingService)
  541.     {
  542.         $configName $request->query->get('config_name');
  543.         return new JsonResponse($importProcessingService->getImportStatus($configName));
  544.     }
  545.     /**
  546.      * @Route("/check-crontab", methods={"GET"})
  547.      *
  548.      * @param Request $request
  549.      *
  550.      * @return JsonResponse
  551.      */
  552.     public function isCronExpressionValidAction(Request $request)
  553.     {
  554.         $message '';
  555.         $success true;
  556.         $cronExpression $request->query->get('cron_expression');
  557.         if (!empty($cronExpression)) {
  558.             try {
  559.                 new CronExpression($cronExpression);
  560.             } catch (Exception $e) {
  561.                 $success false;
  562.                 $message $e->getMessage();
  563.             }
  564.         }
  565.         return new JsonResponse([
  566.             'success' => $success,
  567.             'message' => $message
  568.         ]);
  569.     }
  570.     /**
  571.      * @Route("/cancel-execution", methods={"PUT"})
  572.      *
  573.      * @param Request $request
  574.      * @param ImportProcessingService $importProcessingService
  575.      *
  576.      * @return JsonResponse
  577.      */
  578.     public function cancelExecutionAction(Request $requestImportProcessingService $importProcessingService)
  579.     {
  580.         $configName $request->request->get('config_name');
  581.         $importProcessingService->cancelImportAndCleanupQueue($configName);
  582.         return new JsonResponse([
  583.             'success' => true
  584.         ]);
  585.     }
  586.     /**
  587.      * @Route("/upload-import-file", methods={"POST"})
  588.      *
  589.      * @param Request $request
  590.      * @param FilesystemOperator $pimcoreDataImporterUploadStorage
  591.      *
  592.      * @return JsonResponse
  593.      *
  594.      * @throws \League\Flysystem\FilesystemException
  595.      */
  596.     public function uploadImportFileAction(Request $requestFilesystemOperator $pimcoreDataImporterUploadStorage)
  597.     {
  598.         try {
  599.             if (array_key_exists('Filedata'$_FILES)) {
  600.                 $filename $_FILES['Filedata']['name'];
  601.                 $sourcePath $_FILES['Filedata']['tmp_name'];
  602.             } else {
  603.                 throw new Exception('The filename of the upload data is empty');
  604.             }
  605.             $target $this->getImportFilePath($request->query->get('config_name'));
  606.             $pimcoreDataImporterUploadStorage->write($targetfile_get_contents($sourcePath));
  607.             @unlink($sourcePath);
  608.             return new JsonResponse(['success' => true]);
  609.         } catch (Exception $e) {
  610.             Logger::error($e);
  611.             return $this->jsonResponse([
  612.                 'success' => false,
  613.                 'message' => $e->getMessage(),
  614.             ]);
  615.         }
  616.     }
  617.     /**
  618.      * @param string $configName
  619.      *
  620.      * @return string
  621.      *
  622.      * @throws Exception
  623.      */
  624.     protected function getImportFilePath(string $configName): string
  625.     {
  626.         $configuration Dao::getByName($configName);
  627.         if (!$configuration) {
  628.             throw new Exception('Configuration ' $configName ' does not exist.');
  629.         }
  630.         $filePath $configuration->getName() . '/upload.import';
  631.         return $filePath;
  632.     }
  633.     /**
  634.      * @Route("/has-import-file-uploaded", methods={"GET"})
  635.      *
  636.      * @param Request $request
  637.      * @param Translator $translator
  638.      * @param FilesystemOperator $pimcoreDataImporterUploadStorage
  639.      *
  640.      * @return JsonResponse
  641.      */
  642.     public function hasImportFileUploadedAction(Request $requestTranslator $translatorFilesystemOperator $pimcoreDataImporterUploadStorage)
  643.     {
  644.         try {
  645.             $importFile $this->getImportFilePath($request->query->get('config_name'));
  646.             if ($pimcoreDataImporterUploadStorage->fileExists($importFile)) {
  647.                 return new JsonResponse(['success' => true'filePath' => $importFile'message' => $translator->trans('plugin_pimcore_datahub_data_importer_configpanel_type_upload_exists', [], 'admin')]);
  648.             }
  649.             return new JsonResponse(['success' => false'message' => $translator->trans('plugin_pimcore_datahub_data_importer_configpanel_type_upload_not_exists', [], 'admin')]);
  650.         } catch (Exception $e) {
  651.             Logger::error($e);
  652.             return $this->jsonResponse([
  653.                 'success' => false,
  654.                 'message' => $e->getMessage(),
  655.             ]);
  656.         }
  657.     }
  658.     /**
  659.      * @Route("/load-unit-data", methods={"GET"})
  660.      *
  661.      * @param Request $request
  662.      *
  663.      * @return JsonResponse
  664.      */
  665.     public function loadUnitDataAction(Request $request): JsonResponse
  666.     {
  667.         $unitList = new Unit\Listing();
  668.         $unitList->setOrderKey('abbreviation');
  669.         $data = [];
  670.         foreach ($unitList as $unit) {
  671.             $data[] = ['unitId' => $unit->getId(), 'abbreviation' => $unit->getAbbreviation()];
  672.         }
  673.         return new JsonResponse(['UnitList' => $data]);
  674.     }
  675. }