Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tiny Png Sonata Media Bundle Laravel Package

ekino/tiny-png-sonata-media-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require ekino/tiny-png-sonata-media-bundle
    

    Add the bundle to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    Ekino\TinyPngSonataMediaBundle\EkinoTinyPngSonataMediaBundle::class => ['all' => true],
    
  2. Configure TinyPNG API Key: Add your TinyPNG API key to config/packages/ekino_tiny_png_sonata_media.yaml:

    ekino_tiny_png_sonata_media:
        api_key: '%env(TINYPNG_API_KEY)%'
    

    Ensure the key is in your .env file:

    TINYPNG_API_KEY=your_api_key_here
    
  3. Enable Optimization for Media Providers: Extend your SonataMedia provider configuration to include the EkinoTinyPngSonataMediaBundle\Provider\TinyPngProvider:

    sonata_media:
        providers:
            sonata.media.provider.image:
                format: sonata.media.format.image
                filesystem: sonata.media.filesystem.local
                cdn: sonata.media.cdn.generic
                extensions: ['jpg', 'jpeg', 'png', 'gif']
                provider: sonata.media.provider.image
                context: sonata.media.context.image
                tiny_png: true  # Enable TinyPNG optimization
    
  4. First Use Case: Upload an image via SonataMedia admin. The bundle will automatically optimize the image on save if TinyPNG is enabled for the provider.


Implementation Patterns

Workflow Integration

  1. Media Upload & Optimization:

    • When uploading an image through SonataMedia, the bundle intercepts the process and sends the image to TinyPNG for optimization.
    • Use the tiny_png: true flag in your media provider configuration to enable optimization for specific providers.
  2. Asynchronous Processing:

    • The bundle supports asynchronous optimization via Symfony’s Messenger component (if configured). Ensure your config/packages/messenger.yaml includes:
      framework:
          messenger:
              transports:
                  async: '%env(MESSENGER_TRANSPORT_DSN)%'
      
    • Configure the bundle to use async processing:
      ekino_tiny_png_sonata_media:
          async: true
      
  3. Customizing Optimization:

    • Override the default TinyPNG client behavior by extending the Ekino\TinyPngSonataMediaBundle\Client\TinyPngClient class and injecting it as a service:
      services:
          ekino.tiny_png.client:
              class: App\Custom\TinyPngClient
              arguments:
                  - '%env(TINYPNG_API_KEY)%'
      
  4. Handling Notifications:

    • Use SonataNotificationBundle to notify users of optimization status. Configure the bundle to send notifications:
      ekino_tiny_png_sonata_media:
          notifications:
              enabled: true
              recipient: '%env(ADMIN_EMAIL)%'
      

Common Use Cases

  • Batch Optimization: Re-optimize existing media by triggering the optimization process manually. Use the Ekino\TinyPngSonataMediaBundle\Command\OptimizeMediaCommand:

    php bin/console ekino:tiny-png:optimize-media
    
  • Conditional Optimization: Optimize only specific media types or sizes by extending the provider logic or using event listeners.


Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Ensure your TinyPNG API key is securely stored in environment variables (.env). Hardcoding keys in configuration files is unsafe.
    • TinyPNG has rate limits (5000 requests/month for free tier). Monitor usage to avoid hitting limits.
  2. Async Processing Quirks:

    • If using async processing, ensure your messenger transport is properly configured and running (e.g., a Redis or Doctrine transport).
    • Failed async jobs may not trigger immediate feedback. Implement a retry mechanism or use Symfony’s FailedMessageHandler.
  3. Provider Configuration:

    • The tiny_png: true flag must be set per provider. Misconfiguration may lead to optimization not being applied to all intended media.
    • Verify that your media provider’s extensions include the file types you want to optimize (e.g., ['jpg', 'png']).
  4. File Size Limits:

    • TinyPNG has a 5MB file size limit for free accounts. Larger files will fail optimization. Handle exceptions gracefully:
      // In a custom client or event subscriber
      try {
          $client->optimize($filePath);
      } catch (\Ekino\TinyPngSonataMediaBundle\Exception\TinyPngException $e) {
          $this->logger->error('TinyPNG optimization failed: ' . $e->getMessage());
          // Fallback to local optimization or skip
      }
      

Debugging Tips

  1. Enable Debug Logging: Add the following to config/packages/dev/ekino_tiny_png_sonata_media.yaml:

    ekino_tiny_png_sonata_media:
        debug: true
    

    This will log API responses and errors to var/log/dev.log.

  2. Check Event Listeners: The bundle dispatches events (ekino.tiny_png.media.pre_optimize, ekino.tiny_png.media.post_optimize). Subscribe to these to debug the optimization pipeline:

    // src/EventListener/TinyPngListener.php
    public static function getSubscribedEvents()
    {
        return [
            'ekino.tiny_png.media.pre_optimize' => 'onPreOptimize',
            'ekino.tiny_png.media.post_optimize' => 'onPostOptimize',
        ];
    }
    
  3. Manual Testing: Test the TinyPNG client directly to isolate issues:

    $client = $this->container->get('ekino.tiny_png.client');
    $result = $client->optimize('/path/to/image.jpg');
    

Extension Points

  1. Custom Optimization Logic: Extend the Ekino\TinyPngSonataMediaBundle\Provider\TinyPngProvider to add pre/post-processing steps:

    // src/Provider/CustomTinyPngProvider.php
    class CustomTinyPngProvider extends TinyPngProvider
    {
        public function preOptimize(MediaInterface $media)
        {
            // Custom logic before TinyPNG optimization
        }
    
        public function postOptimize(MediaInterface $media, $optimizedPath)
        {
            // Custom logic after TinyPng optimization
        }
    }
    

    Register the service in config/services.yaml:

    services:
        App\Provider\CustomTinyPngProvider:
            tags: ['sonata.media.provider']
    
  2. Add Custom Metadata: Store optimization metadata (e.g., original size, optimized size) in the media entity:

    // In a post-optimize event subscriber
    $media->setMetadata('tiny_png_optimized', true);
    $media->setMetadata('original_size', filesize($originalPath));
    $media->setMetadata('optimized_size', filesize($optimizedPath));
    $media->save();
    
  3. Fallback to Local Optimization: If TinyPNG fails, fall back to local optimization (e.g., using imagick or gd):

    // In a custom provider or event subscriber
    if (!$tinyPngSuccess) {
        $this->fallbackOptimize($media);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware