Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active July 3, 2022 10:00
Show Gist options
  • Save ismail1432/8a6cb27feb571ce522abbb8cce9de06d to your computer and use it in GitHub Desktop.
Save ismail1432/8a6cb27feb571ce522abbb8cce9de06d to your computer and use it in GitHub Desktop.
// Kernel.php
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Mime\FileBinaryMimeTypeGuesser;
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container)
{
// We should guess the mimetype from the FileBinaryMimeTypeGuesser first.
// We register it as a service
$container->register(FileBinaryMimeTypeGuesser::class, FileBinaryMimeTypeGuesser::class);
$container
// We get the service MimeTypes that is aliased by 'mime_types'
->getDefinition('mime_types')
// we call the method 'registerGuesser' on the MimeTypes with parameterFileBinaryMimeTypeGuesser
->addMethodCall('registerGuesser', [new Reference(FileBinaryMimeTypeGuesser::class)])
;
}
}
// FileCreator.php
use Symfony\Component\Mime\{MimeTypes, FileBinaryMimeTypeGuesser};
class FileCreator
{
private MimeTypesInterface $mimeTypes;
public function __construct(MimeTypesInterface $mimeTypes)
{
$this->mimeTypes = $mimeTypes;
}
public function create(string $filePath): void
{
$mimeType = $this->mimeTypes->guessMimeType($filePath);
if (false === $this->supports($mimeType)) {
// throw error
}
// stuff
}
private function supports(?string $mimeType): bool
{
return 'application/pdf' === $mimeType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment