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

Data Uri Bundle Laravel Package

1tomany/data-uri-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Bundle

    composer require 1tomany/data-uri-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        OneToMany\DataUriBundle\OneToManyDataUriBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Embedding a File in an API Response

    • Create a DTO or Entity with a DataUriInterface property:
      use OneToMany\DataUri\Contract\Record\DataUriInterface;
      
      class ProductDto
      {
          private DataUriInterface $image;
      }
      
    • Annotate the property for serialization:
      use Symfony\Component\Serializer\Annotation\Context;
      
      #[Context(['groups' => ['api']])]
      public function getImage(): DataUriInterface
      {
          return $this->image;
      }
      
  3. Test with the CLI Command Encode a file manually to verify functionality:

    php bin/console onetomany:data-uri:encode-file /path/to/your/file.png
    

    Outputs a base64 Data URI (e.g., data:image/png;base64,...).


Implementation Patterns

Usage Patterns

  1. Automatic Serialization

    • The bundle auto-registers DataUriNormalizer for DataUriInterface objects. No manual configuration is needed for basic use.
    • Example with API Platform:
      # config/packages/api_platform.yaml
      api_platform:
          formats:
              jsonld: ['application/ld+json']
              json: ['application/json']
              html: ['text/html']
              csv: ['text/csv']
              xml: ['application/xml']
              jsonapi: ['application/vnd.api+json']
              data_uri: ['application/vnd.data-uri+json']  # Custom format for Data URIs
      
  2. Manual Encoding in Controllers Use the underlying DataUri service directly:

    use OneToMany\DataUri\DataUri;
    
    public function showImage(UploadedFile $file)
    {
        $dataUri = DataUri::fromFile($file->getPathname());
        return new Response($dataUri->getUri());
    }
    
  3. Conditional Encoding Fall back to URLs for large files:

    public function getAsset(Asset $asset)
    {
        if ($asset->getSize() > 1024 * 1024) { // 1MB
            return $asset->getUrl();
        }
        return DataUri::fromFile($asset->getPath())->getUri();
    }
    
  4. Twig Integration Embed Data URIs in emails or templates:

    <img src="{{ asset.image|data_uri_encode }}" alt="Product">
    

    Create a custom Twig extension:

    use OneToMany\DataUri\DataUri;
    use Twig\TwigFunction;
    
    $twig->addFunction(new TwigFunction('data_uri_encode', function ($filePath) {
        return DataUri::fromFile($filePath)->getUri();
    }));
    

Workflows

  1. File Upload Workflow

    • Upload a file to a temporary location.
    • Store the path in the database (or use a Flysystem adapter).
    • Serialize the entity to include the Data URI in API responses.
  2. Email Attachments

    • Generate Data URIs for inline images in HTML emails:
      $email = (new Email())
          ->from(new Address('sender@example.com', 'Sender'))
          ->to('recipient@example.com')
          ->html('<img src="cid:logo">')
          ->embedFromPath($logoPath, 'logo');
      $dataUri = DataUri::fromFile($logoPath)->getUri();
      $email->html(str_replace('cid:logo', $dataUri, $email->html));
      
  3. Progressive Enhancement

    • Start with small files (e.g., icons, thumbnails).
    • Gradually expand to larger assets, monitoring performance impact.

Integration Tips

  • Flysystem Support Extend the bundle to support Flysystem adapters:

    use League\Flysystem\Filesystem;
    use OneToMany\DataUri\DataUri;
    
    $dataUri = DataUri::fromStream(
        $filesystem->readStream('path/to/file'),
        $filesystem->mimeType('path/to/file')
    );
    
  • Caching Cache encoded URIs to avoid repeated file reads:

    $cacheKey = 'data_uri_' . md5($filePath);
    $dataUri = $cache->get($cacheKey, function () use ($filePath) {
        return DataUri::fromFile($filePath)->getUri();
    });
    
  • Validation Validate file types/sizes before encoding:

    use Symfony\Component\Validator\Constraints as Assert;
    
    #[Assert\File(
        maxSize: '1M',
        mimeTypes: ['image/png', 'image/jpeg'],
        mimeTypesMessage: 'Only PNG or JPEG images are allowed.'
    )]
    private $image;
    

Gotchas and Tips

Pitfalls

  1. Large File Bloat

    • Data URIs can triple the size of binary files (base64 overhead). Avoid for files >1MB.
    • Fix: Implement a size threshold fallback:
      if ($fileSize > 1024 * 1024) {
          throw new \RuntimeException('File too large for Data URI');
      }
      
  2. Serializer Conflicts

    • If DataUriInterface is not properly tagged, serialization may fail silently.
    • Fix: Explicitly tag the normalizer in config/packages/serializer.yaml:
      services:
          OneToMany\DataUriBundle\Serializer\DataUriNormalizer:
              tags: ['serializer.normalizer']
      
  3. File Path Resolution

    • The CLI command and DataUri::fromFile() use absolute paths. Relative paths may fail.
    • Fix: Use realpath() or resolve paths relative to the project root:
      $absolutePath = realpath(__DIR__ . '/../../uploads/' . $relativePath);
      
  4. Character Encoding

    • Non-UTF8 filenames may cause issues in Data URIs.
    • Fix: Encode filenames safely:
      $safeFilename = rawurlencode($filename);
      
  5. Binary Safety

    • Data URIs can expose sensitive data if files are not validated.
    • Fix: Restrict to trusted sources (e.g., uploads directory) and validate MIME types.

Debugging

  1. Console Command Errors

    • If onetomany:data-uri:encode-file fails, check:
      • File permissions (chmod -R 755 uploads/).
      • Path correctness (php -r 'var_dump(realpath("path"));').
  2. Serialization Issues

    • Enable debug mode to see serializer errors:
      $this->container->get('debug')->setDebug(true);
      
    • Check for circular references or unsupported types.
  3. Performance Bottlenecks

    • Profile encoding time with Xdebug or Blackfire:
      blackfire run php bin/console onetomany:data-uri:encode-file large_file.bin
      

Tips

  1. Custom DataUriInterface Implement your own interface for type safety:

    namespace App\DataUri;
    
    use OneToMany\DataUri\Contract\Record\DataUriInterface;
    
    class AppDataUri implements DataUriInterface
    {
        private string $uri;
    
        public function __construct(string $uri)
        {
            $this->uri = $uri;
        }
    
        public function getUri(): string
        {
            return $this->uri;
        }
    }
    
  2. Dynamic MIME Types Use Symfony’s MimeTypeGuesser for dynamic MIME detection:

    use Symfony\Component\Mime\MimeTypes;
    
    $mimeTypes = new MimeTypes();
    $mimeType = $mimeTypes->guessIndex($filePath);
    $dataUri = DataUri::fromFile($filePath, $mimeType);
    
  3. Environment-Specific Config Disable Data URIs in production for large files:

    # config/packages/data_uri.yaml
    parameters:
        data_uri_max_size: '%env(int:DATA_URI_MAX_SIZE, 512000)' # 500KB
    
  4. Testing Mock the DataUri service in PHPUnit:

    $this->container->get('test.service_container')->set(
        OneToMany\DataUri\DataUri::class,
        $this->createMock(OneToMany\DataUri\DataUri::class)
    );
    
  5. Fallback URLs Provide a fallback URL when encoding fails:

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor