-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #150 from Kunstmaan/feature/add-svg-support
Implement simple SVG mime type guesser
- Loading branch information
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |