Giter Club home page Giter Club logo

vichuploaderserializationbundle's Introduction

VichUploaderSerializationBundle

๐Ÿ“ฆ Provides integration between VichUploaderBundle and JMSSerializerBundle. Allows to generate full or relative URIs to entity fields mapped with @Vich and @JMS annotations during the serialization.

Scrutinizer Quality Score Build Status CodeCov License Latest Stable Version Total Downloads StyleCI Gitter

Requirements ๐Ÿง

  • PHP 7.3, 7.4, 8.0, 8.1, 8.2
  • Symfony 5.0, 5.1, 5.2, 5.3, 5.4, 6.0, 6.1, 6.2

Installation ๐ŸŒฑ

composer req fresh/vich-uploader-serialization-bundle='~3.3'

Usage ๐Ÿง‘โ€๐ŸŽ“

Add the next class to the use section of your entity class.

use Fresh\VichUploaderSerializationBundle\Annotation as Fresh;

Bundle provides two annotations which allow the serialization of @Vich\UploadableField fields in your entities. At first you have to add @Fresh\VichSerializableClass to the entity class which has uploadable fields. Then you have to add @Fresh\VichSerializableField annotation to the uploadable field you want to serialize.

Annotation @Fresh\VichSerializableClass does not have any option.
Annotation @Fresh\VichSerializableField has one required option value (or field) which value should link to the field with @Vich\UploadableField annotation. It can be set like this @Fresh\VichSerializableField("photoFile") or @Fresh\VichSerializableField(field="photoFile"). Also there is another option includeHost, it is not required and by default is set to true. But if you need, you can exclude the host from the generated URI, just use the next variant of the annotation @Fresh\VichSerializableField("photoFile", includeHost=false).

And also don't forget that to serialize Vich uploadable fields they also should be marked with @JMS annotations to be serialized.

The generated URI by default:

{
  "photo": "http://example.com/uploads/users/photos/5659828fa80a7.jpg",
  "cover": "http://example.com/uploads/users/covers/456428fa8g4a8.jpg",
}

The generated URI with includeHost set to false:

{
  "photo": "/uploads/users/photos/5659828fa80a7.jpg",
  "cover": "/uploads/users/covers/456428fa8g4a8.jpg",
}

Example of entity with serialized uploadable fields

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Fresh\VichUploaderSerializationBundle\Annotation as Fresh;
use JMS\Serializer\Annotation as JMS;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity()
 *
 * @Vich\Uploadable
 * 
 * @Fresh\VichSerializableClass
 */
class User
{
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     *
     * @JMS\Expose
     * @JMS\SerializedName("photo")
     *
     * @Fresh\VichSerializableField("photoFile")
     */
    private $photoName;

    /**
     * @var File
     *
     * @JMS\Exclude
     *
     * @Vich\UploadableField(mapping="user_photo_mapping", fileNameProperty="photoName")
     */
    private $photoFile;
    
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     *
     * @JMS\Expose
     * @JMS\SerializedName("cover")
     *
     * @Fresh\VichSerializableField("coverFile", includeHost=false)
     */
    private $coverName;

    /**
     * @var File
     *
     * @JMS\Exclude
     *
     * @Vich\UploadableField(mapping="user_cover_mapping", fileNameProperty="coverName")
     */
    private $coverFile;    
}

Don't make a mistake!

Additional example of a wrong usage of provided annotations to attract your attention. Use @Fresh\VichSerializableField only with the field which is mapped with @ORM\Column, because this field is mapped to a database and keeps the name of the stored file. Don't use the @Fresh\VichSerializableField with a field which also mapped with @Vich\UploadableField, this is a wrong use case and will throw an exception!

So the next example is the incorrect usage of provided annotations! Don't do so!

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Fresh\VichUploaderSerializationBundle\Annotation as Fresh;
use JMS\Serializer\Annotation as JMS;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity()
 *
 * @Vich\Uploadable
 * 
 * @Fresh\VichSerializableClass
 */
class User
{
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     */
    private $photoName;

    /**
     * @var File
     *
     * !!! Next three annotations should be moved to the `photoName` property
     * @JMS\Expose
     * @JMS\SerializedName("photo")
     * @Fresh\VichSerializableField("photoFile")
     *
     * !!! This annotation should be left here
     * @Vich\UploadableField(mapping="user_photo_mapping", fileNameProperty="photoName")
     */
    private $photoFile;  
}

Contributing ๐Ÿค

See CONTRIBUTING file.

vichuploaderserializationbundle's People

Contributors

aless673 avatar bukashk0zzz avatar fre5h avatar giantvlad avatar lsv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vichuploaderserializationbundle's Issues

Support for jms/serializer-bundle@^5.0

there is a new major of jms/serializer-bundle

can not use 4.x - i think there is an dependancy error with other package, hope jms/serializer-bundle@^5.0 solve it

Support Symfony LTS 4.4

Hi,

v2.4.2 supports ^4.3
v3.0.0 supports ^5.0

Can't use your bundle with an LTS symfony 4.4 project !

String at CachedReader::__construct()

Hi.

Trying to use this bundle, but have next error:

