-
-
Save patilvishalvs/e55744785e6441b78ffc450cee75ee21 to your computer and use it in GitHub Desktop.
add extensions to file_managed entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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