Vich Bundle – Symfony 4.4 – ApiPlatform – Flysystem – OVH S3 object store – guessMimeType PHP Exception on create and update

  • Vich version : 1.15.0
  • Symfony version : 4.4.13
  • PHP version : 7.4
  • API Platform version : 2.5.7
  • flysystem-bundle version : 1.5.0
  • flysystem-aws-s3-v3 version : 1.0.28

Summary

When creating or updating the object containing a file on a remote repository, an error occurs because it tries to read the MimeType of the file with its path while the file is not present on the server . I don’t get any error when using local storage.

The error:

request.CRITICAL: Uncaught PHP Exception SymfonyComponentMimeExceptionInvalidArgumentException: "The "5f5b6d18c6671164117604.png" file does not exist or is not readable." at /var/www/html/vendor/symfony/mime/FileinfoMimeTypeGuesser.php line 50 {"exception":"[object] (SymfonyComponentMimeExceptionInvalidArgumentException(code: 0): The "5f5b6d18c6671164117604.png" file does not exist or is not readable. at /var/www/html/vendor/symfony/mime/FileinfoMimeTypeGuesser.php:50)"} []

I know the file is sent to the repository because it can be recovered with GET request.

How to reproduce

flysystem.yaml

flysystem:
    storages:
        uploads.storage.ovh:
            adapter: "aws"
            options:
                client: "AwsS3S3Client"
                bucket: "%env(OVH_BUCKET)%"
        uploads.storage.local:
            adapter: 'local'
            options:
                directory: "%kernel.project_dir%/var/storage/uploads"

        uploads.storage.memory:
            adapter: "memory"
# switch with env
        uploads.storage:
            adapter: "lazy"
            options:
                source: "%env(APP_UPLOADS_SOURCE)%"

vich_uploader.yaml:

vich_uploader:
    db_driver: orm
    storage: flysystem
    metadata:
        auto_detection: true

    mappings:
        userAvatar:
            upload_destination: uploads.storage
            namer:
                service: VichUploaderBundleNamingUniqidNamer
            delete_on_remove: true  # determine whether to delete file upon removal of entity
            delete_on_update: true  # determine wheter to delete the file upon update of entity
            inject_on_load: false

        productionCenterLogo:
            upload_destination: uploads.storage
            namer:
                service: VichUploaderBundleNamingUniqidNamer
            delete_on_remove: true
            delete_on_update: true
            inject_on_load: false

        donneurOrdreLogo:
            upload_destination: uploads.storage
            namer:
                service: VichUploaderBundleNamingUniqidNamer
            delete_on_remove: true
            delete_on_update: true
            inject_on_load: false

service.yaml:

services:
  AwsS3S3Client:
    arguments:
      - version: 'latest'
        credentials:
          key: '%env(OVH_ACCESS_KEY_ID)%'
          secret: '%env(OVH_SECRET_ACCESS_KEY)%'
        endpoint: '%env(OVH_ENDPOINT)%'
        region: '%env(OVH_REGION)%'
        S3:
          version: '2006-03-01'
          endpoint_url: '%env(OVH_ENDPOINT)%'
          signature_version: 's3v4'
          addressing_style: 'virtual'
        S3API:
          endpoint_url: '%env(OVH_ENDPOINT)%'

exemple of one entity:

<?php

namespace AppEntity;

use ApiPlatformCoreAnnotationApiResource;
use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentHttpFoundationFileFile;
use SymfonyComponentSerializerAnnotationGroups;
use SymfonyComponentValidatorConstraints as Assert;
use VichUploaderBundleMappingAnnotation as Vich;

/**
 * @ORMEntity(repositoryClass="AppRepositoryUserAvatarRepository")
 * @ApiResource()
 * @VichUploadable
 * @UniqueEntity(fields={"user"}, message="unique.userAvatar.user")
 */
class UserAvatar extends FileUpload
{
    /**
     * @AssertFile(
     *     maxSize = "1980k",
     *     mimeTypes = {
     *      "image/jpeg",
     *      "image/png",
     *      "image/svg+xml",
     *      }
     * )
     * @AssertNotNull()
     *
     * @var File|null
     * @Groups({
     *     "file",
     *     })
     * @VichUploadableField(
     *     mapping="userAvatar",
     *     fileNameProperty="filePath",
     *     size="imageSize",
     *     originalName="originalName",
     *     mimeType="mimeType",
     *     dimensions="dimensions",
     * )
     */
    public $imageFile;

