Skip to content

Instantly share code, notes, and snippets.

@patilvishalvs
Forked from bnchdrff/addext.php
Created February 22, 2017 06:43
Show Gist options
  • Save patilvishalvs/e55744785e6441b78ffc450cee75ee21 to your computer and use it in GitHub Desktop.
Save patilvishalvs/e55744785e6441b78ffc450cee75ee21 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