### Install Sonata Media Assets Command Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/helpers.md Runs the Symfony console command to install bundle assets, making default thumbnails available for file providers. Place the file.png in the bundles directory post-install. Requires the bundle to be installed; outputs assets to public directories. ```bash bin/console assets:install ``` -------------------------------- ### Install SonataMediaBundle via Composer Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Installs the SonataMediaBundle package using Composer. No additional dependencies are required beyond Composer being available on the system. ```bash composer require sonata-project/media-bundle ``` -------------------------------- ### Install Azure Blob Storage Package (Bash) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/azure_blob_storage.md Installs the necessary Microsoft Azure Storage Blob SDK for PHP using Composer. This is a prerequisite for using Azure Blob Storage with the SonataMediaBundle. ```bash composer require microsoft/azure-storage-blob ``` -------------------------------- ### Create Uploads Directory for Media Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md This bash command creates the necessary directory for user uploads. Ensure that your web server's HTTP user has write permissions to this directory (`public/uploads/media`). ```bash mkdir -p public/uploads/media ``` -------------------------------- ### Configure SonataMediaBundle settings in YAML Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Provides the main configuration for SonataMediaBundle, defining media classes, database driver, contexts, providers, formats, CDN, and filesystem settings. Adjust the values to match your project needs. ```yaml # config/packages/sonata_media.yaml sonata_media: class: media: App\Entity\SonataMediaMedia gallery: App\Entity\SonataMediaGallery gallery_item: App\Entity\SonataMediaGalleryItem db_driver: doctrine_orm # or doctrine_mongodb, it is mandatory to choose one here default_context: default # you need to set a context contexts: default: # the default context is mandatory providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file - sonata.media.provider.vimeo formats: small: { width: 100, quality: 70 } big: { width: 500, quality: 70 } cdn: server: path: /uploads/media filesystem: local: directory: '%kernel.project_dir%/public/uploads/media' create: false ``` -------------------------------- ### Add SonataMediaBundle Routes Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md This configuration snippet adds the necessary routes for SonataMediaBundle to your Symfony application. Place this in your `config/routes.yaml` file to enable media-related routes. ```yaml # config/routes.yaml media: resource: '@SonataMediaBundle/Resources/config/routing/media.xml' prefix: /media ``` -------------------------------- ### Install Symfony Messenger via Composer (Bash) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/messenger.md Installs the Symfony Messenger component required for asynchronous thumbnail generation. This command adds the messenger package to the project's dependencies using Composer. ```bash composer require symfony/messenger ``` -------------------------------- ### PHP Coding Style Fixer Command Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/CONTRIBUTING.md This command installs and runs the PHP Coding Standard Fixer to ensure code adheres to PSR-1, PSR-2, and Symfony Coding Standards. It requires PHP and Composer to be installed. ```bash php-cs-fixer fix --verbose ``` -------------------------------- ### Configure Security Strategy and Download Mode Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/security.md YAML configuration example for setting security strategy and download mode in SonataMediaBundle. This sets up a context with superadmin security strategy and HTTP download mode. The configuration defines access control and download behavior for media files. ```yaml # config/packages/sonata_media.yaml sonata_media: db_driver: doctrine_orm contexts: default: # the default context is mandatory download: strategy: sonata.media.security.superadmin_strategy mode: http providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file ``` -------------------------------- ### Install AWS SDK Dependencies for S3 Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/amazon_s3.md Installs required Composer packages for Amazon S3 integration with Sonata Media Bundle. The standard AWS SDK provides core S3 functionality, while the async adapter offers non-blocking S3 operations for better performance in high-concurrency environments. ```bash composer require aws/aws-sdk-php ``` ```bash composer require async-aws/simple-s3 ``` -------------------------------- ### PHP Docblock Annotations for Static Analysis Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/CONTRIBUTING.md Example of using PHP docblock annotations for static analysis, preferring @phpstan- annotations for IDE support and @psalm- annotations for consistency. Standard annotations are used when necessary. This snippet demonstrates type hinting, parameter and return types, and template usage. ```php /** * @param Bar|Baz $foo * @param class-string $class * @param int $limit a crucial, fascinating comment * * @return object * * @phpstan-template T of object * @phpstan-param class-string $class * @phpstan-return T */ protected function bar($foo, string $class, int $limit): object { // ... } ``` -------------------------------- ### Enable SonataMediaBundle in Symfony bundles configuration Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Registers the SonataMediaBundle in the Symfony application by adding it to the config/bundles.php file. This ensures the bundle is loaded in all environments. ```php // config/bundles.php return [ // ... Sonata\MediaBundle\SonataMediaBundle::class => ['all' => true], ]; ``` -------------------------------- ### Configure Sonata MediaBundle to Use Custom Document Classes Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md This YAML configuration tells SonataMediaBundle which custom document classes to use for media, galleries, and gallery items. Update your `config/packages/sonata_media.yaml` with these settings. ```yaml # config/packages/sonata_media.yaml sonata_media: db_driver: doctrine_mongodb class: media: App\Document\SonataMediaMedia gallery: App\Document\SonataMediaGallery gallery_item: App\Document\SonataMediaGalleryItem ``` -------------------------------- ### Custom HTTP Client Configuration (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/UPGRADE-4.0.md This configuration snippet demonstrates how to provide custom implementations for the HTTP client and message factory services. This is required if you were previously using `kriswallsmith/buzz` and need to migrate to a PSR-18 compatible client. ```yaml sonata_media: http: client: 'your_custom.buzz_client' # Psr\Http\Client\ClientInterface message_factory: 'your_custom.message_facory' # Psr\Http\Message\RequestFactoryInterface ``` -------------------------------- ### Configure Sonata MediaBundle Contexts and Providers Source: https://context7.com/sonata-project/sonatamediabundle/llms.txt This YAML configuration defines the media contexts, including available providers (image, file, youtube, vimeo) and image formats with their dimensions and quality settings. It also specifies the default context, CDN path, and local filesystem directory for media storage. This setup is crucial for how media is handled and presented within the application. ```yaml sonata_media: db_driver: doctrine_orm class: media: App\Entity\SonataMediaMedia gallery: App\Entity\SonataMediaGallery gallery_item: App\Entity\SonataMediaGalleryItem default_context: default contexts: default: providers: - sonata.media.provider.image - sonata.media.provider.file - sonata.media.provider.youtube - sonata.media.provider.vimeo formats: small: width: 100 height: 100 quality: 70 resizer: sonata.media.resizer.simple medium: width: 300 quality: 80 large: width: 800 quality: 90 download: strategy: sonata.media.security.public_strategy mode: http news: providers: - sonata.media.provider.image formats: thumbnail: width: 150 height: 150 quality: 95 article: width: 600 cdn: server: path: /uploads/media filesystem: local: directory: '%kernel.project_dir%/public/uploads/media' create: false # Amazon S3 Configuration (optional) # sonata_media: # cdn: # cloudfront: # path: https://d1234567890.cloudfront.net/uploads/media # distribution_id: E1234EXAMPLE # key: AKIAIOSFODNN7EXAMPLE # secret: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY # region: us-east-1 # # filesystem: # s3: # bucket: my-media-bucket # accessKey: AKIAIOSFODNN7EXAMPLE # secretKey: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY # region: us-east-1 # acl: public ``` -------------------------------- ### Manage Providers and Contexts with Sonata MediaBundle Pool Source: https://context7.com/sonata-project/sonatamediabundle/llms.txt Demonstrates how to retrieve and manage media providers and their configurations using the Sonata MediaBundle's provider pool. This includes getting specific providers, listing all providers for a context, accessing context settings like formats and download strategies, and checking CDN access permissions. ```php use Sonata\MediaBundle\Provider\Pool; use Sonata\MediaBundle\Provider\MediaProviderInterface; /** @var Pool $pool */ $pool = $this->container->get('sonata.media.pool'); // Get specific provider $imageProvider = $pool->getProvider('sonata.media.provider.image'); // Get all providers for context $defaultProviders = $pool->getProvidersByContext('default'); foreach ($defaultProviders as $name => $provider) { echo sprintf("Provider: %s\n", $name); } // Get context configuration $contextConfig = $pool->getContext('default'); // Returns: // [ // 'providers' => ['sonata.media.provider.image', ...], // 'formats' => ['small' => [...], 'large' => [...]], // 'download' => ['strategy' => '...', 'mode' => 'http'] // ] // Get available formats for context $formats = $contextConfig['formats']; foreach ($formats as $formatName => $formatConfig) { echo sprintf("Format: %s (%dx%d)\n", $formatName, $formatConfig['width'] ?? 'auto', $formatConfig['height'] ?? 'auto' ); } // Get download strategy for context $downloadStrategy = $pool->getDownloadStrategy('default'); if ($downloadStrategy->isGranted($media, $request)) { $response = $imageProvider->getDownloadResponse($media, 'reference', 'http'); } ``` -------------------------------- ### Define SonataMediaGallery entity class Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Creates the Gallery entity extending Sonata's BaseGallery with an auto‑generated integer identifier, enabling gallery persistence via Doctrine ORM. ```php // src/Entity/SonataMediaGallery.php use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; use Sonata\MediaBundle\Entity\BaseGallery; #[ORM\Entity] #[ORM\Table(name: 'media__gallery')] class SonataMediaGallery extends BaseGallery { #[ORM\Id] #[ORM\Column(type: Types::INTEGER)] #[ORM\GeneratedValue] protected ?int $id = null; public function getId(): ?int { return $this->id; } } ``` -------------------------------- ### Add SonataMediaBundle Doctrine ORM mapping Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Integrates SonataMediaBundle entity mappings into Doctrine ORM configuration, enabling automatic mapping of the bundle's entities. ```yaml # config/packages/doctrine.yaml doctrine: orm: entity_managers: default: mappings: SonataMediaBundle: ~ ``` -------------------------------- ### Define SonataMediaGalleryItem entity class Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Creates the GalleryItem entity extending Sonata's BaseGalleryItem with an auto‑generated integer identifier, allowing association of media items with galleries. ```php // src/Entity/SonataMediaGalleryItem.php use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; use Sonata\MediaBundle\Entity\BaseGalleryItem; #[ORM\Entity] #[ORM\Table(name: 'media__gallery_item')] class SonataMediaGalleryItem extends BaseGalleryItem { #[ORM\Id] #[ORM\Column(type: Types::INTEGER)] #[ORM\GeneratedValue] protected ?int $id = null; public function getId(): ?int { return $this->id; } } ``` -------------------------------- ### Define Sonata MediaBundle Document Classes (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md These PHP classes define the document structure for media, galleries, and gallery items using Doctrine MongoDB ODM annotations. They extend the base classes provided by SonataMediaBundle. Ensure these are placed in `src/Document/`. ```php // src/Document/SonataMediaMedia.php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; use Sonata\MediaBundle\Document\BaseMedia; #[ODM\Document] class SonataMediaMedia extends BaseMedia { #[ODM\Id] protected $id; } ``` ```php // src/Document/SonataMediaGallery.php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; use Sonata\MediaBundle\Document\BaseGallery; #[ODM\Document] class SonataMediaGallery extends BaseGallery { #[ODM\Id] protected $id; } ``` ```php // src/Document/SonataMediaGalleryItem.php use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; use Sonata\MediaBundle\Document\BaseGalleryItem; #[ODM\Document] class SonataMediaGalleryItem extends BaseGalleryItem { #[ODM\Id] protected $id; } ``` -------------------------------- ### Update database schema with Doctrine Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Executes the Doctrine schema update command to create or modify database tables based on the defined entity mappings. Use the '--force' flag to apply changes immediately. ```bash bin/console doctrine:schema:update --force ``` -------------------------------- ### Deprecating Classes, Properties, and Methods (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/CONTRIBUTING.md Demonstrates how to mark classes, properties, and methods as deprecated in PHP using the `@deprecated` annotation and `trigger_error`. Includes examples with `NEXT_MAJOR` tags for future removal and specific version information. ```php /** * NEXT_MAJOR: Remove this class. * * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0. Use Shiny\New\ClassOfTheMonth instead. */ final class IAmOldAndUseless { } final class StillUsedClass { /** * NEXT_MAJOR: Remove this property. * * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0. */ public $butNotThisProperty; /** * NEXT_MAJOR: Remove this method. * * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0. */ public function iAmBatman() { @trigger_error(sprintf( 'Method %s() is deprecated since sonata-project/foo-lib 42.x and will be removed in version 43.0.', __METHOD__ ), \E_USER_DEPRECATED); echo "But this is not Gotham here."; } } ``` -------------------------------- ### Build Create and Edit Forms for Media (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/creating_a_provider_class.md Defines create form with binaryContent input and edit form with multiple fields like name, enabled, and binaryContent. Used by MediaAdmin to delegate form setup per provider. Depends on FormMapper interface. Inputs: FormMapper object. Outputs: configured form fields. Limitations: edit form excludes metadata editing as it's provider-internal. ```PHP public function buildCreateForm(FormMapper $form): void { $form->add('binaryContent', [], ['type' => 'string']); } public function buildEditForm(FormMapper $form): void { $form->add('name'); $form->add('enabled'); $form->add('authorName'); $form->add('cdnIsFlushable'); $form->add('description'); $form->add('copyright'); $form->add('binaryContent', [], ['type' => 'string']); } ``` -------------------------------- ### Updating MediaController Signatures (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/UPGRADE-4.0.md Example of how to update the method signatures in `MediaController` to include `Request $request` as the first parameter. This change is necessary for `downloadAction`, `listAction`, and `liipImagineFilterAction` if you are extending this controller. ```php // Before // public function downloadAction($id) // After public function downloadAction(Request $request, $id) ``` -------------------------------- ### Initialize VimeoProvider Class (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/creating_a_provider_class.md Sets up the VimeoProvider class extending BaseProvider for Vimeo video handling. Imports necessary classes for form mapping and media models. Purpose is to establish the provider foundation. No specific inputs or outputs during initialization. Limitations: requires Sonata bundles for full functionality. ```PHP namespace Sonata\MediaBundle\Provider; use Sonata\MediaBundle\Provider\BaseProvider; use Sonata\AdminBundle\Form\FormMapper; use Sonata\MediaBundle\Model\MediaInterface; use Symfony\Component\Form\Form; final class VimeoProvider extends BaseProvider { } ``` -------------------------------- ### Sonata MediaBundle CLI for Batch Media Operations Source: https://context7.com/sonata-project/sonatamediabundle/llms.txt This section lists various command-line interface (CLI) commands provided by Sonata MediaBundle for managing media assets. These commands facilitate operations such as adding single or multiple media files, synchronizing and removing thumbnails, cleaning orphaned media, fixing media contexts, refreshing metadata, and updating CDN status, enabling efficient batch processing. ```bash # Add single media file bin/console sonata:media:add sonata.media.provider.image default /path/to/image.jpg \ --description="Landscape photo" \ --copyright="© 2024 John Doe" \ --author="John Doe" \ --enabled=true # Add multiple media files from directory bin/console sonata:media:add-mass default /path/to/images/ \ --provider=sonata.media.provider.image # Generate/regenerate thumbnails bin/console sonata:media:sync-thumbs default sonata.media.provider.image # Remove thumbnails for format bin/console sonata:media:remove-thumbs default --format=small # Clean orphaned media (not referenced by any entity) bin/console sonata:media:clean default # Fix media context bin/console sonata:media:fix-media-context # Refresh metadata from original files bin/console sonata:media:refresh-metadata default # Update CDN status bin/console sonata:media:update-cdn-status ``` -------------------------------- ### Register Video Provider Service (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/creating_a_provider_class.md Registering a custom provider service in `config/services.yaml` with the `sonata.media.provider` tag makes it available in the provider pool. This configuration includes setting the class, arguments (like filesystem, CDN, generator, thumbnail, and optional clients), and callbacks for templates and resizers. ```yaml # config/services.yaml sonata.media.provider.vimeo: class: Sonata\MediaBundle\Provider\VimeoProvider arguments: - sonata.media.provider.vimeo - '@sonata.media.filesystem.local' - '@sonata.media.cdn.server' - '@sonata.media.generator.default' - '@sonata.media.thumbnail.format' # - '@sonata.media.http.client' // It's an optional parameter. # - '@sonata.media.metadata.proxy' // This parameter is required when you are using PSR client. calls: - - setTemplates - - helper_thumbnail: '@@SonataMedia/Provider/thumbnail.html.twig' helper_view: '@@SonataMedia/Provider/view_vimeo.html.twig' - - setResizer - ['@sonata.media.resizer.simple'] tags: - { name: sonata.media.provider } public: true ``` -------------------------------- ### Configure provider resizer for images Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Overrides the default image resizer for SonataMediaBundle, setting the resizer to the square implementation. This influences how image formats are resized. ```yaml # config/packages/sonata_media.yaml (additional snippet) sonata_media: providers: image: resizer: sonata.media.resizer.square ``` -------------------------------- ### Configure filesystem adapters for media storage Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/advanced_configuration.md Sets up various filesystem adapters for storing media files including local, FTP, S3, Azure, and replication options. Each adapter requires specific connection parameters and configuration options. ```yaml filesystem: local: directory: '%kernel.project_dir%/web/uploads/media' create: false ftp: directory: host: username: password: port: 21 passive: false create: false mode: !php/const FTP_BINARY # @see: https://www.php.net/manual/en/ftp.constants.php s3: bucket: accessKey: secretKey: create: false region: s3.amazonaws.com # change if not using US Standard region version: 2006-03-01 # change according the API version you are using storage: standard # can be one of: standard or reduced acl: public # can be one of: public, private, open, auth_read, owner_read, owner_full_control encryption: aes256 # can be aes256 or not set cache_control: max-age=86400 # or any other meta: key1: value1 #any amount of metas(sent as x-amz-meta-key1 = value1) async: false azure: container_name: connection_string: create_container: false replicate: primary: sonata.media.adapter.filesystem.s3 secondary: sonata.media.adapter.filesystem.local ``` -------------------------------- ### Configure Media Providers and Services Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/advanced_configuration.md YAML configuration for Sonata Media Bundle defining multiple media providers with their respective services, filesystem, CDN, generator, and thumbnail settings. Includes HTTP client and messenger configuration. ```yaml thumbnail: sonata.media.thumbnail.format allowed_extensions: ['jpg', 'png', 'jpeg'] allowed_mime_types: ['image/pjpeg', 'image/jpeg', 'image/png', 'image/x-png'] youtube: service: sonata.media.provider.youtube resizer: sonata.media.resizer.simple filesystem: sonata.media.filesystem.local cdn: sonata.media.cdn.server generator: sonata.media.generator.default thumbnail: sonata.media.thumbnail.format html5: false dailymotion: service: sonata.media.provider.dailymotion resizer: sonata.media.resizer.simple filesystem: sonata.media.filesystem.local cdn: sonata.media.cdn.server generator: sonata.media.generator.default thumbnail: sonata.media.thumbnail.format http: client: sonata.media.http.base_client # You need symfony/http-client for this message_factory: sonata.media.http.base_message_factory # You need nyholm/psr7 for this messenger: enabled: false generate_thumbnails_bus: messenger.default_bus ``` -------------------------------- ### Configure Doctrine MongoDB for Sonata MediaBundle Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md This YAML snippet configures the Doctrine MongoDB ODM to recognize the SonataMediaBundle mapping. Ensure this is present in your `config/packages/doctrine_mongodb.yaml` file. ```yaml # config/packages/doctrine_mongodb.yaml doctrine_mongodb: odm: mappings: SonataMediaBundle: ~ ``` -------------------------------- ### Configure Sonata Media to Use Liip Imagine (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/extra.md Configures SonataMediaBundle to use the LiipImagineBundle's thumbnail service. This ensures that thumbnail generation is handled by LiipImagine, with options for allowed file extensions and MIME types. ```yaml sonata_media: providers: image: thumbnail: sonata.media.thumbnail.liip_imagine allowed_extensions: ['jpg', 'png', 'gif', 'jpeg'] # Optional allowed_mime_types: ['image/pjpeg','image/jpeg','image/png','image/x-png', 'image/gif'] # Optional vimeo: thumbnail: sonata.media.thumbnail.liip_imagine youtube: thumbnail: sonata.media.thumbnail.liip_imagine dailymotion: thumbnail: sonata.media.thumbnail.liip_imagine cdn: # The CDN part must point to the base root of your application with a valid htaccess to match non existant # file. The non existant image will be send to the SonataMediaBundle:Media:liipImagineFilter controller. server: path: 'http://mydomain.com' ``` -------------------------------- ### Define SonataMediaMedia entity class Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/installation.md Creates the Media entity extending Sonata's BaseMedia, with an auto‑generated integer identifier. Used by Doctrine ORM for media persistence. ```php // src/Entity/SonataMediaMedia.php use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; use Sonata\MediaBundle\Entity\BaseMedia; #[ORM\Entity] #[ORM\Table(name: 'media__media')] class SonataMediaMedia extends BaseMedia { #[ORM\Id] #[ORM\Column(type: Types::INTEGER)] #[ORM\GeneratedValue] protected ?int $id = null; public function getId(): ?int { return $this->id; } } ``` -------------------------------- ### Embed YouTube Video in HTML Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/tests/Fixtures/valid_youtube.txt HTML snippet to embed a YouTube video using object and embed tags. The video URL and dimensions are specified directly in the markup. ```html ``` -------------------------------- ### Configure Media Contexts (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/media_context.md Defines contexts in Sonata Media Bundle with associated providers and formats for different media types like images and videos. Allows customization of sizes, quality, resizers, and constraints. Requires configuration in config/packages/sonata_media.yaml for proper media uploading and resizing. ```yaml # config/packages/sonata_media.yaml sonata_media: contexts: default: # the default context is mandatory providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file formats: small: { width: 100, quality: 70 } big: { width: 500, quality: 70, resizer: sonata.media.resizer.square } news: providers: - sonata.media.provider.youtube - sonata.media.provider.image formats: small: { width: 150, quality: 95 } big: { width: 500, quality: 90, constraint: false } ``` -------------------------------- ### Configure SonataMediaBundle contexts and providers Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/advanced_configuration.md Defines the main configuration structure for SonataMediaBundle including database driver, entity classes, and force disable category settings. Sets up different media contexts with their respective providers and format configurations. ```yaml sonata_media: db_driver: doctrine_orm class: media: App\Entity\SonataMediaMedia gallery: App\Entity\SonataMediaGallery gallery_item: App\Entity\SonataMediaGalleryItem category: null # App\Entity\SonataClassificationCategory if exists force_disable_category: false # true, if you really want to disable the relation with category default_context: default admin_format: { width: 200, quality: 90, format: 'jpg' } contexts: default: # the default context is mandatory download: strategy: sonata.media.security.superadmin_strategy mode: http providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file formats: small: { width: 100, quality: 70 } big: { width: 500, quality: 70, resizer: sonata.media.resizer.square } # You can pass through any custom option to resizer by using the resizer_options key icon: { width: 32, quality: 70, resizer: your.custom.resizer, resizer_options: { custom_crop: true } } tv: download: strategy: sonata.media.security.superadmin_strategy mode: http providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.video formats: cinema: { width: 1850, height: 768 } grandmatv: { width: 640, height: 480 } news: download: strategy: sonata.media.security.superadmin_strategy mode: http providers: - sonata.media.provider.dailymotion - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file formats: small: { width: 150, quality: 95 } big: { width: 500, quality: 90 } ``` -------------------------------- ### Configure Liip Imagine Filters (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/extra.md Defines custom filter sets for LiipImagineBundle, specifying image manipulation options like quality and thumbnail size. These sets are named using the CONTEXTNAME_FORMATNAME convention. ```yaml liip_imagine: filter_sets: default_small: quality: 75 filters: thumbnail: { size: [100, 70], mode: outbound } default_big: quality: 75 filters: thumbnail: { size: [500, 70], mode: outbound } ``` -------------------------------- ### Configure CKEditor default toolbar in FOS CKEditor (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/extra.md Sets up the default CKEditor toolbar and file browser routes for Sonata Media integration. Requires the fos_ck_editor bundle and defines toolbar items, browsing, and upload routes. Adjust the context and format parameters to customize media handling. ```yaml fos_ck_editor: default_config: default configs: default: # default toolbar plus Format button toolbar: - [Bold, Italic, Underline, -, Cut, Copy, Paste, PasteText, PasteFromWord, -, Undo, Redo, -, NumberedList, BulletedList, -, Outdent, Indent, -, Blockquote, -, Image, Link, Unlink, Table] - [Format, Maximize, Source] filebrowserBrowseRoute: admin_sonata_media_media_ckeditor_browser filebrowserImageBrowseRoute: admin_sonata_media_media_ckeditor_browser # Display images by default when clicking the image dialog browse button filebrowserImageBrowseRouteParameters: provider: sonata.media.provider.image filebrowserUploadMethod: form filebrowserUploadRoute: admin_sonata_media_media_ckeditor_upload filebrowserUploadRouteParameters: provider: sonata.media.provider.file # Upload file as image when sending a file from the image dialog filebrowserImageUploadRoute: admin_sonata_media_media_ckeditor_upload filebrowserImageUploadRouteParameters: provider: sonata.media.provider.image context: my-context # Optional, to upload in a custom context format: my-big # Optional, media format or original size returned to editor ``` -------------------------------- ### SQL Migration for cdnIsFlushable Field Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/UPGRADE-4.0.md This SQL statement is used to update the `cdnIsFlushable` field in the media table. It ensures that the field, which is no longer nullable, is set to `false` for any existing rows where it is currently `NULL`. This is a necessary step before upgrading the database schema. ```sql UPDATE media__media SET cdnIsFlushable = false WHERE cdnIsFlushable IS NULL; ``` -------------------------------- ### Implement backward compatible interface method in PHP Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/CONTRIBUTING.md Demonstrates how to add a new method to an existing PHP interface while maintaining backward compatibility. Uses a @method annotation in the docblock to provide IDE support for the new method. Includes a NEXT_MAJOR marker comment to indicate code that should be uncommented in the next major version. ```php getMetadataValue('thumbnail_url'); } ``` -------------------------------- ### Vimeo Helper Properties Generation (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/creating_a_provider_class.md The `getHelperProperties` method in `VideoProvider` normalizes options for embedding Vimeo videos. It merges default player parameters with user-provided options and constructs an array containing the video source URL, ID, dimensions, and frameborder. ```php public function getHelperProperties(Media $media, string $format, array $options = []): array { // documentation: http://vimeo.com/api/docs/moogaloop $defaults = [ // (optional) Flash Player version of app. Defaults to 9 .NEW! // 10 - New Moogaloop. 9 - Old Moogaloop without newest features. 'fp_version' => 10, // (optional) Enable fullscreen capability. Defaults to true. 'fullscreen' => true, // (optional) Show the byline on the video. Defaults to true. 'title' => true, // (optional) Show the title on the video. Defaults to true. 'byline' => 0, // (optional) Show the user's portrait on the video. Defaults to true. 'portrait' => true, // (optional) Specify the color of the video controls. 'color' => null, // (optional) Set to 1 to disable HD. 'hd_off' => 0, // Set to 1 to enable the Javascript API. 'js_api' => null, // (optional) JS function called when the player loads. Defaults to vimeo_player_loaded. 'js_onLoad' => 0, // Unique id that is passed into all player events as the ending parameter. 'js_swf_id' => uniqid('vimeo_player_'), ]; $playerParameters = array_merge($defaults, isset($options['player_parameters']) ? $options['player_parameters'] : []); $params = [ 'src' => http_build_query($playerParameters), 'id' => $playerParameters['js_swf_id'], 'frameborder' => $options['frameborder'] ?? 0, 'width' => $options['width'] ?? $media->getWidth(), 'height' => $options['height'] ?? $media->getHeight(), ]; return $params; } ``` -------------------------------- ### Create Download Link in Twig Template Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/security.md Twig template code for generating download links using SonataMediaBundle's download route. The example uses the sonata_media_download route with URL-safe media ID parameter. This allows users to download media files through the configured security strategy. ```html+twig Download file ``` -------------------------------- ### Configure media providers and their settings Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/advanced_configuration.md Defines provider configurations for different media types including file and image providers. Each provider specifies its service, resizer, filesystem, CDN, generator, thumbnail, and allowed file extensions and MIME types. ```yaml providers: file: service: sonata.media.provider.file resizer: null filesystem: sonata.media.filesystem.local cdn: sonata.media.cdn.server generator: sonata.media.generator.default thumbnail: sonata.media.thumbnail.format allowed_extensions: ['pdf', 'txt', 'rtf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pttx', 'odt', 'odg', 'odp', 'ods', 'odc', 'odf', 'odb', 'csv', 'xml'] allowed_mime_types: ['application/pdf', 'application/x-pdf', 'application/rtf', 'text/html', 'text/rtf', 'text/plain'] image: service: sonata.media.provider.image resizer: sonata.media.resizer.simple # sonata.media.resizer.square, sonata.media.resizer.crop filesystem: sonata.media.filesystem.local cdn: sonata.media.cdn.server generator: sonata.media.generator.default ``` -------------------------------- ### Saving a media file in SonataMediaBundle Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/usage.md Demonstrates how to save a media file by setting binary content, context, and provider name. Requires a media manager instance to perform the save operation. Shows two approaches for saving media with the same functionality. ```php $media = new Media(); $media->setBinaryContent('13142153'); $media->setContext('user'); // video related to the user $media->setProviderName('sonata.media.provider.youtube'); /** @var Sonata\MediaBundle\Model\MediaManagerInterface $mediaManager */ $mediaManager->save($media); ``` ```php $media = new Media(); $media->setBinaryContent('13142153'); $mediaManager->save($media, 'user', 'sonata.media.provider.youtube'); ``` -------------------------------- ### Sonata Media Helper Basics in Twig Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/helpers.md The sonata_media helper generates the full media element, such as images or videos. It takes a media object, size, and optional attributes. For image providers, it defaults to responsive img tags with srcset and sizes. ```twig {{ sonata_media(media, 'small') }} {{ sonata_media(media, 'small', {'class': 'myclass'}) }} ``` -------------------------------- ### Render Media in Twig Templates (Sonata MediaBundle) Source: https://context7.com/sonata-project/sonatamediabundle/llms.txt Demonstrates how to render various media types like images, thumbnails, and embed videos using Sonata's Twig functions. It supports responsive images with `srcset`, art direction with the `` element, and simple file links. The `sonata_media` and `sonata_path` functions are key for generating correct URLs and HTML. ```twig {# Simple image #} {{ media.name }} {# Responsive image with srcset #} {{ sonata_media(media, 'large', { 'class': 'img-fluid', 'alt': media.description, 'sizes': '(min-width: 768px) 50vw, 100vw' }) }} {# Outputs: Beautiful image #} {# Picture element for art direction #} {{ sonata_media(media, 'desktop', { 'picture': { '(max-width: 500px)': 'mobile', '(max-width: 1200px)': 'tablet', '(min-width: 1201px)': 'desktop' } }) }} {# Outputs: ... #} {# Thumbnail for gallery #} {{ sonata_thumbnail(media, 'small', {'class': 'gallery-thumb'}) }} {# File download link #} Download {{ media.name }} {# YouTube video embed #} {% if media.providerName == 'sonata.media.provider.youtube' %} {{ sonata_media(media, 'default') }} {# Renders iframe embed #} {% endif %} ``` -------------------------------- ### Pre-Persist Media with Vimeo Data (PHP) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/creating_a_provider_class.md Populates media object with provider details, metadata, and common fields like name, description from Vimeo's JSON. Sets status to OK and timestamps. Called by AdminBundle during save. Dependencies: getMetadata method. Inputs: MediaInterface object. Outputs: updated media. Limitations: only processes if binaryContent exists. ```PHP public function prePersist(MediaInterface $media): void { if (!$media->getBinaryContent()) { return; } // retrieve metadata $metadata = $this->getMetadata($media); // store provider information $media->setProviderName($this->name); $media->setProviderReference($media->getBinaryContent()); $media->setProviderMetadata($metadata); // update Media common field from metadata $media->setName($metadata['title']); $media->setDescription($metadata['description']); $media->setAuthorName($metadata['author_name']); $media->setHeight($metadata['height']); $media->setWidth($metadata['width']); $media->setLength($metadata['duration']); $media->setContentType('video/x-flv'); $media->setProviderStatus(Media::STATUS_OK); $media->setCreatedAt(new \DateTime()); $media->setUpdatedAt(new \DateTime()); } ``` -------------------------------- ### Configure Symfony Messenger for Sonata Media Thumbnails (YAML) Source: https://github.com/sonata-project/sonatamediabundle/blob/4.x/docs/reference/messenger.md Sets up Sonata Media to generate thumbnails asynchronously by enabling Messenger, defining provider thumbnail services, configuring an async transport, routing messages, and optionally specifying a custom message bus. These YAML snippets modify the project's configuration files. ```yaml # config/packages/sonata_media.yaml sonata_media: messenger: enabled: true providers: image: thumbnail: sonata.media.thumbnail.messenger vimeo: thumbnail: sonata.media.thumbnail.messenger youtube: thumbnail: sonata.media.thumbnail.messenger dailymotion: thumbnail: sonata.media.thumbnail.messenger ``` ```yaml # config/packages/messenger.yaml framework: messenger: transports: async: '%env(MESSENGER_TRANSPORT_DSN)%' routing: 'Sonata\\MediaBundle\\Messenger\\GenerateThumbnailsMessage': async ``` ```yaml # config/packages/sonata_media.yaml sonata_media: messenger: enabled: true generate_thumbnails_bus: my.defined.bus ``` ```yaml # config/packages/messenger.yaml framework: messenger: buses: my.defined.bus: ```