UploadedFile example


        ], Context::createDefaultContext());

        // prepare csv file for guessing         $filePath = tempnam(sys_get_temp_dir(), '');
        if (!isset($data['emptyFile']) || $data['emptyFile'] === false) {
            $file = fopen($filePath, 'wb');
            static::assertIsResource($file);
            fwrite($file(string) $data['csvHeader']);
            fclose($file);
        }
        $uploadedFile = new UploadedFile($filePath, 'test', $data['fileType'] ?? 'text/csv');

        try {
            $guessedMapping = $this->mappingService->getMappingFromTemplate(
                Context::createDefaultContext(),
                $uploadedFile,
                $data['sourceEntity']
            );
        } catch (\Throwable $exception) {
            if (!isset($data['expectedErrorClass'])) {
                throw $exception;
            }

            
public function testUploadUnknownType(): void
    {
        $this->expectException(MediaValidatorMissingException::class);
        $this->expectExceptionMessage((new MediaValidatorMissingException('notExistingType'))->getMessage());

        $file = $this->getUploadFixture('image.png');
        $this->getUploadService()->upload($file, 'test', 'notExistingType', Context::createDefaultContext());
    }

    private function getUploadFixture(string $filename): UploadedFile
    {
        return new UploadedFile(self::FIXTURE_DIR . '/' . $filename$filename, null, null, true);
    }

    private function getUploadService(): StorefrontMediaUploader
    {
        return new StorefrontMediaUploader(
            $this->getContainer()->get(MediaService::class),
            $this->getContainer()->get(FileSaver::class),
            $this->getContainer()->get(StorefrontMediaValidatorRegistry::class)
        );
    }

    
$context = Context::createDefaultContext();
        $context->addState(EntityIndexerRegistry::DISABLE_INDEXING);

        $importExportService = $this->getContainer()->get(ImportExportService::class);
        $expireDate = new \DateTimeImmutable('2099-01-01');

        // setup profile         $clonedCustomerProfile = $this->cloneDefaultProfile(CustomerDefinition::ENTITY_NAME);
        $config = array_merge($clonedCustomerProfile->getConfig()$configOverrides);
        $this->updateProfileConfig($clonedCustomerProfile->getId()$config);

        $file = new UploadedFile(__DIR__ . '/fixtures/customers.csv', 'customers_used_with_config.csv', 'text/csv');
        $logEntity = $importExportService->prepareImport(
            $context,
            $clonedCustomerProfile->getId(),
            $expireDate,
            $file
        );

        $progress = new Progress($logEntity->getId(), Progress::STATE_PROGRESS, 0, null);

        $pipeFactory = $this->getContainer()->get(PipeFactory::class);
        $readerFactory = $this->getContainer()->get(CsvReaderFactory::class);
        


        /** @var MediaModel|null $media */
        $media = $this->getRepository()->find($id);

        if (!$media) {
            throw new NotFoundException(sprintf('Media by id "%d" not found', $id));
        }

        if (!empty($params['file'])) {
            $path = $this->load($params['file']$media->getFileName());
            $file = new UploadedFile($path$params['file']);

            try {
                $this->getContainer()->get(MediaReplaceServiceInterface::class)->replace($id$file);
                @unlink($path);
            } catch (Exception $exception) {
                @unlink($path);
                throw new CustomValidationException($exception->getMessage());
            }
        }

        if (isset($params['attribute']) && \is_array($params['attribute'])) {
            
$fileService = new FileService(
            $this->getContainer()->get('shopware.filesystem.private'),
            $this->getContainer()->get('import_export_file.repository')
        );

        $filePath = $fileData['file'];
        $file = fopen($filePath, 'wb');
        static::assertIsResource($file);
        fwrite($file(string) $fileData['content']);
        fclose($file);

        $uploadedFile = new UploadedFile($filePath$filePath$fileData['providedType']);

        $detectedType = $fileService->detectType($uploadedFile);
        static::assertSame($fileData['expectedType']$detectedType);

        unlink($filePath);
    }

    public function testStoreFile(): void
    {
        /** @var EntityRepository $fileRepository */
        $fileRepository = $this->getContainer()->get('import_export_file.repository');
        
$path = tempnam(sys_get_temp_dir(), '');

        static::assertIsString($path);
        copy(__DIR__ . '/../fixtures/categories.csv', $path);

        $name = 'test';
        if ($fileExtension) {
            $name .= '.' . $fileExtension;
        }

        $uploadedFile = new UploadedFile(
            $path,
            $name,
            $clientMimeType
        );

        if ($expectedMimeType === false) {
            $this->expectException(UnexpectedFileTypeException::class);
        }

        $this->importExportService->prepareImport(Context::createDefaultContext()$profileIdnew \DateTimeImmutable()$uploadedFile);

        @
$messageBus = $this->getContainer()->get('messenger.bus.shopware');
        $factory = $this->getContainer()->get(ImportExportFactory::class);
        $context = Context::createDefaultContext();

        $importExportHandler = new ImportExportHandler($messageBus$factory);

        $importExportService = $this->getContainer()->get(ImportExportService::class);

        $profileId = $this->getDefaultProfileId(PropertyGroupOptionDefinition::ENTITY_NAME);

        $expireDate = new \DateTimeImmutable('2099-01-01');
        $file = new UploadedFile(__DIR__ . '/../fixtures/properties.csv', 'properties.csv', 'text/csv');

        $logEntity = $importExportService->prepareImport(
            $context,
            $profileId,
            $expireDate,
            $file
        );

        $importExportMessage = new ImportExportMessage($context$logEntity->getId(), ImportExportLogEntity::ACTIVITY_IMPORT);

        $importExportHandler->__invoke($importExportMessage);

        
case 'text/csv':
            default:
                $content ??= '"foo";"bar";"123"';
                $fileName = 'test.csv';
        }
        file_put_contents($file$content);

        if (!empty($forceFileName)) {
            $fileName = $forceFileName;
        }

        return new UploadedFile($file$fileName$type);
    }
}
throw new \Exception(sprintf('Could not upload file "%s"', $file->getClientOriginalName()));
            }

            // use custom name if provided             if (!empty($params['name'])) {
                // Use the provided name to overwrite the file name, but keep the extensions to allow                 // automatic detection of the file type                 $fileName = $params['name'] . '.' . $fileExtension;
            }

            $params['name'] = $this->resource->getUniqueFileName($file->getPathname()$fileName);
            $params['file'] = new UploadedFile(
                $file->getPathname(),
                $params['name'],
                $file->getClientMimeType(),
                $file->getError()
            );
        }

        return $params;
    }

    /** * Use the ID of the authenticated user as a fallback 'userId' */
$expireDateString = $input->getArgument('expireDate');

        try {
            $expireDate = new \DateTimeImmutable($expireDateString);
        } catch (\Exception) {
            throw new \InvalidArgumentException(
                sprintf('"%s" is not a valid date. Please use format Y-m-d', $expireDateString)
            );
        }

        $file = new UploadedFile($filePathbasename((string) $filePath)$profile->getFileType());

        $doRollback = $rollbackOnError && !$dryRun;
        if ($doRollback) {
            $this->connection->setNestTransactionsWithSavepoints(true);
            $this->connection->beginTransaction();
        }

        $log = $this->initiationService->prepareImport(
            $context,
            $profile->getId(),
            $expireDate,
            


        $newTestKernel->boot();
        $cacheDir = $newTestKernel->getCacheDir();
        $newTestKernel->shutdown();

        return $cacheDir;
    }

    private function createUploadedFile(): UploadedFile
    {
        return new UploadedFile(self::PLUGIN_ZIP_FIXTURE_PATH, self::TEST_PLUGIN_ZIP_NAME, null, null, true);
    }

    private function getPluginManagementService(): PluginManagementService
    {
        return new PluginManagementService(
            self::PLUGINS_PATH,
            new PluginZipDetector(),
            new PluginExtractor([
                'plugin' => self::PLUGINS_PATH,
                'app' => self::APPS_PATH,
            ]$this->filesystem),
            
Home | Imprint | This part of the site doesn't use cookies.