Skip to content

Instantly share code, notes, and snippets.

@bnchdrff
Created July 26, 2016 15:38
Show Gist options
  • Save bnchdrff/590a353ee78259fd7c66ced7950e76ef to your computer and use it in GitHub Desktop.
Save bnchdrff/590a353ee78259fd7c66ced7950e76ef to your computer and use it in GitHub Desktop.
add extensions to file_managed entities
<?php
use Drupal\Core\File\FileSystem;
use Drupal\file\Entity\File;
$container = \Drupal::getContainer();
$eq = $container->get('entity.query');
$fs = $container->get('file_system');
$type_map = [
'image/gif' => '.gif',
'image/jpeg' => '.jpg',
'image/png' => '.png',
];
$files = File::loadMultiple($eq->get('file')->execute());
foreach ($files as $file) {
if (!file_has_extension($file)) {
$type = mime_content_type($fs->realpath($file->getFileUri()));
if (isset($type_map[$type])) {
$newname = $file->getFileUri() . $type_map[$type];
file_move($file, $newname);
}
}
}
function file_has_extension(File $file) {
$extension = pathinfo($file->getFilename())['extension'];
return ($extension !== NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment