SanitizerHelper.php in SVG Upload Sanitizer 8
File
src/Helper/SanitizerHelper.php
View source
<?php
namespace Drupal\svg_upload_sanitizer\Helper;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\FileInterface;
use enshrined\svgSanitize\Sanitizer;
use Psr\Log\LoggerAwareTrait;
class SanitizerHelper {
use LoggerAwareTrait;
private $fileSystem;
private $sanitizer;
public function __construct(FileSystemInterface $file_system, Sanitizer $sanitizer) {
$this->fileSystem = $file_system;
$this->sanitizer = $sanitizer;
}
public function sanitize(FileInterface $file) {
if ('image/svg+xml' !== $file
->getMimeType()) {
return FALSE;
}
$filePath = $this->fileSystem
->realpath($file
->getFileUri());
if (FALSE === $filePath) {
$this->logger
->notice(sprintf('Could not resolve the path of the file (URI: "%s").', $file
->getFileUri()));
return FALSE;
}
if (FALSE === file_exists($filePath)) {
$this->logger
->notice(sprintf('The file does not exist (path: "%s").', $filePath));
return FALSE;
}
$fileContent = file_get_contents($filePath);
if (FALSE === $fileContent || empty($fileContent)) {
$this->logger
->notice(sprintf('Could not retrieve the content of the file (path: "%s").', $filePath));
return FALSE;
}
$fileCleanContent = $this->sanitizer
->sanitize($fileContent);
if (FALSE === file_put_contents($filePath, $fileCleanContent)) {
throw new \Exception(sprintf('Cannot sanitize the file (URI: "%s")', $file
->getFileUri()));
}
return TRUE;
}
}