Install the Bundle
composer require 1tomany/data-uri-bundle
Add to config/bundles.php:
return [
// ...
OneToMany\DataUriBundle\OneToManyDataUriBundle::class => ['all' => true],
];
First Use Case: Embedding a File in an API Response
DataUriInterface property:
use OneToMany\DataUri\Contract\Record\DataUriInterface;
class ProductDto
{
private DataUriInterface $image;
}
use Symfony\Component\Serializer\Annotation\Context;
#[Context(['groups' => ['api']])]
public function getImage(): DataUriInterface
{
return $this->image;
}
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,...).
Automatic Serialization
DataUriNormalizer for DataUriInterface objects. No manual configuration is needed for basic use.# 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
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());
}
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();
}
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();
}));
File Upload Workflow
Email Attachments
$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));
Progressive Enhancement
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;
Large File Bloat
if ($fileSize > 1024 * 1024) {
throw new \RuntimeException('File too large for Data URI');
}
Serializer Conflicts
DataUriInterface is not properly tagged, serialization may fail silently.config/packages/serializer.yaml:
services:
OneToMany\DataUriBundle\Serializer\DataUriNormalizer:
tags: ['serializer.normalizer']
File Path Resolution
DataUri::fromFile() use absolute paths. Relative paths may fail.realpath() or resolve paths relative to the project root:
$absolutePath = realpath(__DIR__ . '/../../uploads/' . $relativePath);
Character Encoding
$safeFilename = rawurlencode($filename);
Binary Safety
Console Command Errors
onetomany:data-uri:encode-file fails, check:
chmod -R 755 uploads/).php -r 'var_dump(realpath("path"));').Serialization Issues
$this->container->get('debug')->setDebug(true);
Performance Bottlenecks
blackfire run php bin/console onetomany:data-uri:encode-file large_file.bin
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;
}
}
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);
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
Testing
Mock the DataUri service in PHPUnit:
$this->container->get('test.service_container')->set(
OneToMany\DataUri\DataUri::class,
$this->createMock(OneToMany\DataUri\DataUri::class)
);
Fallback URLs Provide a fallback URL when encoding fails:
How can I help you explore Laravel packages today?