|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\ImportService\Model\Import\Processor; |
| 9 | + |
| 10 | +use Magento\Framework\Filesystem; |
| 11 | +use Magento\Framework\App\Filesystem\DirectoryList; |
| 12 | +use Magento\ImportService\Exception as ImportServiceException; |
| 13 | + |
| 14 | +/** |
| 15 | + * Base64 encoded data processor for asynchronous import |
| 16 | + */ |
| 17 | +class Base64EncodedDataProcessor implements SourceProcessorInterface |
| 18 | +{ |
| 19 | + /** |
| 20 | + * Import Type |
| 21 | + */ |
| 22 | + const IMPORT_TYPE = 'base64_encoded_data'; |
| 23 | + |
| 24 | + /** |
| 25 | + * CSV Source Type |
| 26 | + */ |
| 27 | + const SOURCE_TYPE_CSV = 'csv'; |
| 28 | + |
| 29 | + /** |
| 30 | + * The destination directory |
| 31 | + */ |
| 32 | + const DIR_IMPORT_DESTINATION = 'import/'; |
| 33 | + |
| 34 | + /** |
| 35 | + * @var \Magento\Framework\Filesystem |
| 36 | + */ |
| 37 | + protected $filesystem; |
| 38 | + |
| 39 | + /** |
| 40 | + * LocalPathFileProcessor constructor. |
| 41 | + * @param Filesystem $filesystem |
| 42 | + */ |
| 43 | + public function __construct( |
| 44 | + Filesystem $filesystem |
| 45 | + ) { |
| 46 | + $this->filesystem = $filesystem; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * {@inheritdoc} |
| 51 | + */ |
| 52 | + public function processUpload(\Magento\ImportService\Api\Data\SourceInterface $source, \Magento\ImportService\Api\Data\SourceUploadResponseInterface $response) |
| 53 | + { |
| 54 | + /** @var string $fileName */ |
| 55 | + $fileName = rand(); |
| 56 | + |
| 57 | + /** @var string $contentFilePath */ |
| 58 | + $contentFilePath = self::DIR_IMPORT_DESTINATION |
| 59 | + . $fileName |
| 60 | + . '.' |
| 61 | + . $source->getSourceType(); |
| 62 | + |
| 63 | + /** @var string $content */ |
| 64 | + $content = base64_decode($source->getImportData()); |
| 65 | + |
| 66 | + /** @var Magento\Framework\Filesystem\Directory\Write $var */ |
| 67 | + $var = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); |
| 68 | + |
| 69 | + if(!$var->writeFile($contentFilePath, $content)) |
| 70 | + { |
| 71 | + /** @var array $lastError */ |
| 72 | + $lastError = error_get_last(); |
| 73 | + |
| 74 | + /** @var string $errorMessage */ |
| 75 | + $errorMessage = isset($lastError['message']) ? $lastError['message'] : ''; |
| 76 | + |
| 77 | + throw new ImportServiceException( |
| 78 | + __('Cannot copy the remote file: %1', $errorMessage) |
| 79 | + ); |
| 80 | + } |
| 81 | + |
| 82 | + /** Update source's import data */ |
| 83 | + $source->setImportData($fileName); |
| 84 | + |
| 85 | + return $response->setSource($source)->setSourceId($fileName)->setStatus($response::STATUS_UPLOADED); |
| 86 | + } |
| 87 | +} |
0 commit comments