You are here

public static function FileManagement::getAllowedFileExtensions in File Management 8

Finds all usages of a given file and returns the allowed file extensions.

Parameters

\Drupal\file\FileInterface $file: The file entity to check for (global) allowed file extensions.

Return value

array|bool Returns an array with the allowed file extensions, an empty array if there are no restrictions and FALSE if there are no common allowed file extensions.

Throws

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

File

src/FileManagement.php, line 165

Class

FileManagement
File Management helper methods.

Namespace

Drupal\file_management

Code

public static function getAllowedFileExtensions(FileInterface $file) {
  $filtering = FALSE;
  $allowed_file_extensions = [];
  $overall_allowed_file_extensions = [];
  $file_references = file_get_file_references($file);
  $file_usages = \Drupal::service('file.usage')
    ->listUsage($file);
  foreach ($file_usages as $module => $file_usage) {
    foreach ($file_usage as $entity_type => $entity_ids) {
      foreach ($entity_ids as $entity_id => $usage_count) {
        $entity = \Drupal::entityTypeManager()
          ->getStorage($entity_type)
          ->load($entity_id);
        if (!empty($entity)) {
          foreach ($file_references as $field_name => $file_reference) {
            $field_config = FieldConfig::loadByName($entity_type, $entity
              ->bundle(), $field_name);
            if (!empty($field_config)) {
              $file_extensions = $field_config
                ->getSetting('file_extensions');
              $overall_allowed_file_extensions[] = explode(' ', $file_extensions);
            }
          }
        }
      }
    }
  }
  if (!empty($overall_allowed_file_extensions)) {
    $filtering = TRUE;
    $allowed_file_extensions = $overall_allowed_file_extensions[0];
  }
  foreach ($overall_allowed_file_extensions as $single_allowed_file_extensions) {
    $allowed_file_extensions = array_intersect($allowed_file_extensions, $single_allowed_file_extensions);
  }
  if ($filtering && empty($allowed_file_extensions)) {
    $allowed_file_extensions = FALSE;
  }
  return $allowed_file_extensions;
}