function svg_image_field_validate_mime_type in SVG Image Field 8
Same name and namespace in other branches
- 2.1.x svg_image_field.module \svg_image_field_validate_mime_type()
- 2.0.x svg_image_field.module \svg_image_field_validate_mime_type()
Checks that the file has valid mime type.
Parameters
\Drupal\file\FileInterface $file: A file entity.
Return value
array An empty array if the mime_type is allowed or an array containing an error message if it's not.
See also
1 call to svg_image_field_validate_mime_type()
- FileValidationTest::testFileValidation in tests/
src/ Unit/ FileValidationTest.php - Checks that the list of files is being checked as expected.
File
- ./
svg_image_field.module, line 100 - Contains svg_image_field.module.
Code
function svg_image_field_validate_mime_type(FileInterface $file) {
$errors = [];
$file_system = \Drupal::service('file_system');
$file_path = $file_system
->realpath($file
->getFileUri());
$mime_type = mime_content_type($file_path);
$allowed_mime_types = [
'image/svg+xml',
'image/svg',
];
if (in_array($mime_type, $allowed_mime_types) === FALSE) {
$errors[] = t('Only files with mime type %mime-types-allowed are allowed. Mime type detected %mime-type-detected', [
'%mime-types-allowed' => implode(',', $allowed_mime_types),
'%mime-type-detected' => $mime_type,
]);
}
else {
$xml = new DOMDocument();
if (@$xml
->load($file_path) === FALSE || $xml
->getElementsByTagName('svg')->length === 0) {
$errors[] = t('File %file-name is not valid svg', [
'%file-name' => $file
->getFilename(),
]);
}
}
return $errors;
}