Skip to content

Commit

Permalink
Merge pull request #150 from Kunstmaan/feature/add-svg-support
Browse files Browse the repository at this point in the history
Implement simple SVG mime type guesser
  • Loading branch information
kimausloos committed Jun 25, 2014
2 parents 94b52a7 + bd6d317 commit 9d6eed8
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions Helper/File/FileHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function __construct()
{
$this->mimeTypeGuesser = MimeTypeGuesser::getInstance();
$this->mimeTypeGuesser->register(new FileBinaryMimeTypeGuesser());
$this->mimeTypeGuesser->register(new SVGMimeTypeGuesser());
}

/**
Expand Down
71 changes: 71 additions & 0 deletions Helper/File/SVGMimeTypeGuesser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
/**
* Created by Kunstmaan.
* Date: 25/06/14
* Time: 09:28
*/

namespace Kunstmaan\MediaBundle\Helper\File;

use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;

/**
* SVGMimeTypeGuesser
*
* Simple Mime type guesser to detect SVG image files, it will test if the file is an XML file and return SVG mime type
* if the XML contains a valid SVG namespace...
*
* @package Kunstmaan\MediaBundle\Helper\File
*/
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');
}

/**
* {@inheritdoc}
*/
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;
}
}

0 comments on commit 9d6eed8

Please sign in to comment.