You are here

public function SanitizerHelper::sanitize in SVG Upload Sanitizer 8

Sanitize a File entity.

Parameters

\Drupal\file\FileInterface $file: The file.

Return value

bool TRUE if the sanitization has succeeded. FALSE otherwise.

Throws

\Exception

File

src/Helper/SanitizerHelper.php, line 59

Class

SanitizerHelper
Sanitizer Helper class.

Namespace

Drupal\svg_upload_sanitizer\Helper

Code

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;
}