在 Shopware 6 中通过 php 创建媒体

Posted

技术标签:

【中文标题】在 Shopware 6 中通过 php 创建媒体【英文标题】:Media creation via php in Shopware 6 【发布时间】:2020-12-04 05:03:23 【问题描述】:

我正在努力通过 php 导入媒体以使 Shopware 6 正常工作。

这是我的服务:

<?php declare(strict_types=1);

namespace My\Namespace\Service;

use Shopware\Core\Content\Media\File\MediaFile;
use Shopware\Core\Content\Media\MediaService;
use Shopware\Core\Framework\Context;

class ImageImport

    /**
     * @var MediaService
     */
    protected $mediaService;

    /**
     * ImageImport constructor.
     * @param MediaService $mediaService
     */
    public function __construct(MediaService $mediaService)
    
        $this->mediaService = $mediaService;
    


    public function addImageToProductMedia($imageUrl, Context $context)
    
        $mediaId = NULL;
        $context->disableCache(function (Context $context) use ($imageUrl, &$mediaId): void 
            $filePathParts = explode('/', $imageUrl);
            $fileName = array_pop($filePathParts);
            $fileNameParts = explode('.', $fileName);

            $actualFileName = $fileNameParts[0];
            $fileExtension = $fileNameParts[1];


            if ($actualFileName && $fileExtension) 
                $tempFile = tempnam(sys_get_temp_dir(), 'image-import');
                file_put_contents($tempFile, file_get_contents($imageUrl));

                $fileSize = filesize($tempFile);
                $mimeType = mime_content_type($tempFile);

                $mediaFile = new MediaFile($tempFile, $mimeType, $fileExtension, $fileSize);

                $mediaId = $this->mediaService->saveMediaFile($mediaFile, $actualFileName, $context, 'product');
            
        );
        return $mediaId;
    

在表 media 中创建具有正确 media_folder_association 的条目。据我所知,与通过后端上传的其他媒体没有区别(除了 private 为 1 且 user_id 为 NULL)。

但在后端,媒体条目已损坏,似乎无法加载实际的图像文件(我尝试将 private 设置为 true 以在媒体部分看到它,将媒体添加到产品时也会发生同样的情况通过 php,但我想问题出在对产品的任何分配之前)。

Image in backend media

有没有人建议这里有什么问题?

谢谢 菲尔

=====解决方案======

这是更新后的工作服务:

<?php declare(strict_types=1);

namespace My\Namespace\Service;

use Shopware\Core\Content\Media\File\FileSaver;
use Shopware\Core\Content\Media\File\MediaFile;
use Shopware\Core\Content\Media\MediaService;
use Shopware\Core\Framework\Context;

class ImageImport

    /**
     * @var MediaService
     */
    protected $mediaService;

    /**
     * @var FileSaver
     */
    private $fileSaver;

    /**
     * ImageImport constructor.
     * @param MediaService $mediaService
     * @param FileSaver $fileSaver
     */
    public function __construct(MediaService $mediaService, FileSaver $fileSaver)
    
        $this->mediaService = $mediaService;
        $this->fileSaver = $fileSaver;
    


    public function addImageToProductMedia($imageUrl, Context $context)
    
        $mediaId = NULL;
        $context->disableCache(function (Context $context) use ($imageUrl, &$mediaId): void 
            $filePathParts = explode('/', $imageUrl);
            $fileName = array_pop($filePathParts);
            $fileNameParts = explode('.', $fileName);

            $actualFileName = $fileNameParts[0];
            $fileExtension = $fileNameParts[1];


            if ($actualFileName && $fileExtension) 
                $tempFile = tempnam(sys_get_temp_dir(), 'image-import');
                file_put_contents($tempFile, file_get_contents($imageUrl));

                $fileSize = filesize($tempFile);
                $mimeType = mime_content_type($tempFile);

                $mediaFile = new MediaFile($tempFile, $mimeType, $fileExtension, $fileSize);
                $mediaId = $this->mediaService->createMediaInFolder('product', $context, false);

                $this->fileSaver->persistFileToMedia(
                    $mediaFile,
                    $actualFileName,
                    $mediaId,
                    $context
                );
            
        );
        return $mediaId;
    

【问题讨论】:

【参考方案1】:

为了将文件导入 Shopware 6,需要执行两个步骤:

    您必须创建一个媒体文件对象 (MediaDefinition / media table)。看看 MediaConverter 在SwagMigrationMediaFileDefinitionswag_migration_media_file 表)中创建一个新条目。

关联迁移运行的swag_migration_media_file 表中的每个条目都将由 MediaFileProcessorInterface 的实现处理。

要将文件添加到表中,您可以在 Converter 类中执行类似的操作(此示例来自 MediaConverter):

abstract class MediaConverter extends ShopwareConverter


    public function convert(
        array $data,
        Context $context,
        MigrationContextInterface $migrationContext
    ): ConvertStruct 
        $this->generateChecksum($data);
        $this->context = $context;
        $this->locale = $data['_locale'];
        unset($data['_locale']);

        $connection = $migrationContext->getConnection();
        $this->connectionId = '';
        if ($connection !== null) 
            $this->connectionId = $connection->getId();
        

        $converted = [];
        $this->mainMapping = $this->mappingService->getOrCreateMapping(
            $this->connectionId,
            DefaultEntities::MEDIA,
            $data['id'],
            $context,
            $this->checksum
        );
        $converted['id'] = $this->mainMapping['entityUuid'];

        if (!isset($data['name'])) 
            $data['name'] = $converted['id'];
        

        $this->mediaFileService->saveMediaFile(
            [
                'runId' => $migrationContext->getRunUuid(),
                'entity' => MediaDataSet::getEntity(), // important to distinguish between private and public files
                'uri' => $data['uri'] ?? $data['path'],
                'fileName' => $data['name'], // uri or path to the file (because of the different implementations of the gateways)
                'fileSize' => (int) $data['file_size'],
                'mediaId' => $converted['id'], // uuid of the media object in Shopware 6
            ]
        );
        unset($data['uri'], $data['file_size']);

        $this->getMediaTranslation($converted, $data);
        $this->convertValue($converted, 'title', $data, 'name');
        $this->convertValue($converted, 'alt', $data, 'description');

        $albumMapping = $this->mappingService->getMapping(
            $this->connectionId,
            DefaultEntities::MEDIA_FOLDER,
            $data['albumID'],
            $this->context
        );

        if ($albumMapping !== null) 
            $converted['mediaFolderId'] = $albumMapping['entityUuid'];
            $this->mappingIds[] = $albumMapping['id'];
        

        unset(
            $data['id'],
            $data['albumID'],

            // Legacy data which don't need a mapping or there is no equivalent field
            $data['path'],
            $data['type'],
            $data['extension'],
            $data['file_size'],
            $data['width'],
            $data['height'],
            $data['userID'],
            $data['created']
        );

        $returnData = $data;
        if (empty($returnData)) 
            $returnData = null;
        
        $this->updateMainMapping($migrationContext, $context);

        // The MediaWriter will write this Shopware 6 media object
        return new ConvertStruct($converted, $returnData, $this->mainMapping['id']);
    


swag_migration_media_files 由正确的处理器服务处理。该服务对于文档和普通媒体是不同的,但它仍然依赖于网关

=== 不同的方法(Shyim 建议)===

看看这个(取自 Shopwaredowntown 的 Github 存储库):

public function upload(UploadedFile $file, string $folder, string $type, Context $context): string
    
        $this->checkValidFile($file);

        $this->validator->validate($file, $type);

        $mediaFile = new MediaFile($file->getPathname(), $file->getMimeType(), $file->getClientOriginalExtension(), $file->getSize());

        $mediaId = $this->mediaService->createMediaInFolder($folder, $context, false);

        try 
            $this->fileSaver->persistFileToMedia(
                $mediaFile,
                pathinfo($file->getFilename(), PATHINFO_FILENAME),
                $mediaId,
                $context
            );
         catch (MediaNotFoundException $e) 
            throw new UploadException($e->getMessage());
        

        return $mediaId;
    

src/Portal/Hacks/StorefrontMediaUploader.php:49

public function upload(UploadedFile $file, string $folder, string $type, Context $context): string

【讨论】:

以上是关于在 Shopware 6 中通过 php 创建媒体的主要内容,如果未能解决你的问题,请参考以下文章

Shopware 6:在自己的自定义管理模块中获取 PHP 数据

shopware 6 中的电子邮件模板变量

带有 Mailchimp 的 Shopware 6

在php中通过空格读取字符串

如何在 Shopware 6 中获取公用文件夹绝对路径?

与 Shopware 6 中的其他字段的多对多关联