An Exception was thrown while handling: Catchable Fatal Error: Argument 2 passed to Doctrine\Common\Annotations\CachedReader::__construct() must implement interface Doctrine\Common\Cache\Cache, string given, called in /vagrant/app/cache/dev/appDevDebugProjectContainer.php on line 6258 and defined
# appDevDebugProjectContainer.php

    /**
     * Gets the 'vich_uploader.jms_serializer.listener' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return \Fresh\VichUploaderSerializationBundle\EventListener\JmsPreSerializeListener A Fresh\VichUploaderSerializationBundle\EventListener\JmsPreSerializeListener instance.
     */
    protected function getVichUploader_JmsSerializer_ListenerService()
    {
        return $this->services['vich_uploader.jms_serializer.listener'] = new \Fresh\VichUploaderSerializationBundle\EventListener\JmsPreSerializeListener($this->get('vich_uploader.storage'), $this->get('router.request_context'), new \Doctrine\Common\Annotations\CachedReader($this->get('annotations.reader'), '', ''), $this->get('monolog.logger.vich_uploader_serialization'));
    }
# src/Symfony/Bundle/FrameworkBundle/Resources/config/annotations.xml
        <service id="annotations.cached_reader" class="%annotations.cached_reader.class%" public="false">
            <argument type="service" id="annotations.reader" />
            <argument /><!-- Cache Implementation -->
            <argument /><!-- Debug-Flag -->
        </service>

Support for Symfony Serializer

Is it possible to customize the bundle to use both JMSSerializer and Symony Serializer? I find the bundle very useful, but would like to stay with Symfony Serializer.

Symfony Flex support

Now I use this bundle in Symfony flex project and to run this bundle I need put in my service config this setting:

    Monolog\Logger: '@Psr\Log\LoggerInterface'
    Symfony\Component\PropertyAccess\PropertyAccessor: '@Symfony\Component\PropertyAccess\PropertyAccessorInterface'
    Vich\UploaderBundle\Storage\StorageInterface: '@vich_uploader.storage'
    Vich\UploaderBundle\Storage\FlysystemStorage: '@vich_uploader.storage.flysystem'
    Vich\UploaderBundle\Handler\DownloadHandler: '@vich_uploader.download_handler'
    Vich\UploaderBundle\Templating\Helper\UploaderHelper: '@vich_uploader.templating.helper.uploader_helper'

    Fresh\VichUploaderSerializationBundle\EventListener\JmsSerializerSubscriber:
        arguments:
            $annotationReader: '@Doctrine\Common\Annotations\Reader'
        tags:
            - 'jms_serializer.event_subscriber'
            - { name: monolog.logger, channel: vich_uploader_serialization }

I think we can make life better if change __construct parameters in JmsSerializerSubscriber to interfaces. What you think?

Cannot autowire service

Hello,

I'm juste trying to update the dependance but I have this error with symfony 3.4 and I got this error :

[RuntimeException]
An error occurred when executing the "'cache:clear --no-warmup'" command:
In DefinitionErrorExceptionPass.php line 37:

Cannot autowire service "Fresh\VichUploaderSerializationBundle\EventListene    
r\JmsSerializerSubscriber": argument "$storage" of method "__construct()" r    
eferences interface "Vich\UploaderBundle\Storage\StorageInterface" but no s    
uch service exists. You should maybe alias this interface to one of these e    
xisting services: "vich_uploader.storage.file_system", "meero.vich.gaufrett    
e_storage". Did you create a class that implements this interface?             

Do you have any idea what's going on ?

Thank you,

Add image filter annotation

What do you think about adding new option "filter" for annotation.
Example:
@Fresh\VichSerializableField("coverFile", includeHost=false, filter="my_thumb")

This option will be adding filter to image using LiipImagineBundle

S3 naming Bug

Hi,

I have a problem with vich uploader, gaufrette and the VichUploaderSerializationBundle and I'm not really sure what is causing it.

I set vich to upload images to an S3 bucket using gaufrette which is working fine.
When I serialize my entity using the JMS Serializer the VichUploaderSerializationBundle will return the link to the S3 bucket.
All that is working fine except that on some seemingly random occasions it will append the S3 url to the database entry for the file name (it even will append it multiple times causeing things like UrlUrlUrlName...)

I have no clue what might be the cause for that because I don't update the entity at all.

Here is part of my configuration:

vich_uploader:
    db_driver: orm
    storage: gaufrette
    mappings:
        product_image:
            uri_prefix: 'https://s3-%aws_region%.amazonaws.com/%s3_bucket%/products' # you'll need this set to use the Vich URL generator
            upload_destination: aws_s3_products
            namer: vich_uploader.namer_uniqid
            delete_on_remove: true
            delete_on_update: true

knp_gaufrette:
    stream_wrapper: ~
    adapters:
        products:
            aws_s3:
                service_id: 'aws.s3'
                bucket_name: '%s3_bucket%'
                options:
                    directory: 'products'
                    acl: 'public-read'
    filesystems:
        aws_s3_products:
            adapter:    products

Vich part from product entity:

/**
     * @ORM\Column(type="string", nullable=true)
     * @Fresh\VichSerializableField("imageFile", includeHost=false)
     * @Expose
     * @Groups({"default"})
     */
    private $imageName;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Assert\File(
     *     maxSize="5M",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     * @Expose
     *
     * @var File
     */
    private $imageFile;

I really have no clue what's causing this strange behavior...

I already asked on the vich upload bundle but they said the root of the issue is more likely to be found here.

Thanks in advance

Serializing an entity manually does not work with the annotated fields.

I am passing extra data (user info.) to lexic jwt authentication success response. Serializing the entity manually above:

$serializer = new SerializerBuilder();
$data['user'] = $serializer->create()->build()->toArray($user);

Manually serializing does not work. Do you know a solution? Or any other better way?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.