    /**
     * @ORMOneToOne(targetEntity=User::class, inversedBy="avatar")
     * @ORMJoinColumn(nullable=false, unique=true)
     */
    private User $user;

    public function getUser(): User
    {
        return $this->user;
    }

    public function setUser(User $user): self
    {
        $this->user = $user;

        return $this;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|SymfonyComponentHttpFoundationFileUploadedFile|null $imageFile
     */
    public function setImageFile($imageFile = null): void
    {
        $this->imageFile = $imageFile;
        if (null !== $imageFile) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->setUpdatedAt(new DateTime());
        }
    }

    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }
}
<?php

namespace AppEntity;

use ApiPlatformCoreAnnotationApiProperty;
use ApiPlatformCoreAnnotationApiResource;
use AppEntityTraitsUpdatedAtTrait;
use DoctrineORMMapping as ORM;
use SymfonyComponentSerializerAnnotationGroups;

/**
 * @ORMEntity(repositoryClass="AppRepositoryFileUploadRepository")
 * @ApiResource()
 * @ORMInheritanceType("JOINED")
 * @ORMDiscriminatorColumn(name="type", type="string")
 * @ORMDiscriminatorMap({
 *     "userAvatar" = "AppEntityUserAvatar",
 *     "productionCenterLogo" = "AppEntityProductionCenterLogo",
 *     "donneurOrdreLogo" = "AppEntityDonneurOrdreLogo",
 * })
 */
abstract class FileUpload
{
    use UpdatedAtTrait;
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     * @ApiProperty(identifier=true)
     */
    private int $id;

    /**
     * @ORMColumn(type="string")
     *
     * @var string|null
     * @Groups({
     *     "file",
     *     "user_read",
     *     "production_center_read",
     *     "donneur_ordre_read",
     *     })     */
    private $filePath;

    /**
     * @ORMColumn(type="string")
     *
     * @var string|null
     * @Groups({
     *     "file",
     *     "user_read",
     *     "production_center_read",
     *     "donneur_ordre_read",
     *     })     */
    private $originalName;

    /**
     * @ORMColumn(type="string")
     *
     * @var string|null
     * @Groups({
     *     "file",
     *     "user_read",
     *     "production_center_read",
     *     "donneur_ordre_read",
     *     })     */
    private $mimeType;

    /**
     * @ORMColumn(type="json", nullable=true)
     *
     * @var array|null
     * @Groups({
     *     "file",
     *     "user_read",
     *     "production_center_read",
     *     "donneur_ordre_read",
     *     })     */
    private $dimensions;

    /**
     * @ORMColumn(type="integer", nullable=true)
     *
     * @var int|null
     * @Groups({
     *     "file",
     *     "user_read",
     *     "production_center_read",
     *     "donneur_ordre_read",
     *     })     */
    private $imageSize;

    public function setFilePath(?string $filePath): self
    {
        $this->filePath = $filePath;

        return $this;
    }

    public function getFilePath(): ?string
    {
        return $this->filePath;
    }

    public function setImageSize(?int $imageSize): self
    {
        $this->imageSize = $imageSize;

        return $this;
    }

    public function getImageSize(): ?int
    {
        return $this->imageSize;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function setId(int $id): self
    {
        $this->id = $id;

        return $this;
    }

    public function getOriginalName(): ?string
    {
        return $this->originalName;
    }

    public function setOriginalName(?string $originalName): self
    {
        $this->originalName = $originalName;

        return $this;
    }

    public function getMimeType(): ?string
    {
        return $this->mimeType;
    }

    public function setMimeType(?string $mimeType): self
    {
        $this->mimeType = $mimeType;

        return $this;
    }

    public function getDimensions(): ?array
    {
        return $this->dimensions;
    }

    public function setDimensions(?array $dimensions): self
    {
        $this->dimensions = $dimensions;

        return $this;
    }
}

Source: Symfony4 Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *