Skip to content

Instantly share code, notes, and snippets.

@zemd
Last active December 11, 2015 17:40
Show Gist options
  • Save zemd/923eed272798f3e3f86a to your computer and use it in GitHub Desktop.
Save zemd/923eed272798f3e3f86a to your computer and use it in GitHub Desktop.
Due to standard symfony's mime guessers doesn't detect proper svg files' mime, there should be some simple way to detect it
<?php
namespace AppBundle;
use AppBundle\File\MimeType\SVGMimeTypeGuesser;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
public function boot() {
parent::boot();
MimeTypeGuesser::getInstance()->register(new SVGMimeTypeGuesser());
}
}
<?php
namespace AppBundle\File\MimeType;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
class SVGMimeTypeGuesser implements MimeTypeGuesserInterface {
private $MIMETYPE_NAMESPACES = array(
'http://www.w3.org/2000/svg' => 'image/svg+xml'
);
/**
* Returns whether this guesser is supported on the current OS.
*
* @return bool
*/
public static function isSupported()
{
return class_exists('DOMDocument') && class_exists('DOMXPath');
}
/**
* Guesses the mime type of the file with the given path.
*
* @param string $path The path to the file
*
* @return string The mime type or NULL, if none could be guessed
*
* @throws FileNotFoundException If the file does not exist
* @throws AccessDeniedException If the file could not be read
*/
public function guess($path) {
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
if (!is_readable($path)) {
throw new AccessDeniedException($path);
}
if (!self::isSupported()) {
return;
}
$dom = new \DOMDocument();
$xml = $dom->load($path, LIBXML_NOERROR + LIBXML_ERR_FATAL + LIBXML_ERR_NONE);
if ($xml === false) {
return;
}
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('namespace::*') as $node) {
if (isset($this->MIMETYPE_NAMESPACES[$node->nodeValue])) {
return $this->MIMETYPE_NAMESPACES[$node->nodeValue];
}
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment