diff options
author | xjm <xjm@65776.no-reply.drupal.org> | 2017-03-03 19:20:24 -0600 |
---|---|---|
committer | xjm <xjm@65776.no-reply.drupal.org> | 2017-03-03 19:20:24 -0600 |
commit | 52e3eec616efab4d5201e30d085a09ba5c4817e6 (patch) | |
tree | d295cc8b862edc04018ba0e04ded752fd1a2f5c6 /core/modules/file | |
parent | 3aba956a39a4852f42cad8483e4e6e307bedbd0e (diff) | |
download | drupal-52e3eec616efab4d5201e30d085a09ba5c4817e6.tar.gz drupal-52e3eec616efab4d5201e30d085a09ba5c4817e6.zip |
Issue #2776975 by joelpittet, dawehner, tim.plunkett, xjm, pfrenssen: March 3, 2017: Convert core to array syntax coding standards for Drupal 8.3.x RC phase
Diffstat (limited to 'core/modules/file')
70 files changed, 1094 insertions, 1094 deletions
diff --git a/core/modules/file/file.api.php b/core/modules/file/file.api.php index c7994ff7231..1fda717da7a 100644 --- a/core/modules/file/file.api.php +++ b/core/modules/file/file.api.php @@ -25,7 +25,7 @@ * @see file_validate() */ function hook_file_validate(Drupal\file\FileInterface $file) { - $errors = array(); + $errors = []; if (!$file->getFilename()) { $errors[] = t("The file's name is empty. Please give a name to the file."); @@ -53,7 +53,7 @@ function hook_file_copy(Drupal\file\FileInterface $file, Drupal\file\FileInterfa $file->setFilename($file->getOwner()->name . '_' . $file->getFilename()); $file->save(); - \Drupal::logger('file')->notice('Copied file %source has been renamed to %destination', array('%source' => $source->filename, '%destination' => $file->getFilename())); + \Drupal::logger('file')->notice('Copied file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]); } } @@ -73,7 +73,7 @@ function hook_file_move(Drupal\file\FileInterface $file, Drupal\file\FileInterfa $file->setFilename($file->getOwner()->name . '_' . $file->getFilename()); $file->save(); - \Drupal::logger('file')->notice('Moved file %source has been renamed to %destination', array('%source' => $source->filename, '%destination' => $file->getFilename())); + \Drupal::logger('file')->notice('Moved file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]); } } diff --git a/core/modules/file/file.field.inc b/core/modules/file/file.field.inc index bbfc2b23ea4..80ffbe99794 100644 --- a/core/modules/file/file.field.inc +++ b/core/modules/file/file.field.inc @@ -26,26 +26,26 @@ function template_preprocess_file_widget_multiple(&$variables) { $table_id = $element['#id'] . '-table'; // Build up a table of applicable fields. - $headers = array(); + $headers = []; $headers[] = t('File information'); if ($element['#display_field']) { - $headers[] = array( + $headers[] = [ 'data' => t('Display'), - 'class' => array('checkbox'), - ); + 'class' => ['checkbox'], + ]; } $headers[] = t('Weight'); $headers[] = t('Operations'); // Get our list of widgets in order (needed when the form comes back after // preview or failed validation). - $widgets = array(); + $widgets = []; foreach (Element::children($element) as $key) { $widgets[] = &$element[$key]; } usort($widgets, '_field_multiple_value_form_sort_helper'); - $rows = array(); + $rows = []; foreach ($widgets as $key => &$widget) { // Save the uploading row for last. if (empty($widget['#files'])) { @@ -56,7 +56,7 @@ function template_preprocess_file_widget_multiple(&$variables) { // Delay rendering of the buttons, so that they can be rendered later in the // "operations" column. - $operations_elements = array(); + $operations_elements = []; foreach (Element::children($widget) as $sub_key) { if (isset($widget[$sub_key]['#type']) && $widget[$sub_key]['#type'] == 'submit') { hide($widget[$sub_key]); @@ -72,21 +72,21 @@ function template_preprocess_file_widget_multiple(&$variables) { hide($widget['_weight']); // Render everything else together in a column, without the normal wrappers. - $widget['#theme_wrappers'] = array(); + $widget['#theme_wrappers'] = []; $information = drupal_render($widget); $display = ''; if ($element['#display_field']) { unset($widget['display']['#title']); - $display = array( + $display = [ 'data' => render($widget['display']), - 'class' => array('checkbox'), - ); + 'class' => ['checkbox'], + ]; } - $widget['_weight']['#attributes']['class'] = array($weight_class); + $widget['_weight']['#attributes']['class'] = [$weight_class]; $weight = render($widget['_weight']); // Arrange the row with all of the rendered columns. - $row = array(); + $row = []; $row[] = $information; if ($element['#display_field']) { $row[] = $display; @@ -98,31 +98,31 @@ function template_preprocess_file_widget_multiple(&$variables) { foreach (Element::children($operations_elements) as $key) { show($operations_elements[$key]); } - $row[] = array( + $row[] = [ 'data' => $operations_elements, - ); - $rows[] = array( + ]; + $rows[] = [ 'data' => $row, - 'class' => isset($widget['#attributes']['class']) ? array_merge($widget['#attributes']['class'], array('draggable')) : array('draggable'), - ); + 'class' => isset($widget['#attributes']['class']) ? array_merge($widget['#attributes']['class'], ['draggable']) : ['draggable'], + ]; } - $variables['table'] = array( + $variables['table'] = [ '#type' => 'table', '#header' => $headers, '#rows' => $rows, - '#attributes' => array( + '#attributes' => [ 'id' => $table_id, - ), - '#tabledrag' => array( - array( + ], + '#tabledrag' => [ + [ 'action' => 'order', 'relationship' => 'sibling', 'group' => $weight_class, - ), - ), + ], + ], '#access' => !empty($rows), - ); + ]; $variables['element'] = $element; } @@ -144,7 +144,7 @@ function template_preprocess_file_upload_help(&$variables) { $upload_validators = $variables['upload_validators']; $cardinality = $variables['cardinality']; - $descriptions = array(); + $descriptions = []; if (!empty($description)) { $descriptions[] = FieldFilteredMarkup::create($description); @@ -158,26 +158,26 @@ function template_preprocess_file_upload_help(&$variables) { } } if (isset($upload_validators['file_validate_size'])) { - $descriptions[] = t('@size limit.', array('@size' => format_size($upload_validators['file_validate_size'][0]))); + $descriptions[] = t('@size limit.', ['@size' => format_size($upload_validators['file_validate_size'][0])]); } if (isset($upload_validators['file_validate_extensions'])) { - $descriptions[] = t('Allowed types: @extensions.', array('@extensions' => $upload_validators['file_validate_extensions'][0])); + $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $upload_validators['file_validate_extensions'][0]]); } if (isset($upload_validators['file_validate_image_resolution'])) { $max = $upload_validators['file_validate_image_resolution'][0]; $min = $upload_validators['file_validate_image_resolution'][1]; if ($min && $max && $min == $max) { - $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', array('@size' => $max)); + $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', ['@size' => $max]); } elseif ($min && $max) { - $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', array('@min' => $min, '@max' => $max)); + $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', ['@min' => $min, '@max' => $max]); } elseif ($min) { - $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', array('@min' => $min)); + $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', ['@min' => $min]); } elseif ($max) { - $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', array('@max' => $max)); + $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', ['@max' => $max]); } } diff --git a/core/modules/file/file.install b/core/modules/file/file.install index d371384664e..9134a25e9e2 100644 --- a/core/modules/file/file.install +++ b/core/modules/file/file.install @@ -9,51 +9,51 @@ * Implements hook_schema(). */ function file_schema() { - $schema['file_usage'] = array( + $schema['file_usage'] = [ 'description' => 'Track where a file is used.', - 'fields' => array( - 'fid' => array( + 'fields' => [ + 'fid' => [ 'description' => 'File ID.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, - ), - 'module' => array( + ], + 'module' => [ 'description' => 'The name of the module that is using the file.', 'type' => 'varchar_ascii', 'length' => DRUPAL_EXTENSION_NAME_MAX_LENGTH, 'not null' => TRUE, 'default' => '', - ), - 'type' => array( + ], + 'type' => [ 'description' => 'The name of the object type in which the file is used.', 'type' => 'varchar_ascii', 'length' => 64, 'not null' => TRUE, 'default' => '', - ), - 'id' => array( + ], + 'id' => [ 'description' => 'The primary key of the object using the file.', 'type' => 'varchar_ascii', 'length' => 64, 'not null' => TRUE, 'default' => 0, - ), - 'count' => array( + ], + 'count' => [ 'description' => 'The number of times this file is used by this object.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - ), - 'primary key' => array('fid', 'type', 'id', 'module'), - 'indexes' => array( - 'type_id' => array('type', 'id'), - 'fid_count' => array('fid', 'count'), - 'fid_module' => array('fid', 'module'), - ), - ); + ], + ], + 'primary key' => ['fid', 'type', 'id', 'module'], + 'indexes' => [ + 'type_id' => ['type', 'id'], + 'fid_count' => ['fid', 'count'], + 'fid_module' => ['fid', 'module'], + ], + ]; return $schema; } @@ -63,7 +63,7 @@ function file_schema() { * Display information about getting upload progress bars working. */ function file_requirements($phase) { - $requirements = array(); + $requirements = []; // Check the server's ability to indicate upload progress. if ($phase == 'runtime') { @@ -107,11 +107,11 @@ function file_requirements($phase) { elseif ($implementation == 'uploadprogress') { $value = t('Enabled (<a href="http://pecl.php.net/package/uploadprogress">PECL uploadprogress</a>)'); } - $requirements['file_progress'] = array( + $requirements['file_progress'] = [ 'title' => t('Upload progress'), 'value' => $value, 'description' => $description, - ); + ]; } return $requirements; diff --git a/core/modules/file/file.module b/core/modules/file/file.module index 687a62c70b2..a6fc3f6ebe0 100644 --- a/core/modules/file/file.module +++ b/core/modules/file/file.module @@ -30,15 +30,15 @@ function file_help($route_name, RouteMatchInterface $route_match) { case 'help.page.file': $output = ''; $output .= '<h3>' . t('About') . '</h3>'; - $output .= '<p>' . t('The File module allows you to create fields that contain files. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":file_documentation">online documentation for the File module</a>.', array(':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#', ':file_documentation' => 'https://www.drupal.org/documentation/modules/file')) . '</p>'; + $output .= '<p>' . t('The File module allows you to create fields that contain files. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":file_documentation">online documentation for the File module</a>.', [':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#', ':file_documentation' => 'https://www.drupal.org/documentation/modules/file']) . '</p>'; $output .= '<h3>' . t('Uses') . '</h3>'; $output .= '<dl>'; $output .= '<dt>' . t('Managing and displaying file fields') . '</dt>'; - $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the file field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', array(':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>'; + $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the file field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '</dd>'; $output .= '<dt>' . t('Allowing file extensions') . '</dt>'; $output .= '<dd>' . t('In the field settings, you can define the allowed file extensions (for example <em>pdf docx psd</em>) for the files that will be uploaded with the file field.') . '</dd>'; $output .= '<dt>' . t('Storing files') . '</dt>'; - $output .= '<dd>' . t('Uploaded files can either be stored as <em>public</em> or <em>private</em>, depending on the <a href=":file-system">File system settings</a>. For more information, see the <a href=":system-help">System module help page</a>.', array(':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', array('name' => 'system')))) . '</dd>'; + $output .= '<dd>' . t('Uploaded files can either be stored as <em>public</em> or <em>private</em>, depending on the <a href=":file-system">File system settings</a>. For more information, see the <a href=":system-help">System module help page</a>.', [':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', ['name' => 'system'])]) . '</dd>'; $output .= '<dt>' . t('Restricting the maximum file size') . '</dt>'; $output .= '<dd>' . t('The maximum file size that users can upload is limited by PHP settings of the server, but you can restrict by entering the desired value as the <em>Maximum upload size</em> setting. The maximum file size is automatically displayed to users in the help text of the file field.') . '</dd>'; $output .= '<dt>' . t('Displaying files and descriptions') . '<dt>'; @@ -96,7 +96,7 @@ function file_load_multiple(array $fids = NULL, $reset = FALSE) { */ function file_load($fid, $reset = FALSE) { if ($reset) { - \Drupal::entityManager()->getStorage('file')->resetCache(array($fid)); + \Drupal::entityManager()->getStorage('file')->resetCache([$fid]); } return File::load($fid); } @@ -141,12 +141,12 @@ function file_load($fid, $reset = FALSE) { function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) { if (!file_valid_uri($destination)) { if (($realpath = drupal_realpath($source->getFileUri())) !== FALSE) { - \Drupal::logger('file')->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination)); + \Drupal::logger('file')->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]); } else { - \Drupal::logger('file')->notice('File %file could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%destination' => $destination)); + \Drupal::logger('file')->notice('File %file could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]); } - drupal_set_message(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', array('%file' => $source->getFileUri())), 'error'); + drupal_set_message(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error'); return FALSE; } @@ -158,7 +158,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E // @todo Do not create a new entity in order to update it. See // https://www.drupal.org/node/2241865. if ($replace == FILE_EXISTS_REPLACE) { - $existing_files = entity_load_multiple_by_properties('file', array('uri' => $uri)); + $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]); if (count($existing_files)) { $existing = reset($existing_files); $file->fid = $existing->id(); @@ -175,7 +175,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E $file->save(); // Inform modules that the file has been copied. - \Drupal::moduleHandler()->invokeAll('file_copy', array($file, $source)); + \Drupal::moduleHandler()->invokeAll('file_copy', [$file, $source]); return $file; } @@ -216,12 +216,12 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E function file_move(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) { if (!file_valid_uri($destination)) { if (($realpath = drupal_realpath($source->getFileUri())) !== FALSE) { - \Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination)); + \Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]); } else { - \Drupal::logger('file')->notice('File %file could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%destination' => $destination)); + \Drupal::logger('file')->notice('File %file could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]); } - drupal_set_message(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', array('%file' => $source->getFileUri())), 'error'); + drupal_set_message(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error'); return FALSE; } @@ -232,7 +232,7 @@ function file_move(FileInterface $source, $destination = NULL, $replace = FILE_E $file->setFileUri($uri); // If we are replacing an existing file re-use its database record. if ($replace == FILE_EXISTS_REPLACE) { - $existing_files = entity_load_multiple_by_properties('file', array('uri' => $uri)); + $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]); if (count($existing_files)) { $existing = reset($existing_files); $delete_source = TRUE; @@ -249,7 +249,7 @@ function file_move(FileInterface $source, $destination = NULL, $replace = FILE_E $file->save(); // Inform modules that the file has been moved. - \Drupal::moduleHandler()->invokeAll('file_move', array($file, $source)); + \Drupal::moduleHandler()->invokeAll('file_move', [$file, $source]); // Delete the original if it's not in use elsewhere. if ($delete_source && !\Drupal::service('file.usage')->listUsage($source)) { @@ -283,9 +283,9 @@ function file_move(FileInterface $source, $destination = NULL, $replace = FILE_E * * @see hook_file_validate() */ -function file_validate(FileInterface $file, $validators = array()) { +function file_validate(FileInterface $file, $validators = []) { // Call the validation functions specified by this function's caller. - $errors = array(); + $errors = []; foreach ($validators as $function => $args) { if (function_exists($function)) { array_unshift($args, $file); @@ -294,7 +294,7 @@ function file_validate(FileInterface $file, $validators = array()) { } // Let other modules perform validation on the new file. - return array_merge($errors, \Drupal::moduleHandler()->invokeAll('file_validate', array($file))); + return array_merge($errors, \Drupal::moduleHandler()->invokeAll('file_validate', [$file])); } /** @@ -308,7 +308,7 @@ function file_validate(FileInterface $file, $validators = array()) { * array containing an error message if it's not or is empty. */ function file_validate_name_length(FileInterface $file) { - $errors = array(); + $errors = []; if (!$file->getFilename()) { $errors[] = t("The file's name is empty. Please give a name to the file."); @@ -334,11 +334,11 @@ function file_validate_name_length(FileInterface $file) { * @see hook_file_validate() */ function file_validate_extensions(FileInterface $file, $extensions) { - $errors = array(); + $errors = []; $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i'; if (!preg_match($regex, $file->getFilename())) { - $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions)); + $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => $extensions]); } return $errors; } @@ -363,15 +363,15 @@ function file_validate_extensions(FileInterface $file, $extensions) { */ function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = 0) { $user = \Drupal::currentUser(); - $errors = array(); + $errors = []; if ($file_limit && $file->getSize() > $file_limit) { - $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->getSize()), '%maxsize' => format_size($file_limit))); + $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', ['%filesize' => format_size($file->getSize()), '%maxsize' => format_size($file_limit)]); } // Save a query by only calling spaceUsed() when a limit is provided. if ($user_limit && (\Drupal::entityManager()->getStorage('file')->spaceUsed($user->id()) + $file->getSize()) > $user_limit) { - $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($file->getSize()), '%quota' => format_size($user_limit))); + $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', ['%filesize' => format_size($file->getSize()), '%quota' => format_size($user_limit)]); } return $errors; @@ -390,13 +390,13 @@ function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = * @see hook_file_validate() */ function file_validate_is_image(FileInterface $file) { - $errors = array(); + $errors = []; $image_factory = \Drupal::service('image.factory'); $image = $image_factory->get($file->getFileUri()); if (!$image->isValid()) { $supported_extensions = $image_factory->getSupportedExtensions(); - $errors[] = t('Image type not supported. Allowed types: %types', array('%types' => implode(' ', $supported_extensions))); + $errors[] = t('Image type not supported. Allowed types: %types', ['%types' => implode(' ', $supported_extensions)]); } return $errors; @@ -429,7 +429,7 @@ function file_validate_is_image(FileInterface $file) { * @see hook_file_validate() */ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions = 0, $minimum_dimensions = 0) { - $errors = array(); + $errors = []; // Check first that the file is an image. $image_factory = \Drupal::service('image.factory'); @@ -443,13 +443,13 @@ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions if ($image->scale($width, $height)) { $image->save(); if (!empty($width) && !empty($height)) { - $message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)); + $message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', ['%dimensions' => $maximum_dimensions]); } elseif (empty($width)) { - $message = t('The image was resized to fit within the maximum allowed height of %height pixels.', array('%height' => $height)); + $message = t('The image was resized to fit within the maximum allowed height of %height pixels.', ['%height' => $height]); } elseif (empty($height)) { - $message = t('The image was resized to fit within the maximum allowed width of %width pixels.', array('%width' => $width)); + $message = t('The image was resized to fit within the maximum allowed width of %width pixels.', ['%width' => $width]); } drupal_set_message($message); } @@ -463,7 +463,7 @@ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions // Check that it is larger than the given dimensions. list($width, $height) = explode('x', $minimum_dimensions); if ($image->getWidth() < $width || $image->getHeight() < $height) { - $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions)); + $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', ['%dimensions' => $minimum_dimensions]); } } } @@ -503,7 +503,7 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM $destination = file_default_scheme() . '://'; } if (!file_valid_uri($destination)) { - \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination)); + \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', ['%destination' => $destination]); drupal_set_message(t('The data could not be saved because the destination is invalid. More information is available in the system log.'), 'error'); return FALSE; } @@ -519,7 +519,7 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM // @todo Do not create a new entity in order to update it. See // https://www.drupal.org/node/2241865. if ($replace == FILE_EXISTS_REPLACE) { - $existing_files = entity_load_multiple_by_properties('file', array('uri' => $uri)); + $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]); if (count($existing_files)) { $existing = reset($existing_files); $file->fid = $existing->id(); @@ -552,36 +552,36 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM function file_get_content_headers(FileInterface $file) { $type = Unicode::mimeHeaderEncode($file->getMimeType()); - return array( + return [ 'Content-Type' => $type, 'Content-Length' => $file->getSize(), 'Cache-Control' => 'private', - ); + ]; } /** * Implements hook_theme(). */ function file_theme() { - return array( + return [ // From file.module. - 'file_link' => array( - 'variables' => array('file' => NULL, 'description' => NULL, 'attributes' => array()), - ), - 'file_managed_file' => array( + 'file_link' => [ + 'variables' => ['file' => NULL, 'description' => NULL, 'attributes' => []], + ], + 'file_managed_file' => [ 'render element' => 'element', - ), + ], // From file.field.inc. - 'file_widget_multiple' => array( + 'file_widget_multiple' => [ 'render element' => 'element', 'file' => 'file.field.inc', - ), - 'file_upload_help' => array( - 'variables' => array('description' => NULL, 'upload_validators' => NULL, 'cardinality' => NULL), + ], + 'file_upload_help' => [ + 'variables' => ['description' => NULL, 'upload_validators' => NULL, 'cardinality' => NULL], 'file' => 'file.field.inc', - ), - ); + ], + ]; } /** @@ -590,7 +590,7 @@ function file_theme() { function file_file_download($uri) { // Get the file record based on the URI. If not in the database just return. /** @var \Drupal\file\FileInterface[] $files */ - $files = entity_load_multiple_by_properties('file', array('uri' => $uri)); + $files = entity_load_multiple_by_properties('file', ['uri' => $uri]); if (count($files)) { foreach ($files as $item) { // Since some database servers sometimes use a case-insensitive comparison @@ -663,11 +663,11 @@ function file_cron() { $file->delete(); } else { - \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', array('%path' => $file->getFileUri())); + \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', ['%path' => $file->getFileUri()]); } } else { - \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', array('%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references)))); + \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', ['%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references))]); } } } @@ -711,11 +711,11 @@ function file_cron() { * array element contains the file entity if the upload succeeded or FALSE if * there was an error. Function returns NULL if no file was uploaded. */ -function file_save_upload($form_field_name, $validators = array(), $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) { +function file_save_upload($form_field_name, $validators = [], $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) { $user = \Drupal::currentUser(); static $upload_cache; - $all_files = \Drupal::request()->files->get('files', array()); + $all_files = \Drupal::request()->files->get('files', []); // Make sure there's an upload to process. if (empty($all_files[$form_field_name])) { return NULL; @@ -735,10 +735,10 @@ function file_save_upload($form_field_name, $validators = array(), $destination // for multiple uploads and we fix that here. $uploaded_files = $file_upload; if (!is_array($file_upload)) { - $uploaded_files = array($file_upload); + $uploaded_files = [$file_upload]; } - $files = array(); + $files = []; foreach ($uploaded_files as $i => $file_info) { // Check for file upload errors and return FALSE for this file if a lower // level system error occurred. For a complete list of errors: @@ -746,13 +746,13 @@ function file_save_upload($form_field_name, $validators = array(), $destination switch ($file_info->getError()) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: - drupal_set_message(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size()))), 'error'); + drupal_set_message(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', ['%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size())]), 'error'); $files[$i] = FALSE; continue; case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: - drupal_set_message(t('The file %file could not be saved because the upload did not complete.', array('%file' => $file_info->getFilename())), 'error'); + drupal_set_message(t('The file %file could not be saved because the upload did not complete.', ['%file' => $file_info->getFilename()]), 'error'); $files[$i] = FALSE; continue; @@ -765,19 +765,19 @@ function file_save_upload($form_field_name, $validators = array(), $destination // Unknown error default: - drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $file_info->getFilename())), 'error'); + drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', ['%file' => $file_info->getFilename()]), 'error'); $files[$i] = FALSE; continue; } // Begin building file entity. - $values = array( + $values = [ 'uid' => $user->id(), 'status' => 0, 'filename' => $file_info->getClientOriginalName(), 'uri' => $file_info->getRealPath(), 'filesize' => $file_info->getSize(), - ); + ]; $values['filemime'] = \Drupal::service('file.mime_type.guesser')->guess($values['filename']); $file = File::create($values); @@ -798,7 +798,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination // No validator was provided, so add one using the default list. // Build a default non-munged safe list for file_munge_filename(). $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'; - $validators['file_validate_extensions'] = array(); + $validators['file_validate_extensions'] = []; $validators['file_validate_extensions'][0] = $extensions; } @@ -820,7 +820,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination // to add it here or else the file upload will fail. if (!empty($extensions)) { $validators['file_validate_extensions'][0] .= ' txt'; - drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->getFilename()))); + drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()])); } } @@ -832,7 +832,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination // Assert that the destination contains a valid stream. $destination_scheme = file_uri_scheme($destination); if (!file_stream_wrapper_valid_scheme($destination_scheme)) { - drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', array('%destination' => $destination)), 'error'); + drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error'); $files[$i] = FALSE; continue; } @@ -846,28 +846,28 @@ function file_save_upload($form_field_name, $validators = array(), $destination // If file_destination() returns FALSE then $replace === FILE_EXISTS_ERROR and // there's an existing file so we need to bail. if ($file->destination === FALSE) { - drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $form_field_name, '%directory' => $destination)), 'error'); + drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', ['%source' => $form_field_name, '%directory' => $destination]), 'error'); $files[$i] = FALSE; continue; } // Add in our check of the file name length. - $validators['file_validate_name_length'] = array(); + $validators['file_validate_name_length'] = []; // Call the validation functions specified by this function's caller. $errors = file_validate($file, $validators); // Check for errors. if (!empty($errors)) { - $message = array( - 'error' => array( - '#markup' => t('The specified file %name could not be uploaded.', array('%name' => $file->getFilename())), - ), - 'item_list' => array( + $message = [ + 'error' => [ + '#markup' => t('The specified file %name could not be uploaded.', ['%name' => $file->getFilename()]), + ], + 'item_list' => [ '#theme' => 'item_list', '#items' => $errors, - ), - ); + ], + ]; // @todo Add support for render arrays in drupal_set_message()? See // https://www.drupal.org/node/2505497. drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error'); @@ -881,7 +881,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination $file->setFileUri($file->destination); if (!drupal_move_uploaded_file($file_info->getRealPath(), $file->getFileUri())) { drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error'); - \Drupal::logger('file')->notice('Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->getFilename(), '%destination' => $file->getFileUri())); + \Drupal::logger('file')->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]); $files[$i] = FALSE; continue; } @@ -893,7 +893,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination // @todo Do not create a new entity in order to update it. See // https://www.drupal.org/node/2241865. if ($replace == FILE_EXISTS_REPLACE) { - $existing_files = entity_load_multiple_by_properties('file', array('uri' => $file->getFileUri())); + $existing_files = entity_load_multiple_by_properties('file', ['uri' => $file->getFileUri()]); if (count($existing_files)) { $existing = reset($existing_files); $file->fid = $existing->id(); @@ -949,7 +949,7 @@ function file_file_predelete(File $file) { function file_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { $token_service = \Drupal::token(); - $url_options = array('absolute' => TRUE); + $url_options = ['absolute' => TRUE]; if (isset($options['langcode'])) { $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']); $langcode = $options['langcode']; @@ -958,7 +958,7 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta $langcode = NULL; } - $replacements = array(); + $replacements = []; if ($type == 'file' && !empty($data['file'])) { /** @var \Drupal\file\FileInterface $file */ @@ -1020,15 +1020,15 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta } if ($date_tokens = $token_service->findWithPrefix($tokens, 'created')) { - $replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getCreatedTime()), $options, $bubbleable_metadata); + $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getCreatedTime()], $options, $bubbleable_metadata); } if ($date_tokens = $token_service->findWithPrefix($tokens, 'changed')) { - $replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getChangedTime()), $options, $bubbleable_metadata); + $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getChangedTime()], $options, $bubbleable_metadata); } if (($owner_tokens = $token_service->findWithPrefix($tokens, 'owner')) && $file->getOwner()) { - $replacements += $token_service->generate('user', $owner_tokens, array('user' => $file->getOwner()), $options, $bubbleable_metadata); + $replacements += $token_service->generate('user', $owner_tokens, ['user' => $file->getOwner()], $options, $bubbleable_metadata); } } @@ -1039,59 +1039,59 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta * Implements hook_token_info(). */ function file_token_info() { - $types['file'] = array( + $types['file'] = [ 'name' => t("Files"), 'description' => t("Tokens related to uploaded files."), 'needs-data' => 'file', - ); + ]; // File related tokens. - $file['fid'] = array( + $file['fid'] = [ 'name' => t("File ID"), 'description' => t("The unique ID of the uploaded file."), - ); - $file['name'] = array( + ]; + $file['name'] = [ 'name' => t("File name"), 'description' => t("The name of the file on disk."), - ); - $file['path'] = array( + ]; + $file['path'] = [ 'name' => t("Path"), 'description' => t("The location of the file relative to Drupal root."), - ); - $file['mime'] = array( + ]; + $file['mime'] = [ 'name' => t("MIME type"), 'description' => t("The MIME type of the file."), - ); - $file['size'] = array( + ]; + $file['size'] = [ 'name' => t("File size"), 'description' => t("The size of the file."), - ); - $file['url'] = array( + ]; + $file['url'] = [ 'name' => t("URL"), 'description' => t("The web-accessible URL for the file."), - ); - $file['created'] = array( + ]; + $file['created'] = [ 'name' => t("Created"), 'description' => t("The date the file created."), 'type' => 'date', - ); - $file['changed'] = array( + ]; + $file['changed'] = [ 'name' => t("Changed"), 'description' => t("The date the file was most recently changed."), 'type' => 'date', - ); - $file['owner'] = array( + ]; + $file['owner'] = [ 'name' => t("Owner"), 'description' => t("The user who originally uploaded the file."), 'type' => 'user', - ); + ]; - return array( + return [ 'types' => $types, - 'tokens' => array( + 'tokens' => [ 'file' => $file, - ), - ); + ], + ]; } /** @@ -1115,7 +1115,7 @@ function file_managed_file_submit($form, FormStateInterface $form_state) { $fids = array_keys($element['#files']); // Get files that will be removed. if ($element['#multiple']) { - $remove_fids = array(); + $remove_fids = []; foreach (Element::children($element) as $name) { if (strpos($name, 'file_') === 0 && $element[$name]['selected']['#value']) { $remove_fids[] = (int) substr($name, 5); @@ -1128,7 +1128,7 @@ function file_managed_file_submit($form, FormStateInterface $form_state) { // element's value to empty array (file could not be removed from // element if we don't do that). $remove_fids = $fids; - $fids = array(); + $fids = []; } foreach ($remove_fids as $fid) { @@ -1175,7 +1175,7 @@ function file_managed_file_submit($form, FormStateInterface $form_state) { */ function file_managed_file_save_upload($element, FormStateInterface $form_state) { $upload_name = implode('_', $element['#parents']); - $all_files = \Drupal::request()->files->get('files', array()); + $all_files = \Drupal::request()->files->get('files', []); if (empty($all_files[$upload_name])) { return FALSE; } @@ -1183,7 +1183,7 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state) $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL; if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) { - \Drupal::logger('file')->notice('The upload directory %directory for the file field %name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $destination, '%name' => $element['#field_name'])); + \Drupal::logger('file')->notice('The upload directory %directory for the file field %name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', ['%directory' => $destination, '%name' => $element['#field_name']]); $form_state->setError($element, t('The file could not be uploaded.')); return FALSE; } @@ -1193,19 +1193,19 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state) $files_uploaded |= !$element['#multiple'] && !empty($file_upload); if ($files_uploaded) { if (!$files = file_save_upload($upload_name, $element['#upload_validators'], $destination)) { - \Drupal::logger('file')->notice('The file upload failed. %upload', array('%upload' => $upload_name)); - $form_state->setError($element, t('Files in the @name field were unable to be uploaded.', array('@name' => $element['#title']))); - return array(); + \Drupal::logger('file')->notice('The file upload failed. %upload', ['%upload' => $upload_name]); + $form_state->setError($element, t('Files in the @name field were unable to be uploaded.', ['@name' => $element['#title']])); + return []; } // Value callback expects FIDs to be keys. $files = array_filter($files); $fids = array_map(function($file) { return $file->id(); }, $files); - return empty($files) ? array() : array_combine($fids, $files); + return empty($files) ? [] : array_combine($fids, $files); } - return array(); + return []; } /** @@ -1220,7 +1220,7 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state) function template_preprocess_file_managed_file(&$variables) { $element = $variables['element']; - $variables['attributes'] = array(); + $variables['attributes'] = []; if (isset($element['#id'])) { $variables['attributes']['id'] = $element['#id']; } @@ -1244,7 +1244,7 @@ function template_preprocess_file_managed_file(&$variables) { */ function template_preprocess_file_link(&$variables) { $file = $variables['file']; - $options = array(); + $options = []; $file_entity = ($file instanceof File) ? $file : File::load($file->fid); // @todo Wrap in file_url_transform_relative(). This is currently @@ -1270,13 +1270,13 @@ function template_preprocess_file_link(&$variables) { } // Classes to add to the file field for icons. - $classes = array( + $classes = [ 'file', // Add a specific class for each and every mime type. - 'file--mime-' . strtr($mime_type, array('/' => '-', '.' => '-')), + 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']), // Add a more general class for groups of well known MIME types. 'file--' . file_icon_class($mime_type), - ); + ]; // Set file classes to the options array. $variables['attributes'] = new Attribute($variables['attributes']); @@ -1302,7 +1302,7 @@ function file_icon_class($mime_type) { } // Use generic icons for each category that provides such icons. - foreach (array('audio', 'image', 'text', 'video') as $category) { + foreach (['audio', 'image', 'text', 'video'] as $category) { if (strpos($mime_type, $category) === 0) { return $category; } @@ -1473,14 +1473,14 @@ function file_icon_map($mime_type) { * @ingroup file */ function file_get_file_references(FileInterface $file, FieldDefinitionInterface $field = NULL, $age = EntityStorageInterface::FIELD_LOAD_REVISION, $field_type = 'file') { - $references = &drupal_static(__FUNCTION__, array()); - $field_columns = &drupal_static(__FUNCTION__ . ':field_columns', array()); + $references = &drupal_static(__FUNCTION__, []); + $field_columns = &drupal_static(__FUNCTION__ . ':field_columns', []); // Fill the static cache, disregard $field and $field_type for now. if (!isset($references[$file->id()][$age])) { - $references[$file->id()][$age] = array(); + $references[$file->id()][$age] = []; $usage_list = \Drupal::service('file.usage')->listUsage($file); - $file_usage_list = isset($usage_list['file']) ? $usage_list['file'] : array(); + $file_usage_list = isset($usage_list['file']) ? $usage_list['file'] : []; foreach ($file_usage_list as $entity_type_id => $entity_ids) { $entities = \Drupal::entityTypeManager() ->getStorage($entity_type_id)->loadMultiple(array_keys($entity_ids)); @@ -1488,7 +1488,7 @@ function file_get_file_references(FileInterface $file, FieldDefinitionInterface $bundle = $entity->bundle(); // We need to find file fields for this entity type and bundle. if (!isset($file_fields[$entity_type_id][$bundle])) { - $file_fields[$entity_type_id][$bundle] = array(); + $file_fields[$entity_type_id][$bundle] = []; // This contains the possible field names. foreach ($entity->getFieldDefinitions() as $field_name => $field_definition) { // If this is the first time this field type is seen, check @@ -1549,10 +1549,10 @@ function file_get_file_references(FileInterface $file, FieldDefinitionInterface * An array of file statuses or a specified status if $choice is set. */ function _views_file_status($choice = NULL) { - $status = array( + $status = [ 0 => t('Temporary'), FILE_STATUS_PERMANENT => t('Permanent'), - ); + ]; if (isset($choice)) { return isset($status[$choice]) ? $status[$choice] : t('Unknown'); diff --git a/core/modules/file/file.views.inc b/core/modules/file/file.views.inc index 7fb54b61362..8e45101bd84 100644 --- a/core/modules/file/file.views.inc +++ b/core/modules/file/file.views.inc @@ -19,13 +19,13 @@ function file_field_views_data(FieldStorageConfigInterface $field_storage) { $data = views_field_default_views_data($field_storage); foreach ($data as $table_name => $table_data) { // Add the relationship only on the fid field. - $data[$table_name][$field_storage->getName() . '_target_id']['relationship'] = array( + $data[$table_name][$field_storage->getName() . '_target_id']['relationship'] = [ 'id' => 'standard', 'base' => 'file_managed', 'entity type' => 'file', 'base field' => 'fid', - 'label' => t('file from @field_name', array('@field_name' => $field_storage->getName())), - ); + 'label' => t('file from @field_name', ['@field_name' => $field_storage->getName()]), + ]; } return $data; @@ -47,11 +47,11 @@ function file_field_views_data_views_data_alter(array &$data, FieldStorageConfig list($label) = views_entity_field_label($entity_type_id, $field_name); - $data['file_managed'][$pseudo_field_name]['relationship'] = array( - 'title' => t('@entity using @field', array('@entity' => $entity_type->getLabel(), '@field' => $label)), - 'label' => t('@field_name', array('@field_name' => $field_name)), + $data['file_managed'][$pseudo_field_name]['relationship'] = [ + 'title' => t('@entity using @field', ['@entity' => $entity_type->getLabel(), '@field' => $label]), + 'label' => t('@field_name', ['@field_name' => $field_name]), 'group' => $entity_type->getLabel(), - 'help' => t('Relate each @entity with a @field set to the file.', array('@entity' => $entity_type->getLabel(), '@field' => $label)), + 'help' => t('Relate each @entity with a @field set to the file.', ['@entity' => $entity_type->getLabel(), '@field' => $label]), 'id' => 'entity_reverse', 'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(), 'entity_type' => $entity_type_id, @@ -59,12 +59,12 @@ function file_field_views_data_views_data_alter(array &$data, FieldStorageConfig 'field_name' => $field_name, 'field table' => $table_mapping->getDedicatedDataTableName($field_storage), 'field field' => $field_name . '_target_id', - 'join_extra' => array( - 0 => array( + 'join_extra' => [ + 0 => [ 'field' => 'deleted', 'value' => 0, 'numeric' => TRUE, - ), - ), - ); + ], + ], + ]; } diff --git a/core/modules/file/src/Controller/FileWidgetAjaxController.php b/core/modules/file/src/Controller/FileWidgetAjaxController.php index d5c6874528e..c9587504430 100644 --- a/core/modules/file/src/Controller/FileWidgetAjaxController.php +++ b/core/modules/file/src/Controller/FileWidgetAjaxController.php @@ -19,23 +19,23 @@ class FileWidgetAjaxController { * A JsonResponse object. */ public function progress($key) { - $progress = array( + $progress = [ 'message' => t('Starting upload...'), 'percentage' => -1, - ); + ]; $implementation = file_progress_implementation(); if ($implementation == 'uploadprogress') { $status = uploadprogress_get_info($key); if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) { - $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total']))); + $progress['message'] = t('Uploading... (@current of @total)', ['@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])]); $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']); } } elseif ($implementation == 'apc') { $status = apcu_fetch('upload_' . $key); if (isset($status['current']) && !empty($status['total'])) { - $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total']))); + $progress['message'] = t('Uploading... (@current of @total)', ['@current' => format_size($status['current']), '@total' => format_size($status['total'])]); $progress['percentage'] = round(100 * $status['current'] / $status['total']); } } diff --git a/core/modules/file/src/Element/ManagedFile.php b/core/modules/file/src/Element/ManagedFile.php index f465b181ac3..45c8aa7cec5 100644 --- a/core/modules/file/src/Element/ManagedFile.php +++ b/core/modules/file/src/Element/ManagedFile.php @@ -108,7 +108,7 @@ class ManagedFile extends FormElement { // submissions of the same form, so to allow that, check for the // token added by $this->processManagedFile(). elseif (\Drupal::currentUser()->isAnonymous()) { - $token = NestedArray::getValue($form_state->getUserInput(), array_merge($element['#parents'], array('file_' . $file->id(), 'fid_token'))); + $token = NestedArray::getValue($form_state->getUserInput(), array_merge($element['#parents'], ['file_' . $file->id(), 'fid_token'])); if ($token !== Crypt::hmacBase64('file-' . $file->id(), \Drupal::service('private_key')->get() . Settings::getHashSalt())) { $force_default = TRUE; break; @@ -334,10 +334,10 @@ class ManagedFile extends FormElement { // of the same form (for example, after an Ajax upload or form // validation error). if ($file->isTemporary() && \Drupal::currentUser()->isAnonymous()) { - $element['file_' . $delta]['fid_token'] = array( + $element['file_' . $delta]['fid_token'] = [ '#type' => 'hidden', '#value' => Crypt::hmacBase64('file-' . $delta, \Drupal::service('private_key')->get() . Settings::getHashSalt()), - ); + ]; } } } diff --git a/core/modules/file/src/Entity/File.php b/core/modules/file/src/Entity/File.php index cd7a65897f7..a68b9bae9bc 100644 --- a/core/modules/file/src/Entity/File.php +++ b/core/modules/file/src/Entity/File.php @@ -70,7 +70,7 @@ class File extends ContentEntityBase implements FileInterface { * * @see file_url_transform_relative() */ - public function url($rel = 'canonical', $options = array()) { + public function url($rel = 'canonical', $options = []) { return file_create_url($this->getFileUri()); } diff --git a/core/modules/file/src/FileUsage/DatabaseFileUsageBackend.php b/core/modules/file/src/FileUsage/DatabaseFileUsageBackend.php index 12647b112f3..cfb0c447a68 100644 --- a/core/modules/file/src/FileUsage/DatabaseFileUsageBackend.php +++ b/core/modules/file/src/FileUsage/DatabaseFileUsageBackend.php @@ -44,14 +44,14 @@ class DatabaseFileUsageBackend extends FileUsageBase { */ public function add(FileInterface $file, $module, $type, $id, $count = 1) { $this->connection->merge($this->tableName) - ->keys(array( + ->keys([ 'fid' => $file->id(), 'module' => $module, 'type' => $type, 'id' => $id, - )) - ->fields(array('count' => $count)) - ->expression('count', 'count + :count', array(':count' => $count)) + ]) + ->fields(['count' => $count]) + ->expression('count', 'count + :count', [':count' => $count]) ->execute(); parent::add($file, $module, $type, $id, $count); @@ -85,7 +85,7 @@ class DatabaseFileUsageBackend extends FileUsageBase { ->condition('type', $type) ->condition('id', $id); } - $query->expression('count', 'count - :count', array(':count' => $count)); + $query->expression('count', 'count - :count', [':count' => $count]); $query->execute(); } @@ -97,11 +97,11 @@ class DatabaseFileUsageBackend extends FileUsageBase { */ public function listUsage(FileInterface $file) { $result = $this->connection->select($this->tableName, 'f') - ->fields('f', array('module', 'type', 'id', 'count')) + ->fields('f', ['module', 'type', 'id', 'count']) ->condition('fid', $file->id()) ->condition('count', 0, '>') ->execute(); - $references = array(); + $references = []; foreach ($result as $usage) { $references[$usage->module][$usage->type][$usage->id] = $usage->count; } diff --git a/core/modules/file/src/FileViewsData.php b/core/modules/file/src/FileViewsData.php index cf240622541..459a37eba30 100644 --- a/core/modules/file/src/FileViewsData.php +++ b/core/modules/file/src/FileViewsData.php @@ -20,13 +20,13 @@ class FileViewsData extends EntityViewsData { $data['file_managed']['table']['base']['defaults']['field'] = 'filename'; $data['file_managed']['table']['wizard_id'] = 'file_managed'; - $data['file_managed']['fid']['argument'] = array( + $data['file_managed']['fid']['argument'] = [ 'id' => 'file_fid', // The field to display in the summary. 'name field' => 'filename', 'numeric' => TRUE, - ); - $data['file_managed']['fid']['relationship'] = array( + ]; + $data['file_managed']['fid']['relationship'] = [ 'title' => $this->t('File usage'), 'help' => $this->t('Relate file entities to their usage.'), 'id' => 'standard', @@ -34,24 +34,24 @@ class FileViewsData extends EntityViewsData { 'base field' => 'fid', 'field' => 'fid', 'label' => $this->t('File usage'), - ); + ]; $data['file_managed']['uri']['field']['default_formatter'] = 'file_uri'; $data['file_managed']['filemime']['field']['default_formatter'] = 'file_filemime'; - $data['file_managed']['extension'] = array( + $data['file_managed']['extension'] = [ 'title' => $this->t('Extension'), 'help' => $this->t('The extension of the file.'), 'real field' => 'filename', - 'field' => array( + 'field' => [ 'entity_type' => 'file', 'field_name' => 'filename', 'default_formatter' => 'file_extension', 'id' => 'field', 'click sortable' => FALSE, - ), - ); + ], + ]; $data['file_managed']['filesize']['field']['default_formatter'] = 'file_size'; @@ -71,40 +71,40 @@ class FileViewsData extends EntityViewsData { // ("file_managed") so that we can create relationships from files to // entities, and then on each core entity type base table so that we can // provide general relationships between entities and files. - $data['file_usage']['table']['join'] = array( - 'file_managed' => array( + $data['file_usage']['table']['join'] = [ + 'file_managed' => [ 'field' => 'fid', 'left_field' => 'fid', - ), + ], // Link ourselves to the {node_field_data} table // so we can provide node->file relationships. - 'node_field_data' => array( + 'node_field_data' => [ 'field' => 'id', 'left_field' => 'nid', - 'extra' => array(array('field' => 'type', 'value' => 'node')), - ), + 'extra' => [['field' => 'type', 'value' => 'node']], + ], // Link ourselves to the {users_field_data} table // so we can provide user->file relationships. - 'users_field_data' => array( + 'users_field_data' => [ 'field' => 'id', 'left_field' => 'uid', - 'extra' => array(array('field' => 'type', 'value' => 'user')), - ), + 'extra' => [['field' => 'type', 'value' => 'user']], + ], // Link ourselves to the {comment_field_data} table // so we can provide comment->file relationships. - 'comment' => array( + 'comment' => [ 'field' => 'id', 'left_field' => 'cid', - 'extra' => array(array('field' => 'type', 'value' => 'comment')), - ), + 'extra' => [['field' => 'type', 'value' => 'comment']], + ], // Link ourselves to the {taxonomy_term_field_data} table // so we can provide taxonomy_term->file relationships. - 'taxonomy_term_data' => array( + 'taxonomy_term_data' => [ 'field' => 'id', 'left_field' => 'tid', - 'extra' => array(array('field' => 'type', 'value' => 'taxonomy_term')), - ), - ); + 'extra' => [['field' => 'type', 'value' => 'taxonomy_term']], + ], + ]; // Provide a relationship between the files table and each entity type, // and between each entity type and the files table. Entity->file @@ -113,210 +113,210 @@ class FileViewsData extends EntityViewsData { // declarations below. // Describes relationships between files and nodes. - $data['file_usage']['file_to_node'] = array( + $data['file_usage']['file_to_node'] = [ 'title' => $this->t('Content'), 'help' => $this->t('Content that is associated with this file, usually because this file is in a field on the content.'), // Only provide this field/relationship/etc., // when the 'file_managed' base table is present. - 'skip base' => array('node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'id', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('Content'), 'label' => $this->t('Content'), 'base' => 'node_field_data', 'base field' => 'nid', 'relationship field' => 'id', - 'extra' => array(array('table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'node')), - ), - ); - $data['file_usage']['node_to_file'] = array( + 'extra' => [['table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'node']], + ], + ]; + $data['file_usage']['node_to_file'] = [ 'title' => $this->t('File'), 'help' => $this->t('A file that is associated with this node, usually because it is in a field on the node.'), // Only provide this field/relationship/etc., // when the 'node' base table is present. - 'skip base' => array('file_managed', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['file_managed', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'fid', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('File'), 'label' => $this->t('File'), 'base' => 'file_managed', 'base field' => 'fid', 'relationship field' => 'fid', - ), - ); + ], + ]; // Describes relationships between files and users. - $data['file_usage']['file_to_user'] = array( + $data['file_usage']['file_to_user'] = [ 'title' => $this->t('User'), 'help' => $this->t('A user that is associated with this file, usually because this file is in a field on the user.'), // Only provide this field/relationship/etc., // when the 'file_managed' base table is present. - 'skip base' => array('node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'id', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('User'), 'label' => $this->t('User'), 'base' => 'users', 'base field' => 'uid', 'relationship field' => 'id', - 'extra' => array(array('table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'user')), - ), - ); - $data['file_usage']['user_to_file'] = array( + 'extra' => [['table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'user']], + ], + ]; + $data['file_usage']['user_to_file'] = [ 'title' => $this->t('File'), 'help' => $this->t('A file that is associated with this user, usually because it is in a field on the user.'), // Only provide this field/relationship/etc., // when the 'users' base table is present. - 'skip base' => array('file_managed', 'node_field_data', 'node_field_revision', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['file_managed', 'node_field_data', 'node_field_revision', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'fid', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('File'), 'label' => $this->t('File'), 'base' => 'file_managed', 'base field' => 'fid', 'relationship field' => 'fid', - ), - ); + ], + ]; // Describes relationships between files and comments. - $data['file_usage']['file_to_comment'] = array( + $data['file_usage']['file_to_comment'] = [ 'title' => $this->t('Comment'), 'help' => $this->t('A comment that is associated with this file, usually because this file is in a field on the comment.'), // Only provide this field/relationship/etc., // when the 'file_managed' base table is present. - 'skip base' => array('node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'id', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('Comment'), 'label' => $this->t('Comment'), 'base' => 'comment_field_data', 'base field' => 'cid', 'relationship field' => 'id', - 'extra' => array(array('table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'comment')), - ), - ); - $data['file_usage']['comment_to_file'] = array( + 'extra' => [['table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'comment']], + ], + ]; + $data['file_usage']['comment_to_file'] = [ 'title' => $this->t('File'), 'help' => $this->t('A file that is associated with this comment, usually because it is in a field on the comment.'), // Only provide this field/relationship/etc., // when the 'comment' base table is present. - 'skip base' => array('file_managed', 'node_field_data', 'node_field_revision', 'users_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['file_managed', 'node_field_data', 'node_field_revision', 'users_field_data', 'taxonomy_term_field_data'], 'real field' => 'fid', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('File'), 'label' => $this->t('File'), 'base' => 'file_managed', 'base field' => 'fid', 'relationship field' => 'fid', - ), - ); + ], + ]; // Describes relationships between files and taxonomy_terms. - $data['file_usage']['file_to_taxonomy_term'] = array( + $data['file_usage']['file_to_taxonomy_term'] = [ 'title' => $this->t('Taxonomy Term'), 'help' => $this->t('A taxonomy term that is associated with this file, usually because this file is in a field on the taxonomy term.'), // Only provide this field/relationship/etc., // when the 'file_managed' base table is present. - 'skip base' => array('node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'), + 'skip base' => ['node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data', 'taxonomy_term_field_data'], 'real field' => 'id', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('Taxonomy Term'), 'label' => $this->t('Taxonomy Term'), 'base' => 'taxonomy_term_data', 'base field' => 'tid', 'relationship field' => 'id', - 'extra' => array(array('table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'taxonomy_term')), - ), - ); - $data['file_usage']['taxonomy_term_to_file'] = array( + 'extra' => [['table' => 'file_usage', 'field' => 'type', 'operator' => '=', 'value' => 'taxonomy_term']], + ], + ]; + $data['file_usage']['taxonomy_term_to_file'] = [ 'title' => $this->t('File'), 'help' => $this->t('A file that is associated with this taxonomy term, usually because it is in a field on the taxonomy term.'), // Only provide this field/relationship/etc., // when the 'taxonomy_term_data' base table is present. - 'skip base' => array('file_managed', 'node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data'), + 'skip base' => ['file_managed', 'node_field_data', 'node_field_revision', 'users_field_data', 'comment_field_data'], 'real field' => 'fid', - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('File'), 'label' => $this->t('File'), 'base' => 'file_managed', 'base field' => 'fid', 'relationship field' => 'fid', - ), - ); + ], + ]; // Provide basic fields from the {file_usage} table to all of the base tables // we've declared joins to, because there is no 'skip base' property on these // fields. - $data['file_usage']['module'] = array( + $data['file_usage']['module'] = [ 'title' => $this->t('Module'), 'help' => $this->t('The module managing this file relationship.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); - $data['file_usage']['type'] = array( + ], + ]; + $data['file_usage']['type'] = [ 'title' => $this->t('Entity type'), 'help' => $this->t('The type of entity that is related to the file.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); - $data['file_usage']['id'] = array( + ], + ]; + $data['file_usage']['id'] = [ 'title' => $this->t('Entity ID'), 'help' => $this->t('The ID of the entity that is related to the file.'), - 'field' => array( + 'field' => [ 'id' => 'numeric', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'numeric', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); - $data['file_usage']['count'] = array( + ], + ]; + $data['file_usage']['count'] = [ 'title' => $this->t('Use count'), 'help' => $this->t('The number of times the file is used by this entity.'), - 'field' => array( + 'field' => [ 'id' => 'numeric', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); - $data['file_usage']['entity_label'] = array( + ], + ]; + $data['file_usage']['entity_label'] = [ 'title' => $this->t('Entity label'), 'help' => $this->t('The label of the entity that is related to the file.'), 'real field' => 'id', - 'field' => array( + 'field' => [ 'id' => 'entity_label', 'entity type field' => 'type', - ), - ); + ], + ]; return $data; } diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/FileExtensionFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/FileExtensionFormatter.php index bb6a770ca60..afe1b7efc0a 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/FileExtensionFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/FileExtensionFormatter.php @@ -34,12 +34,12 @@ class FileExtensionFormatter extends BaseFieldFileFormatterBase { */ public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); - $form['extension_detect_tar'] = array( + $form['extension_detect_tar'] = [ '#type' => 'checkbox', '#title' => $this->t('Include tar in extension'), '#description' => $this->t("If the part of the filename just before the extension is '.tar', include this in the extension output."), '#default_value' => $this->getSetting('extension_detect_tar'), - ); + ]; return $form; } diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php index 6103239b6e8..631d94140ed 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php @@ -43,12 +43,12 @@ class FilemimeFormatter extends BaseFieldFileFormatterBase { public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); - $form['filemime_image'] = array( + $form['filemime_image'] = [ '#title' => $this->t('Display an icon'), '#description' => $this->t('The icon is representing the file type, instead of the MIME text (such as "image/jpeg")'), '#type' => 'checkbox', '#default_value' => $this->getSetting('filemime_image'), - ); + ]; return $form; } diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/GenericFileFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/GenericFileFormatter.php index a76d75a07af..daeb9f42c22 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/GenericFileFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/GenericFileFormatter.php @@ -21,21 +21,21 @@ class GenericFileFormatter extends FileFormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) { $item = $file->_referringItem; - $elements[$delta] = array( + $elements[$delta] = [ '#theme' => 'file_link', '#file' => $file, '#description' => $item->description, - '#cache' => array( + '#cache' => [ 'tags' => $file->getCacheTags(), - ), - ); + ], + ]; // Pass field item attributes to the theme function. if (isset($item->_attributes)) { - $elements[$delta] += array('#attributes' => array()); + $elements[$delta] += ['#attributes' => []]; $elements[$delta]['#attributes'] += $item->_attributes; // Unset field item attributes since they have been included in the // formatter output and should not be rendered in the field template. diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php index 46bbbde569a..a433d99b16e 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php @@ -25,17 +25,17 @@ class RSSEnclosureFormatter extends FileFormatterBase { // Add the first file as an enclosure to the RSS item. RSS allows only one // enclosure per item. See: http://wikipedia.org/wiki/RSS_enclosure foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) { - $entity->rss_elements[] = array( + $entity->rss_elements[] = [ 'key' => 'enclosure', - 'attributes' => array( + 'attributes' => [ // In RSS feeds, it is necessary to use absolute URLs. The 'url.site' // cache context is already associated with RSS feed responses, so it // does not need to be specified here. 'url' => file_create_url($file->getFileUri()), 'length' => $file->getSize(), 'type' => $file->getMimeType(), - ), - ); + ], + ]; } return []; } diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php index 939329a595f..4da9e84366f 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php @@ -21,33 +21,33 @@ class TableFormatter extends FileFormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; if ($files = $this->getEntitiesToView($items, $langcode)) { - $header = array(t('Attachment'), t('Size')); - $rows = array(); + $header = [t('Attachment'), t('Size')]; + $rows = []; foreach ($files as $delta => $file) { - $rows[] = array( - array( - 'data' => array( + $rows[] = [ + [ + 'data' => [ '#theme' => 'file_link', '#file' => $file, - '#cache' => array( + '#cache' => [ 'tags' => $file->getCacheTags(), - ), - ), - ), - array('data' => format_size($file->getSize())), - ); + ], + ], + ], + ['data' => format_size($file->getSize())], + ]; } - $elements[0] = array(); + $elements[0] = []; if (!empty($rows)) { - $elements[0] = array( + $elements[0] = [ '#theme' => 'table__file_formatter_table', '#header' => $header, '#rows' => $rows, - ); + ]; } } diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/UrlPlainFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/UrlPlainFormatter.php index ccb97d5ef5d..d5e2a7c70a0 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/UrlPlainFormatter.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/UrlPlainFormatter.php @@ -21,15 +21,15 @@ class UrlPlainFormatter extends FileFormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) { - $elements[$delta] = array( + $elements[$delta] = [ '#markup' => file_url_transform_relative(file_create_url($file->getFileUri())), - '#cache' => array( + '#cache' => [ 'tags' => $file->getCacheTags(), - ), - ); + ], + ]; } return $elements; diff --git a/core/modules/file/src/Plugin/Field/FieldType/FileFieldItemList.php b/core/modules/file/src/Plugin/Field/FieldType/FileFieldItemList.php index 20f47975025..9a4dc8339b7 100644 --- a/core/modules/file/src/Plugin/Field/FieldType/FileFieldItemList.php +++ b/core/modules/file/src/Plugin/Field/FieldType/FileFieldItemList.php @@ -30,7 +30,7 @@ class FileFieldItemList extends EntityReferenceFieldItemList { else { // Get current target file entities and file IDs. $files = $this->referencedEntities(); - $ids = array(); + $ids = []; /** @var \Drupal\file\FileInterface $file */ foreach ($files as $file) { @@ -48,7 +48,7 @@ class FileFieldItemList extends EntityReferenceFieldItemList { // Get the file IDs attached to the field before this update. $field_name = $this->getFieldDefinition()->getName(); - $original_ids = array(); + $original_ids = []; $langcode = $this->getLangcode(); $original = $entity->original; if ($original->hasTranslation($langcode)) { diff --git a/core/modules/file/src/Plugin/Field/FieldType/FileItem.php b/core/modules/file/src/Plugin/Field/FieldType/FileItem.php index 5ea2692ea1a..7373c4397fe 100644 --- a/core/modules/file/src/Plugin/Field/FieldType/FileItem.php +++ b/core/modules/file/src/Plugin/Field/FieldType/FileItem.php @@ -32,59 +32,59 @@ class FileItem extends EntityReferenceItem { * {@inheritdoc} */ public static function defaultStorageSettings() { - return array( + return [ 'target_type' => 'file', 'display_field' => FALSE, 'display_default' => FALSE, 'uri_scheme' => file_default_scheme(), - ) + parent::defaultStorageSettings(); + ] + parent::defaultStorageSettings(); } /** * {@inheritdoc} */ public static function defaultFieldSettings() { - return array( + return [ 'file_extensions' => 'txt', 'file_directory' => '[date:custom:Y]-[date:custom:m]', 'max_filesize' => '', 'description_field' => 0, - ) + parent::defaultFieldSettings(); + ] + parent::defaultFieldSettings(); } /** * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { - return array( - 'columns' => array( - 'target_id' => array( + return [ + 'columns' => [ + 'target_id' => [ 'description' => 'The ID of the file entity.', 'type' => 'int', 'unsigned' => TRUE, - ), - 'display' => array( + ], + 'display' => [ 'description' => 'Flag to control whether this file should be displayed when viewing content.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => TRUE, 'default' => 1, - ), - 'description' => array( + ], + 'description' => [ 'description' => 'A description of the file.', 'type' => 'text', - ), - ), - 'indexes' => array( - 'target_id' => array('target_id'), - ), - 'foreign keys' => array( - 'target_id' => array( + ], + ], + 'indexes' => [ + 'target_id' => ['target_id'], + ], + 'foreign keys' => [ + 'target_id' => [ 'table' => 'file_managed', - 'columns' => array('target_id' => 'fid'), - ), - ), - ); + 'columns' => ['target_id' => 'fid'], + ], + ], + ]; } /** @@ -107,37 +107,37 @@ class FileItem extends EntityReferenceItem { * {@inheritdoc} */ public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) { - $element = array(); + $element = []; $element['#attached']['library'][] = 'file/drupal.file'; - $element['display_field'] = array( + $element['display_field'] = [ '#type' => 'checkbox', '#title' => t('Enable <em>Display</em> field'), '#default_value' => $this->getSetting('display_field'), '#description' => t('The display option allows users to choose if a file should be shown when viewing the content.'), - ); - $element['display_default'] = array( + ]; + $element['display_default'] = [ '#type' => 'checkbox', '#title' => t('Files displayed by default'), '#default_value' => $this->getSetting('display_default'), '#description' => t('This setting only has an effect if the display option is enabled.'), - '#states' => array( - 'visible' => array( - ':input[name="settings[display_field]"]' => array('checked' => TRUE), - ), - ), - ); + '#states' => [ + 'visible' => [ + ':input[name="settings[display_field]"]' => ['checked' => TRUE], + ], + ], + ]; $scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE); - $element['uri_scheme'] = array( + $element['uri_scheme'] = [ '#type' => 'radios', '#title' => t('Upload destination'), '#options' => $scheme_options, '#default_value' => $this->getSetting('uri_scheme'), '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'), '#disabled' => $has_data, - ); + ]; return $element; } @@ -146,50 +146,50 @@ class FileItem extends EntityReferenceItem { * {@inheritdoc} */ public function fieldSettingsForm(array $form, FormStateInterface $form_state) { - $element = array(); + $element = []; $settings = $this->getSettings(); - $element['file_directory'] = array( + $element['file_directory'] = [ '#type' => 'textfield', '#title' => t('File directory'), '#default_value' => $settings['file_directory'], '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'), - '#element_validate' => array(array(get_class($this), 'validateDirectory')), + '#element_validate' => [[get_class($this), 'validateDirectory']], '#weight' => 3, - ); + ]; // Make the extension list a little more human-friendly by comma-separation. $extensions = str_replace(' ', ', ', $settings['file_extensions']); - $element['file_extensions'] = array( + $element['file_extensions'] = [ '#type' => 'textfield', '#title' => t('Allowed file extensions'), '#default_value' => $extensions, '#description' => t('Separate extensions with a space or comma and do not include the leading dot.'), - '#element_validate' => array(array(get_class($this), 'validateExtensions')), + '#element_validate' => [[get_class($this), 'validateExtensions']], '#weight' => 1, '#maxlength' => 256, // By making this field required, we prevent a potential security issue // that would allow files of any type to be uploaded. '#required' => TRUE, - ); + ]; - $element['max_filesize'] = array( + $element['max_filesize'] = [ '#type' => 'textfield', '#title' => t('Maximum upload size'), '#default_value' => $settings['max_filesize'], - '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))), + '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', ['%limit' => format_size(file_upload_max_size())]), '#size' => 10, - '#element_validate' => array(array(get_class($this), 'validateMaxFilesize')), + '#element_validate' => [[get_class($this), 'validateMaxFilesize']], '#weight' => 5, - ); + ]; - $element['description_field'] = array( + $element['description_field'] = [ '#type' => 'checkbox', '#title' => t('Enable <em>Description</em> field'), '#default_value' => isset($settings['description_field']) ? $settings['description_field'] : '', '#description' => t('The description field allows users to enter a description about the uploaded file.'), '#weight' => 11, - ); + ]; return $element; } @@ -245,7 +245,7 @@ class FileItem extends EntityReferenceItem { */ public static function validateMaxFilesize($element, FormStateInterface $form_state) { if (!empty($element['#value']) && !is_numeric(Bytes::toInt($element['#value']))) { - $form_state->setError($element, t('The "@name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('@name' => $element['title']))); + $form_state->setError($element, t('The "@name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', ['@name' => $element['title']])); } } @@ -261,7 +261,7 @@ class FileItem extends EntityReferenceItem { * * @see \Drupal\Core\Utility\Token::replace() */ - public function getUploadLocation($data = array()) { + public function getUploadLocation($data = []) { return static::doGetUploadLocation($this->getSettings(), $data); } @@ -296,7 +296,7 @@ class FileItem extends EntityReferenceItem { * element's '#upload_validators' property. */ public function getUploadValidators() { - $validators = array(); + $validators = []; $settings = $this->getSettings(); // Cap the upload size according to the PHP limit. @@ -306,11 +306,11 @@ class FileItem extends EntityReferenceItem { } // There is always a file size limit due to the PHP server limit. - $validators['file_validate_size'] = array($max_filesize); + $validators['file_validate_size'] = [$max_filesize]; // Add the extension check if necessary. if (!empty($settings['file_extensions'])) { - $validators['file_validate_extensions'] = array($settings['file_extensions']); + $validators['file_validate_extensions'] = [$settings['file_extensions']]; } return $validators; @@ -331,11 +331,11 @@ class FileItem extends EntityReferenceItem { $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt'; $data = $random->paragraphs(3); $file = file_save_data($data, $destination, FILE_EXISTS_ERROR); - $values = array( + $values = [ 'target_id' => $file->id(), 'display' => (int)$settings['display_default'], 'description' => $random->sentences(10), - ); + ]; return $values; } diff --git a/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php b/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php index 9a9dfe220f0..587a396fc60 100644 --- a/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php +++ b/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php @@ -48,27 +48,27 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'progress_indicator' => 'throbber', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $element['progress_indicator'] = array( + $element['progress_indicator'] = [ '#type' => 'radios', '#title' => t('Progress indicator'), - '#options' => array( + '#options' => [ 'throbber' => t('Throbber'), 'bar' => t('Bar with progress meter'), - ), + ], '#default_value' => $this->getSetting('progress_indicator'), '#description' => t('The throbber display does not show the status of uploads but takes up less space. The progress bar is helpful for monitoring progress on large uploads.'), '#weight' => 16, '#access' => file_progress_implementation(), - ); + ]; return $element; } @@ -76,8 +76,8 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { * {@inheritdoc} */ public function settingsSummary() { - $summary = array(); - $summary[] = t('Progress indicator: @progress_indicator', array('@progress_indicator' => $this->getSetting('progress_indicator'))); + $summary = []; + $summary[] = t('Progress indicator: @progress_indicator', ['@progress_indicator' => $this->getSetting('progress_indicator')]); return $summary; } @@ -115,15 +115,15 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { $title = $this->fieldDefinition->getLabel(); $description = $this->getFilteredDescription(); - $elements = array(); + $elements = []; $delta = 0; // Add an element for every existing item. foreach ($items as $item) { - $element = array( + $element = [ '#title' => $title, '#description' => $description, - ); + ]; $element = $this->formSingleElement($items, $delta, $element, $form, $form_state); if ($element) { @@ -131,15 +131,15 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { if ($is_multiple) { // We name the element '_weight' to avoid clashing with elements // defined by widget. - $element['_weight'] = array( + $element['_weight'] = [ '#type' => 'weight', - '#title' => t('Weight for row @number', array('@number' => $delta + 1)), + '#title' => t('Weight for row @number', ['@number' => $delta + 1]), '#title_display' => 'invisible', // Note: this 'delta' is the FAPI #type 'weight' element's property. '#delta' => $max, '#default_value' => $item->_weight ?: $delta, '#weight' => 100, - ); + ]; } $elements[$delta] = $element; @@ -155,10 +155,10 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { if ($empty_single_allowed || $empty_multiple_allowed) { // Create a new empty item. $items->appendItem(); - $element = array( + $element = [ '#title' => $title, '#description' => $description, - ); + ]; $element = $this->formSingleElement($items, $delta, $element, $form, $form_state); if ($element) { $element['#required'] = ($element['#required'] && $delta == 0); @@ -173,8 +173,8 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { $elements['#type'] = 'details'; $elements['#open'] = TRUE; $elements['#theme'] = 'file_widget_multiple'; - $elements['#theme_wrappers'] = array('details'); - $elements['#process'] = array(array(get_class($this), 'processMultiple')); + $elements['#theme_wrappers'] = ['details']; + $elements['#process'] = [[get_class($this), 'processMultiple']]; $elements['#title'] = $title; $elements['#description'] = $description; @@ -183,19 +183,19 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // The field settings include defaults for the field type. However, this // widget is a base class for other widgets (e.g., ImageWidget) that may // act on field types without these expected settings. - $field_settings = $this->getFieldSettings() + array('display_field' => NULL); + $field_settings = $this->getFieldSettings() + ['display_field' => NULL]; $elements['#display_field'] = (bool) $field_settings['display_field']; // Add some properties that will eventually be added to the file upload // field. These are added here so that they may be referenced easily // through a hook_form_alter(). $elements['#file_upload_title'] = t('Add a new file'); - $elements['#file_upload_description'] = array( + $elements['#file_upload_description'] = [ '#theme' => 'file_upload_help', '#description' => '', '#upload_validators' => $elements[0]['#upload_validators'], '#cardinality' => $cardinality, - ); + ]; } return $elements; @@ -210,28 +210,28 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // The field settings include defaults for the field type. However, this // widget is a base class for other widgets (e.g., ImageWidget) that may act // on field types without these expected settings. - $field_settings += array( + $field_settings += [ 'display_default' => NULL, 'display_field' => NULL, 'description_field' => NULL, - ); + ]; $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality(); - $defaults = array( - 'fids' => array(), + $defaults = [ + 'fids' => [], 'display' => (bool) $field_settings['display_default'], 'description' => '', - ); + ]; // Essentially we use the managed_file type, extended with some // enhancements. $element_info = $this->elementInfo->getInfo('managed_file'); - $element += array( + $element += [ '#type' => 'managed_file', '#upload_location' => $items[$delta]->getUploadLocation(), '#upload_validators' => $items[$delta]->getUploadValidators(), - '#value_callback' => array(get_class($this), 'value'), - '#process' => array_merge($element_info['#process'], array(array(get_class($this), 'process'))), + '#value_callback' => [get_class($this), 'value'], + '#process' => array_merge($element_info['#process'], [[get_class($this), 'process']]), '#progress_indicator' => $this->getSetting('progress_indicator'), // Allows this field to return an array instead of a single value. '#extended' => TRUE, @@ -242,29 +242,29 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { '#display_default' => $field_settings['display_default'], '#description_field' => $field_settings['description_field'], '#cardinality' => $cardinality, - ); + ]; $element['#weight'] = $delta; // Field stores FID value in a single mode, so we need to transform it for // form element to recognize it correctly. if (!isset($items[$delta]->fids) && isset($items[$delta]->target_id)) { - $items[$delta]->fids = array($items[$delta]->target_id); + $items[$delta]->fids = [$items[$delta]->target_id]; } $element['#default_value'] = $items[$delta]->getValue() + $defaults; $default_fids = $element['#extended'] ? $element['#default_value']['fids'] : $element['#default_value']; if (empty($default_fids)) { - $file_upload_help = array( + $file_upload_help = [ '#theme' => 'file_upload_help', '#description' => $element['#description'], '#upload_validators' => $element['#upload_validators'], '#cardinality' => $cardinality, - ); + ]; $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help); $element['#multiple'] = $cardinality != 1 ? TRUE : FALSE; if ($cardinality != 1 && $cardinality != -1) { - $element['#element_validate'] = array(array(get_class($this), 'validateMultipleCount')); + $element['#element_validate'] = [[get_class($this), 'validateMultipleCount']]; } } @@ -278,7 +278,7 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // Since file upload widget now supports uploads of more than one file at a // time it always returns an array of fids. We have to translate this to a // single fid, as field expects single value. - $new_values = array(); + $new_values = []; foreach ($values as &$value) { foreach ($value['fids'] as $fid) { $new_value = $value; @@ -324,11 +324,11 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { $return = ManagedFile::valueCallback($element, $input, $form_state); // Ensure that all the required properties are returned even if empty. - $return += array( - 'fids' => array(), + $return += [ + 'fids' => [], 'display' => 1, 'description' => '', - ); + ]; return $return; } @@ -353,7 +353,7 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { if ($total_uploaded_count > $field_storage->getCardinality()) { $keep = $newly_uploaded_count - $total_uploaded_count + $field_storage->getCardinality(); $removed_files = array_slice($values['fids'], $keep); - $removed_names = array(); + $removed_names = []; foreach ($removed_files as $fid) { $file = File::load($fid); $removed_names[] = $file->getFilename(); @@ -385,11 +385,11 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // Add the display field if enabled. if ($element['#display_field']) { - $element['display'] = array( + $element['display'] = [ '#type' => empty($item['fids']) ? 'hidden' : 'checkbox', '#title' => t('Include file in display'), - '#attributes' => array('class' => array('file-display')), - ); + '#attributes' => ['class' => ['file-display']], + ]; if (isset($item['display'])) { $element['display']['#value'] = $item['display'] ? '1' : ''; } @@ -398,33 +398,33 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { } } else { - $element['display'] = array( + $element['display'] = [ '#type' => 'hidden', '#value' => '1', - ); + ]; } // Add the description field if enabled. if ($element['#description_field'] && $item['fids']) { $config = \Drupal::config('file.settings'); - $element['description'] = array( + $element['description'] = [ '#type' => $config->get('description.type'), '#title' => t('Description'), '#value' => isset($item['description']) ? $item['description'] : '', '#maxlength' => $config->get('description.length'), '#description' => t('The description may be used as the label of the link to the file.'), - ); + ]; } // Adjust the Ajax settings so that on upload and remove of any individual // file, the entire group of file fields is updated together. if ($element['#cardinality'] != 1) { $parents = array_slice($element['#array_parents'], 0, -1); - $new_options = array( - 'query' => array( + $new_options = [ + 'query' => [ 'element_parents' => implode('/', $parents), - ), - ); + ], + ]; $field_element = NestedArray::getValue($form, $parents); $new_wrapper = $field_element['#id'] . '-ajax-wrapper'; foreach (Element::children($element) as $key) { @@ -440,9 +440,9 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // functionality needed by the field widget. This submit handler, along with // the rebuild logic in file_field_widget_form() requires the entire field, // not just the individual item, to be valid. - foreach (array('upload_button', 'remove_button') as $key) { - $element[$key]['#submit'][] = array(get_called_class(), 'submit'); - $element[$key]['#limit_validation_errors'] = array(array_slice($element['#parents'], 0, -1)); + foreach (['upload_button', 'remove_button'] as $key) { + $element[$key]['#submit'][] = [get_called_class(), 'submit']; + $element[$key]['#limit_validation_errors'] = [array_slice($element['#parents'], 0, -1)]; } return $element; @@ -477,22 +477,22 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { foreach ($element_children as $delta => $key) { if ($key != $element['#file_upload_delta']) { $description = static::getDescriptionFromElement($element[$key]); - $element[$key]['_weight'] = array( + $element[$key]['_weight'] = [ '#type' => 'weight', - '#title' => $description ? t('Weight for @title', array('@title' => $description)) : t('Weight for new file'), + '#title' => $description ? t('Weight for @title', ['@title' => $description]) : t('Weight for new file'), '#title_display' => 'invisible', '#delta' => $count, '#default_value' => $delta, - ); + ]; } else { // The title needs to be assigned to the upload field so that validation // errors include the correct widget label. $element[$key]['#title'] = $element['#title']; - $element[$key]['_weight'] = array( + $element[$key]['_weight'] = [ '#type' => 'hidden', '#default_value' => $delta, - ); + ]; } } @@ -559,12 +559,12 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { // If there are more files uploaded via the same widget, we have to separate // them, as we display each file in its own widget. - $new_values = array(); + $new_values = []; foreach ($submitted_values as $delta => $submitted_value) { if (is_array($submitted_value['fids'])) { foreach ($submitted_value['fids'] as $fid) { $new_value = $submitted_value; - $new_value['fids'] = array($fid); + $new_value['fids'] = [$fid]; $new_values[] = $new_value; } } diff --git a/core/modules/file/src/Plugin/migrate/cckfield/d7/ImageField.php b/core/modules/file/src/Plugin/migrate/cckfield/d7/ImageField.php index 7f47caa96e0..ad24ae24f1e 100644 --- a/core/modules/file/src/Plugin/migrate/cckfield/d7/ImageField.php +++ b/core/modules/file/src/Plugin/migrate/cckfield/d7/ImageField.php @@ -17,7 +17,7 @@ class ImageField extends CckFieldPluginBase { * {@inheritdoc} */ public function getFieldFormatterMap() { - return array(); + return []; } /** diff --git a/core/modules/file/src/Plugin/migrate/source/d6/File.php b/core/modules/file/src/Plugin/migrate/source/d6/File.php index 13aee57bf67..0564b6b7886 100644 --- a/core/modules/file/src/Plugin/migrate/source/d6/File.php +++ b/core/modules/file/src/Plugin/migrate/source/d6/File.php @@ -75,7 +75,7 @@ class File extends DrupalSqlBase { * {@inheritdoc} */ public function fields() { - return array( + return [ 'fid' => $this->t('File ID'), 'uid' => $this->t('The {users}.uid who added the file. If set to 0, this file was added by an anonymous user.'), 'filename' => $this->t('File name'), @@ -85,7 +85,7 @@ class File extends DrupalSqlBase { 'timestamp' => $this->t('The time that the file was added.'), 'file_directory_path' => $this->t('The Drupal files path.'), 'is_public' => $this->t('TRUE if the files directory is public otherwise FALSE.'), - ); + ]; } /** * {@inheritdoc} diff --git a/core/modules/file/src/Plugin/migrate/source/d6/Upload.php b/core/modules/file/src/Plugin/migrate/source/d6/Upload.php index 5b7c3ae7402..4e07a236b5f 100644 --- a/core/modules/file/src/Plugin/migrate/source/d6/Upload.php +++ b/core/modules/file/src/Plugin/migrate/source/d6/Upload.php @@ -26,7 +26,7 @@ class Upload extends DrupalSqlBase { public function query() { $query = $this->select('upload', 'u') ->distinct() - ->fields('u', array('nid', 'vid')); + ->fields('u', ['nid', 'vid']); $query->innerJoin('node', 'n', static::JOIN); $query->addField('n', 'type'); return $query; @@ -37,7 +37,7 @@ class Upload extends DrupalSqlBase { */ public function prepareRow(Row $row) { $query = $this->select('upload', 'u') - ->fields('u', array('fid', 'description', 'list')) + ->fields('u', ['fid', 'description', 'list']) ->condition('u.nid', $row->getSourceProperty('nid')) ->orderBy('u.weight'); $query->innerJoin('node', 'n', static::JOIN); @@ -49,7 +49,7 @@ class Upload extends DrupalSqlBase { * {@inheritdoc} */ public function fields() { - return array( + return [ 'fid' => $this->t('The file Id.'), 'nid' => $this->t('The node Id.'), 'vid' => $this->t('The version Id.'), @@ -57,7 +57,7 @@ class Upload extends DrupalSqlBase { 'description' => $this->t('The file description.'), 'list' => $this->t('Whether the list should be visible on the node page.'), 'weight' => $this->t('The file weight.'), - ); + ]; } /** diff --git a/core/modules/file/src/Plugin/migrate/source/d6/UploadInstance.php b/core/modules/file/src/Plugin/migrate/source/d6/UploadInstance.php index c20ac03eb93..c1b3345d761 100644 --- a/core/modules/file/src/Plugin/migrate/source/d6/UploadInstance.php +++ b/core/modules/file/src/Plugin/migrate/source/d6/UploadInstance.php @@ -30,7 +30,7 @@ class UploadInstance extends DrupalSqlBase { $max_filesize = $this->variableGet('upload_uploadsize_default', 1); $max_filesize = $max_filesize ? $max_filesize . 'MB' : ''; $file_extensions = $this->variableGet('upload_extensions_default', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'); - $return = array(); + $return = []; $values = $this->select('variable', 'v') ->fields('v', ['name', 'value']) ->condition('v.name', $variables, 'IN') @@ -55,22 +55,22 @@ class UploadInstance extends DrupalSqlBase { * {@inheritdoc} */ public function getIds() { - return array( - 'node_type' => array( + return [ + 'node_type' => [ 'type' => 'string', - ), - ); + ], + ]; } /** * {@inheritdoc} */ public function fields() { - return array( + return [ 'node_type' => $this->t('Node type'), 'max_filesize' => $this->t('Max filesize'), 'file_extensions' => $this->t('File extensions'), - ); + ]; } /** diff --git a/core/modules/file/src/Plugin/migrate/source/d7/File.php b/core/modules/file/src/Plugin/migrate/source/d7/File.php index 247a6cf0480..e418f825bb8 100644 --- a/core/modules/file/src/Plugin/migrate/source/d7/File.php +++ b/core/modules/file/src/Plugin/migrate/source/d7/File.php @@ -46,7 +46,7 @@ class File extends DrupalSqlBase { // Filter by scheme(s), if configured. if (isset($this->configuration['scheme'])) { - $schemes = array(); + $schemes = []; // Accept either a single scheme, or a list. foreach ((array) $this->configuration['scheme'] as $scheme) { $schemes[] = rtrim($scheme) . '://'; @@ -93,7 +93,7 @@ class File extends DrupalSqlBase { * {@inheritdoc} */ public function fields() { - return array( + return [ 'fid' => $this->t('File ID'), 'uid' => $this->t('The {users}.uid who added the file. If set to 0, this file was added by an anonymous user.'), 'filename' => $this->t('File name'), @@ -101,7 +101,7 @@ class File extends DrupalSqlBase { 'filemime' => $this->t('File MIME Type'), 'status' => $this->t('The published status of a file.'), 'timestamp' => $this->t('The time that the file was added.'), - ); + ]; } /** diff --git a/core/modules/file/src/Plugin/views/argument/Fid.php b/core/modules/file/src/Plugin/views/argument/Fid.php index 832e85dad57..1654fcc2e3e 100644 --- a/core/modules/file/src/Plugin/views/argument/Fid.php +++ b/core/modules/file/src/Plugin/views/argument/Fid.php @@ -61,7 +61,7 @@ class Fid extends NumericArgument implements ContainerFactoryPluginInterface { ->condition('fid', $this->value, 'IN') ->execute(); $files = $storage->loadMultiple($fids); - $titles = array(); + $titles = []; foreach ($files as $file) { $titles[] = $file->getFilename(); } diff --git a/core/modules/file/src/Plugin/views/field/File.php b/core/modules/file/src/Plugin/views/field/File.php index 18bc1fc312a..57d8c60acca 100644 --- a/core/modules/file/src/Plugin/views/field/File.php +++ b/core/modules/file/src/Plugin/views/field/File.php @@ -33,7 +33,7 @@ class File extends FieldPluginBase { */ protected function defineOptions() { $options = parent::defineOptions(); - $options['link_to_file'] = array('default' => FALSE); + $options['link_to_file'] = ['default' => FALSE]; return $options; } @@ -41,12 +41,12 @@ class File extends FieldPluginBase { * Provide link to file option */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { - $form['link_to_file'] = array( + $form['link_to_file'] = [ '#title' => $this->t('Link this field to download the file'), '#description' => $this->t("Enable to override this field's links."), '#type' => 'checkbox', '#default_value' => !empty($this->options['link_to_file']), - ); + ]; parent::buildOptionsForm($form, $form_state); } diff --git a/core/modules/file/src/Tests/DownloadTest.php b/core/modules/file/src/Tests/DownloadTest.php index e92cef3f2fc..bb871d4fb1c 100644 --- a/core/modules/file/src/Tests/DownloadTest.php +++ b/core/modules/file/src/Tests/DownloadTest.php @@ -63,7 +63,7 @@ class DownloadTest extends FileManagedTestBase { $url = file_create_url($file->getFileUri()); // Set file_test access header to allow the download. - file_test_set_return('download', array('x-foo' => 'Bar')); + file_test_set_return('download', ['x-foo' => 'Bar']); $this->drupalGet($url); $this->assertEqual($this->drupalGetHeader('x-foo'), 'Bar', 'Found header set by file_test module on private download.'); $this->assertFalse($this->drupalGetHeader('x-drupal-cache'), 'Page cache is disabled on private file download.'); @@ -102,10 +102,10 @@ class DownloadTest extends FileManagedTestBase { // routed through Drupal, whereas private files should be served by Drupal, // so they need to be. The difference is most apparent when $script_path // is not empty (i.e., when not using clean URLs). - $clean_url_settings = array( + $clean_url_settings = [ 'clean' => '', 'unclean' => 'index.php/', - ); + ]; $public_directory_path = \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath(); foreach ($clean_url_settings as $clean_url_setting => $script_path) { $clean_urls = $clean_url_setting == 'clean'; @@ -158,7 +158,7 @@ class DownloadTest extends FileManagedTestBase { if ($scheme == 'private') { // Tell the implementation of hook_file_download() in file_test.module // that this file may be downloaded. - file_test_set_return('download', array('x-foo' => 'Bar')); + file_test_set_return('download', ['x-foo' => 'Bar']); } $this->drupalGet($url); diff --git a/core/modules/file/src/Tests/FileFieldAnonymousSubmissionTest.php b/core/modules/file/src/Tests/FileFieldAnonymousSubmissionTest.php index 2286473c038..b59b1bafd33 100644 --- a/core/modules/file/src/Tests/FileFieldAnonymousSubmissionTest.php +++ b/core/modules/file/src/Tests/FileFieldAnonymousSubmissionTest.php @@ -19,10 +19,10 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { protected function setUp() { parent::setUp(); // Set up permissions for anonymous attacker user. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'create article content' => TRUE, 'access content' => TRUE, - )); + ]); } /** @@ -36,17 +36,17 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { $this->drupalLogout(); $this->drupalGet('node/add/article'); $this->assertResponse(200, 'Loaded the article node form.'); - $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label)))); + $this->assertText(strip_tags(t('Create @name', ['@name' => $bundle_label]))); - $edit = array( + $edit = [ 'title[0][value]' => $node_title, 'body[0][value]' => 'Test article', - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertResponse(200); - $t_args = array('@type' => $bundle_label, '%title' => $node_title); + $t_args = ['@type' => $bundle_label, '%title' => $node_title]; $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.'); - $matches = array(); + $matches = []; if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) { $nid = end($matches); $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.'); @@ -61,28 +61,28 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { public function testAnonymousNodeWithFile() { $bundle_label = 'Article'; $node_title = 'Test page'; - $this->createFileField('field_image', 'node', 'article', array(), array('file_extensions' => 'txt png')); + $this->createFileField('field_image', 'node', 'article', [], ['file_extensions' => 'txt png']); // Load the node form. $this->drupalLogout(); $this->drupalGet('node/add/article'); $this->assertResponse(200, 'Loaded the article node form.'); - $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label)))); + $this->assertText(strip_tags(t('Create @name', ['@name' => $bundle_label]))); // Generate an image file. $image = $this->getTestFile('image'); // Submit the form. - $edit = array( + $edit = [ 'title[0][value]' => $node_title, 'body[0][value]' => 'Test article', 'files[field_image_0]' => $this->container->get('file_system')->realpath($image->getFileUri()), - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertResponse(200); - $t_args = array('@type' => $bundle_label, '%title' => $node_title); + $t_args = ['@type' => $bundle_label, '%title' => $node_title]; $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.'); - $matches = array(); + $matches = []; if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) { $nid = end($matches); $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.'); @@ -104,11 +104,11 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { * Tests file submission for an authenticated user with a missing node title. */ public function testAuthenticatedNodeWithFileWithoutTitle() { - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'bypass node access', 'access content overview', 'administer nodes', - )); + ]); $this->drupalLogin($admin_user); $this->doTestNodeWithFileWithoutTitle(); } @@ -119,21 +119,21 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { protected function doTestNodeWithFileWithoutTitle() { $bundle_label = 'Article'; $node_title = 'Test page'; - $this->createFileField('field_image', 'node', 'article', array(), array('file_extensions' => 'txt png')); + $this->createFileField('field_image', 'node', 'article', [], ['file_extensions' => 'txt png']); // Load the node form. $this->drupalGet('node/add/article'); $this->assertResponse(200, 'Loaded the article node form.'); - $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label)))); + $this->assertText(strip_tags(t('Create @name', ['@name' => $bundle_label]))); // Generate an image file. $image = $this->getTestFile('image'); // Submit the form but exclude the title field. - $edit = array( + $edit = [ 'body[0][value]' => 'Test article', 'files[field_image_0]' => $this->container->get('file_system')->realpath($image->getFileUri()), - ); + ]; if (!$this->loggedInUser) { $label = 'Save'; } @@ -142,21 +142,21 @@ class FileFieldAnonymousSubmissionTest extends FileFieldTestBase { } $this->drupalPostForm(NULL, $edit, $label); $this->assertResponse(200); - $t_args = array('@type' => $bundle_label, '%title' => $node_title); + $t_args = ['@type' => $bundle_label, '%title' => $node_title]; $this->assertNoText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.'); $this->assertText('Title field is required.'); // Submit the form again but this time with the missing title field. This // should still work. - $edit = array( + $edit = [ 'title[0][value]' => $node_title, - ); + ]; $this->drupalPostForm(NULL, $edit, $label); // Confirm the final submission actually worked. - $t_args = array('@type' => $bundle_label, '%title' => $node_title); + $t_args = ['@type' => $bundle_label, '%title' => $node_title]; $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.'); - $matches = array(); + $matches = []; if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) { $nid = end($matches); $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.'); diff --git a/core/modules/file/src/Tests/FileFieldDisplayTest.php b/core/modules/file/src/Tests/FileFieldDisplayTest.php index b25b5142bc6..f78cd7d6960 100644 --- a/core/modules/file/src/Tests/FileFieldDisplayTest.php +++ b/core/modules/file/src/Tests/FileFieldDisplayTest.php @@ -18,23 +18,23 @@ class FileFieldDisplayTest extends FileFieldTestBase { function testNodeDisplay() { $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; - $field_storage_settings = array( + $field_storage_settings = [ 'display_field' => '1', 'display_default' => '1', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, - ); - $field_settings = array( + ]; + $field_settings = [ 'description_field' => '1', - ); - $widget_settings = array(); + ]; + $widget_settings = []; $this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings); // Create a new node *without* the file field set, and check that the field // is not shown for each node display. - $node = $this->drupalCreateNode(array('type' => $type_name)); + $node = $this->drupalCreateNode(['type' => $type_name]); // Check file_default last as the assertions below assume that this is the // case. - $file_formatters = array('file_table', 'file_url_plain', 'hidden', 'file_default'); + $file_formatters = ['file_table', 'file_url_plain', 'hidden', 'file_default']; foreach ($file_formatters as $formatter) { if ($formatter === 'hidden') { $edit = [ @@ -49,7 +49,7 @@ class FileFieldDisplayTest extends FileFieldTestBase { } $this->drupalPostForm("admin/structure/types/manage/$type_name/display", $edit, t('Save')); $this->drupalGet('node/' . $node->id()); - $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter))); + $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', ['%formatter' => $formatter])); } $test_file = $this->getTestFile('text'); @@ -65,28 +65,28 @@ class FileFieldDisplayTest extends FileFieldTestBase { // Check that the default formatter is displaying with the file name. $node_storage = $this->container->get('entity.manager')->getStorage('node'); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); - $file_link = array( + $file_link = [ '#theme' => 'file_link', '#file' => $node_file, - ); + ]; $default_output = \Drupal::service('renderer')->renderRoot($file_link); $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.'); // Turn the "display" option off and check that the file is no longer displayed. - $edit = array($field_name . '[0][display]' => FALSE); + $edit = [$field_name . '[0][display]' => FALSE]; $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published')); $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.'); // Add a description and make sure that it is displayed. $description = $this->randomMachineName(); - $edit = array( + $edit = [ $field_name . '[0][description]' => $description, $field_name . '[0][display]' => TRUE, - ); + ]; $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published')); $this->assertText($description); @@ -113,15 +113,15 @@ class FileFieldDisplayTest extends FileFieldTestBase { function testDefaultFileFieldDisplay() { $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; - $field_storage_settings = array( + $field_storage_settings = [ 'display_field' => '1', 'display_default' => '0', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, - ); - $field_settings = array( + ]; + $field_settings = [ 'description_field' => '1', - ); - $widget_settings = array(); + ]; + $widget_settings = []; $this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings); $test_file = $this->getTestFile('text'); @@ -142,31 +142,31 @@ class FileFieldDisplayTest extends FileFieldTestBase { $field_type = 'file'; $field_name = strtolower($this->randomMachineName()); // Use the UI to add a new content type that also contains a file field. - $edit = array( + $edit = [ 'name' => $type_name, 'type' => $type_name, - ); + ]; $this->drupalPostForm('admin/structure/types/add', $edit, t('Save and manage fields')); - $edit = array( + $edit = [ 'new_storage_type' => $field_type, 'field_name' => $field_name, 'label' => $this->randomString(), - ); + ]; $this->drupalPostForm('/admin/structure/types/manage/' . $type_name . '/fields/add-field', $edit, t('Save and continue')); - $this->drupalPostForm(NULL, array(), t('Save field settings')); + $this->drupalPostForm(NULL, [], t('Save field settings')); // Ensure the description field is selected on the field instance settings // form. That's what this test is all about. - $edit = array( + $edit = [ 'settings[description_field]' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save settings')); // Add a node of our new type and upload a file to it. $file = current($this->drupalGetTestFiles('text')); $title = $this->randomString(); - $edit = array( + $edit = [ 'title[0][value]' => $title, 'files[field_' . $field_name . '_0]' => drupal_realpath($file->uri), - ); + ]; $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); $node = $this->drupalGetNodeByTitle($title); $this->drupalGet('node/' . $node->id() . '/edit'); diff --git a/core/modules/file/src/Tests/FileFieldPathTest.php b/core/modules/file/src/Tests/FileFieldPathTest.php index c9a15de812a..f2498b52ff2 100644 --- a/core/modules/file/src/Tests/FileFieldPathTest.php +++ b/core/modules/file/src/Tests/FileFieldPathTest.php @@ -26,7 +26,7 @@ class FileFieldPathTest extends FileFieldTestBase { $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded to the correct location. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); /** @var \Drupal\file\FileInterface $node_file */ $node_file = $node->{$field_name}->entity; @@ -36,36 +36,36 @@ class FileFieldPathTest extends FileFieldTestBase { $date_formatter->format(REQUEST_TIME, 'custom', 'Y') . '-' . $date_formatter->format(REQUEST_TIME, 'custom', 'm') . '/' . $test_file->getFilename(); - $this->assertPathMatch($expected_filename, $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); + $this->assertPathMatch($expected_filename, $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', ['%file' => $node_file->getFileUri()])); // Change the path to contain multiple subdirectories. - $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz')); + $this->updateFileField($field_name, $type_name, ['file_directory' => 'foo/bar/baz']); // Upload a new file into the subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); - $this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); + $this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', ['%file' => $node_file->getFileUri()])); // Check the path when used with tokens. // Change the path to contain multiple token directories. - $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]')); + $this->updateFileField($field_name, $type_name, ['file_directory' => '[current-user:uid]/[current-user:name]']); // Upload a new file into the token subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); // Do token replacement using the same user which uploaded the file, not // the user running the test case. - $data = array('user' => $this->adminUser); + $data = ['user' => $this->adminUser]; $subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data); - $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->getFileUri()))); + $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', ['%file' => $node_file->getFileUri()])); } /** diff --git a/core/modules/file/src/Tests/FileFieldRSSContentTest.php b/core/modules/file/src/Tests/FileFieldRSSContentTest.php index 4e18e715515..e16e82e6918 100644 --- a/core/modules/file/src/Tests/FileFieldRSSContentTest.php +++ b/core/modules/file/src/Tests/FileFieldRSSContentTest.php @@ -16,7 +16,7 @@ class FileFieldRSSContentTest extends FileFieldTestBase { * * @var array */ - public static $modules = array('node', 'views'); + public static $modules = ['node', 'views']; /** * Tests RSS enclosure formatter display for RSS feeds. @@ -30,29 +30,29 @@ class FileFieldRSSContentTest extends FileFieldTestBase { // RSS display must be added manually. $this->drupalGet("admin/structure/types/manage/$type_name/display"); - $edit = array( + $edit = [ "display_modes_custom[rss]" => '1', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); // Change the format to 'RSS enclosure'. $this->drupalGet("admin/structure/types/manage/$type_name/display/rss"); - $edit = array( + $edit = [ "fields[$field_name][type]" => 'file_rss_enclosure', "fields[$field_name][region]" => 'content', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); // Create a new node with a file field set. Promote to frontpage // needs to be set so this node will appear in the RSS feed. - $node = $this->drupalCreateNode(array('type' => $type_name, 'promote' => 1)); + $node = $this->drupalCreateNode(['type' => $type_name, 'promote' => 1]); $test_file = $this->getTestFile('text'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $field_name, $node->id()); // Get the uploaded file from the node. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); @@ -61,7 +61,7 @@ class FileFieldRSSContentTest extends FileFieldTestBase { $uploaded_filename = str_replace('public://', '', $node_file->getFileUri()); $selector = sprintf( 'enclosure[url="%s"][length="%s"][type="%s"]', - file_create_url("public://$uploaded_filename", array('absolute' => TRUE)), + file_create_url("public://$uploaded_filename", ['absolute' => TRUE]), $node_file->getSize(), $node_file->getMimeType() ); diff --git a/core/modules/file/src/Tests/FileFieldRevisionTest.php b/core/modules/file/src/Tests/FileFieldRevisionTest.php index f5d00c7cb03..ef7904182f1 100644 --- a/core/modules/file/src/Tests/FileFieldRevisionTest.php +++ b/core/modules/file/src/Tests/FileFieldRevisionTest.php @@ -35,7 +35,7 @@ class FileFieldRevisionTest extends FileFieldTestBase { $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file exists on disk and in the database. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file_r1 = File::load($node->{$field_name}->target_id); $node_vid_r1 = $node->getRevisionId(); @@ -45,7 +45,7 @@ class FileFieldRevisionTest extends FileFieldTestBase { // Upload another file to the same node in a new revision. $this->replaceNodeFile($test_file, $field_name, $nid); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file_r2 = File::load($node->{$field_name}->target_id); $node_vid_r2 = $node->getRevisionId(); @@ -63,8 +63,8 @@ class FileFieldRevisionTest extends FileFieldTestBase { // Save a new version of the node without any changes. // Check that the file is still the same as the previous revision. - $this->drupalPostForm('node/' . $nid . '/edit', array('revision' => '1'), t('Save and keep published')); - $node_storage->resetCache(array($nid)); + $this->drupalPostForm('node/' . $nid . '/edit', ['revision' => '1'], t('Save and keep published')); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file_r3 = File::load($node->{$field_name}->target_id); $node_vid_r3 = $node->getRevisionId(); @@ -72,8 +72,8 @@ class FileFieldRevisionTest extends FileFieldTestBase { $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.'); // Revert to the first revision and check that the original file is active. - $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert')); - $node_storage->resetCache(array($nid)); + $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', [], t('Revert')); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file_r4 = File::load($node->{$field_name}->target_id); $this->assertEqual($node_file_r1->id(), $node_file_r4->id(), 'Original revision file still in place after reverting to the original revision.'); @@ -81,7 +81,7 @@ class FileFieldRevisionTest extends FileFieldTestBase { // Delete the second revision and check that the file is kept (since it is // still being used by the third revision). - $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete')); + $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', [], t('Delete')); $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.'); $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.'); $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.'); @@ -94,7 +94,7 @@ class FileFieldRevisionTest extends FileFieldTestBase { $this->drupalGet('user/' . $user->id() . '/edit'); // Delete the third revision and check that the file is not deleted yet. - $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete')); + $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', [], t('Delete')); $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.'); $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.'); $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.'); @@ -113,9 +113,9 @@ class FileFieldRevisionTest extends FileFieldTestBase { // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed') - ->fields(array( + ->fields([ 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), - )) + ]) ->condition('fid', $node_file_r3->id()) ->execute(); \Drupal::service('cron')->run(); @@ -124,14 +124,14 @@ class FileFieldRevisionTest extends FileFieldTestBase { $this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.'); // Delete the entire node and check that the original file is deleted. - $this->drupalPostForm('node/' . $nid . '/delete', array(), t('Delete')); + $this->drupalPostForm('node/' . $nid . '/delete', [], t('Delete')); // Call file_cron() to clean up the file. Make sure the changed timestamp // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed') - ->fields(array( + ->fields([ 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), - )) + ]) ->condition('fid', $node_file_r1->id()) ->execute(); \Drupal::service('cron')->run(); diff --git a/core/modules/file/src/Tests/FileFieldTestBase.php b/core/modules/file/src/Tests/FileFieldTestBase.php index 9ec9c753770..a9c96f3a72a 100644 --- a/core/modules/file/src/Tests/FileFieldTestBase.php +++ b/core/modules/file/src/Tests/FileFieldTestBase.php @@ -21,7 +21,7 @@ abstract class FileFieldTestBase extends WebTestBase { * * @var array */ - public static $modules = array('node', 'file', 'file_module_test', 'field_ui'); + public static $modules = ['node', 'file', 'file_module_test', 'field_ui']; /** * An user with administration permissions. @@ -32,9 +32,9 @@ abstract class FileFieldTestBase extends WebTestBase { protected function setUp() { parent::setUp(); - $this->adminUser = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access')); + $this->adminUser = $this->drupalCreateUser(['access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access']); $this->drupalLogin($this->adminUser); - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); } /** @@ -76,14 +76,14 @@ abstract class FileFieldTestBase extends WebTestBase { * @param array $widget_settings * A list of widget settings that will be added to the widget defaults. */ - function createFileField($name, $entity_type, $bundle, $storage_settings = array(), $field_settings = array(), $widget_settings = array()) { - $field_storage = FieldStorageConfig::create(array( + function createFileField($name, $entity_type, $bundle, $storage_settings = [], $field_settings = [], $widget_settings = []) { + $field_storage = FieldStorageConfig::create([ 'entity_type' => $entity_type, 'field_name' => $name, 'type' => 'file', 'settings' => $storage_settings, 'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1, - )); + ]); $field_storage->save(); $this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings); @@ -104,44 +104,44 @@ abstract class FileFieldTestBase extends WebTestBase { * @param array $widget_settings * A list of widget settings that will be added to the widget defaults. */ - function attachFileField($name, $entity_type, $bundle, $field_settings = array(), $widget_settings = array()) { - $field = array( + function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) { + $field = [ 'field_name' => $name, 'label' => $name, 'entity_type' => $entity_type, 'bundle' => $bundle, 'required' => !empty($field_settings['required']), 'settings' => $field_settings, - ); + ]; FieldConfig::create($field)->save(); entity_get_form_display($entity_type, $bundle, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'type' => 'file_generic', 'settings' => $widget_settings, - )) + ]) ->save(); // Assign display settings. entity_get_display($entity_type, $bundle, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'label' => 'hidden', 'type' => 'file_default', - )) + ]) ->save(); } /** * Updates an existing file field with new settings. */ - function updateFileField($name, $type_name, $field_settings = array(), $widget_settings = array()) { + function updateFileField($name, $type_name, $field_settings = [], $widget_settings = []) { $field = FieldConfig::loadByName('node', $type_name, $name); $field->setSettings(array_merge($field->getSettings(), $field_settings)); $field->save(); entity_get_form_display('node', $type_name, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'settings' => $widget_settings, - )) + ]) ->save(); } @@ -163,7 +163,7 @@ abstract class FileFieldTestBase extends WebTestBase { * @return int * The node id. */ - function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) { + function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) { return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras); } @@ -185,16 +185,16 @@ abstract class FileFieldTestBase extends WebTestBase { * @return int * The node id. */ - function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) { - $edit = array( + function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) { + $edit = [ 'title[0][value]' => $this->randomMachineName(), 'revision' => (string) (int) $new_revision, - ); + ]; $node_storage = $this->container->get('entity.manager')->getStorage('node'); if (is_numeric($nid_or_type)) { $nid = $nid_or_type; - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); } else { @@ -205,7 +205,7 @@ abstract class FileFieldTestBase extends WebTestBase { // Save at least one revision to better simulate a real site. $node->setNewRevision(); $node->save(); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.'); } @@ -238,11 +238,11 @@ abstract class FileFieldTestBase extends WebTestBase { * Note that if replacing a file, it must first be removed then added again. */ function removeNodeFile($nid, $new_revision = TRUE) { - $edit = array( + $edit = [ 'revision' => (string) (int) $new_revision, - ); + ]; - $this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove')); + $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove')); $this->drupalPostForm(NULL, $edit, t('Save and keep published')); } @@ -250,12 +250,12 @@ abstract class FileFieldTestBase extends WebTestBase { * Replaces a file within a node. */ function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) { - $edit = array( + $edit = [ 'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()), 'revision' => (string) (int) $new_revision, - ); + ]; - $this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove')); + $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove')); $this->drupalPostForm(NULL, $edit, t('Save and keep published')); } @@ -263,7 +263,7 @@ abstract class FileFieldTestBase extends WebTestBase { * Asserts that a file exists physically on disk. */ function assertFileExists($file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]); $this->assertTrue(is_file($file->getFileUri()), $message); } @@ -273,7 +273,7 @@ abstract class FileFieldTestBase extends WebTestBase { function assertFileEntryExists($file, $message = NULL) { $this->container->get('entity.manager')->getStorage('file')->resetCache(); $db_file = File::load($file->id()); - $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]); $this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message); } @@ -281,7 +281,7 @@ abstract class FileFieldTestBase extends WebTestBase { * Asserts that a file does not exist on disk. */ function assertFileNotExists($file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]); $this->assertFalse(is_file($file->getFileUri()), $message); } @@ -290,7 +290,7 @@ abstract class FileFieldTestBase extends WebTestBase { */ function assertFileEntryNotExists($file, $message) { $this->container->get('entity.manager')->getStorage('file')->resetCache(); - $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]); $this->assertFalse(File::load($file->id()), $message); } @@ -298,7 +298,7 @@ abstract class FileFieldTestBase extends WebTestBase { * Asserts that a file's status is set to permanent in the database. */ function assertFileIsPermanent(FileInterface $file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]); $this->assertTrue($file->isPermanent(), $message); } diff --git a/core/modules/file/src/Tests/FileFieldValidateTest.php b/core/modules/file/src/Tests/FileFieldValidateTest.php index 9d43060ccce..0f8b1f1de7f 100644 --- a/core/modules/file/src/Tests/FileFieldValidateTest.php +++ b/core/modules/file/src/Tests/FileFieldValidateTest.php @@ -21,22 +21,22 @@ class FileFieldValidateTest extends FileFieldTestBase { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); - $storage = $this->createFileField($field_name, 'node', $type_name, array(), array('required' => '1')); + $storage = $this->createFileField($field_name, 'node', $type_name, [], ['required' => '1']); $field = FieldConfig::loadByName('node', $type_name, $field_name); $test_file = $this->getTestFile('text'); // Try to post a new node without uploading a file. - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); - $this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required file field was empty.'); + $this->assertRaw(t('@title field is required.', ['@title' => $field->getLabel()]), 'Node save failed when required file field was empty.'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->getFileUri(), '@field_name' => $field_name, '@type_name' => $type_name))); + $this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', ['@test_file' => $test_file->getFileUri(), '@field_name' => $field_name, '@type_name' => $type_name])); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); @@ -45,17 +45,17 @@ class FileFieldValidateTest extends FileFieldTestBase { // Try again with a multiple value field. $storage->delete(); - $this->createFileField($field_name, 'node', $type_name, array('cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED), array('required' => '1')); + $this->createFileField($field_name, 'node', $type_name, ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED], ['required' => '1']); // Try to post a new node without uploading a file in the multivalue field. - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); - $this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required multiple value file field was empty.'); + $this->assertRaw(t('@title field is required.', ['@title' => $field->getLabel()]), 'Node save failed when required multiple value file field was empty.'); // Create a new node with the uploaded file into the multivalue field. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.'); @@ -69,46 +69,46 @@ class FileFieldValidateTest extends FileFieldTestBase { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); - $this->createFileField($field_name, 'node', $type_name, array(), array('required' => '1')); + $this->createFileField($field_name, 'node', $type_name, [], ['required' => '1']); $small_file = $this->getTestFile('text', 131072); // 128KB. $large_file = $this->getTestFile('text', 1310720); // 1.2MB // Test uploading both a large and small file with different increments. - $sizes = array( + $sizes = [ '1M' => 1048576, '1024K' => 1048576, '1048576' => 1048576, - ); + ]; foreach ($sizes as $max_filesize => $file_limit) { // Set the max file upload size. - $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize)); + $this->updateFileField($field_name, $type_name, ['max_filesize' => $max_filesize]); // Create a new node with the small file, which should pass. $nid = $this->uploadNodeFile($small_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); - $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize))); - $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize))); + $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', ['%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize])); + $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', ['%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize])); // Check that uploading the large file fails (1M limit). $this->uploadNodeFile($large_file, $field_name, $type_name); - $error_message = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($large_file->getSize()), '%maxsize' => format_size($file_limit))); - $this->assertRaw($error_message, format_string('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', array('%filesize' => format_size($large_file->getSize()), '%maxsize' => $max_filesize))); + $error_message = t('The file is %filesize exceeding the maximum file size of %maxsize.', ['%filesize' => format_size($large_file->getSize()), '%maxsize' => format_size($file_limit)]); + $this->assertRaw($error_message, format_string('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', ['%filesize' => format_size($large_file->getSize()), '%maxsize' => $max_filesize])); } // Turn off the max filesize. - $this->updateFileField($field_name, $type_name, array('max_filesize' => '')); + $this->updateFileField($field_name, $type_name, ['max_filesize' => '']); // Upload the big file successfully. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); - $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->getSize())))); - $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->getSize())))); + $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', ['%filesize' => format_size($large_file->getSize())])); + $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', ['%filesize' => format_size($large_file->getSize())])); } /** @@ -124,30 +124,30 @@ class FileFieldValidateTest extends FileFieldTestBase { list(, $test_file_extension) = explode('.', $test_file->getFilename()); // Disable extension checking. - $this->updateFileField($field_name, $type_name, array('file_extensions' => '')); + $this->updateFileField($field_name, $type_name, ['file_extensions' => '']); // Check that the file can be uploaded with no extension checking. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.'); $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.'); // Enable extension checking for text files. - $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt')); + $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']); // Check that the file with the wrong extension cannot be uploaded. $this->uploadNodeFile($test_file, $field_name, $type_name); - $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt')); + $error_message = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => 'txt']); $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.'); // Enable extension checking for text and image files. - $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension")); + $this->updateFileField($field_name, $type_name, ['file_extensions' => "txt $test_file_extension"]); // Check that the file can be uploaded with extension checking. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.'); @@ -166,18 +166,18 @@ class FileFieldValidateTest extends FileFieldTestBase { $test_file = $this->getTestFile('image'); // Disable extension checking. - $this->updateFileField($field_name, $type_name, array('file_extensions' => '')); + $this->updateFileField($field_name, $type_name, ['file_extensions' => '']); // Check that the file can be uploaded with no extension checking. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.'); $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.'); // Enable extension checking for text files. - $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt')); + $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']); // Check that the file can still be removed. $this->removeNodeFile($nid); diff --git a/core/modules/file/src/Tests/FileFieldWidgetTest.php b/core/modules/file/src/Tests/FileFieldWidgetTest.php index 414c86b55f3..f132d70d5f7 100644 --- a/core/modules/file/src/Tests/FileFieldWidgetTest.php +++ b/core/modules/file/src/Tests/FileFieldWidgetTest.php @@ -38,7 +38,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { * * @var array */ - public static $modules = array('comment', 'block'); + public static $modules = ['comment', 'block']; /** * Creates a temporary file, for a specific user. @@ -81,13 +81,13 @@ class FileFieldWidgetTest extends FileFieldTestBase { $test_file = $this->getTestFile('text'); - foreach (array('nojs', 'js') as $type) { + foreach (['nojs', 'js'] as $type) { // Create a new node with the uploaded file and ensure it got uploaded // successfully. // @todo This only tests a 'nojs' submission, because drupalPostAjaxForm() // does not yet support file uploads. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'New file saved to disk on node creation.'); @@ -104,11 +104,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { // "Click" the remove button (emulating either a nojs or js submission). switch ($type) { case 'nojs': - $this->drupalPostForm(NULL, array(), t('Remove')); + $this->drupalPostForm(NULL, [], t('Remove')); break; case 'js': $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]'); - $this->drupalPostAjaxForm(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value'])); + $this->drupalPostAjaxForm(NULL, [], [(string) $button[0]['name'] => (string) $button[0]['value']]); break; } @@ -121,8 +121,8 @@ class FileFieldWidgetTest extends FileFieldTestBase { $this->assertTrue(isset($label[0]), 'Label for upload found.'); // Save the node and ensure it does not have the file. - $this->drupalPostForm(NULL, array(), t('Save and keep published')); - $node_storage->resetCache(array($nid)); + $this->drupalPostForm(NULL, [], t('Save and keep published')); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertTrue(empty($node->{$field_name}->target_id), 'File was successfully removed from the node.'); } @@ -143,12 +143,12 @@ class FileFieldWidgetTest extends FileFieldTestBase { $field_name = 'test_file_field_1'; $field_name2 = 'test_file_field_2'; $cardinality = 3; - $this->createFileField($field_name, 'node', $type_name, array('cardinality' => $cardinality)); - $this->createFileField($field_name2, 'node', $type_name, array('cardinality' => $cardinality)); + $this->createFileField($field_name, 'node', $type_name, ['cardinality' => $cardinality]); + $this->createFileField($field_name2, 'node', $type_name, ['cardinality' => $cardinality]); $test_file = $this->getTestFile('text'); - foreach (array('nojs', 'js') as $type) { + foreach (['nojs', 'js'] as $type) { // Visit the node creation form, and upload 3 files for each field. Since // the field has cardinality of 3, ensure the "Upload" button is displayed // until after the 3rd file, and after that, isn't displayed. Because @@ -158,9 +158,9 @@ class FileFieldWidgetTest extends FileFieldTestBase { // does not yet emulate jQuery's file upload. // $this->drupalGet("node/add/$type_name"); - foreach (array($field_name2, $field_name) as $each_field_name) { + foreach ([$field_name2, $field_name] as $each_field_name) { for ($delta = 0; $delta < 3; $delta++) { - $edit = array('files[' . $each_field_name . '_' . $delta . '][]' => drupal_realpath($test_file->getFileUri())); + $edit = ['files[' . $each_field_name . '_' . $delta . '][]' => drupal_realpath($test_file->getFileUri())]; // If the Upload button doesn't exist, drupalPostForm() will automatically // fail with an assertion message. $this->drupalPostForm(NULL, $edit, t('Upload')); @@ -170,7 +170,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { $num_expected_remove_buttons = 6; - foreach (array($field_name, $field_name2) as $current_field_name) { + foreach ([$field_name, $field_name2] as $current_field_name) { // How many uploaded files for the current field are remaining. $remaining = 3; // Test clicking each "Remove" button. For extra robustness, test them out @@ -179,11 +179,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { // - First remove the 2nd file. // - Then remove what is then the 2nd file (was originally the 3rd file). // - Then remove the first file. - foreach (array(1, 1, 0) as $delta) { + foreach ([1, 1, 0] as $delta) { // Ensure we have the expected number of Remove buttons, and that they // are numbered sequentially. $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]'); - $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', array('%n' => $num_expected_remove_buttons, '%type' => $type))); + $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', ['%n' => $num_expected_remove_buttons, '%type' => $type])); foreach ($buttons as $i => $button) { $key = $i >= $remaining ? $i - $remaining : $i; $check_field_name = $field_name2; @@ -210,12 +210,12 @@ class FileFieldWidgetTest extends FileFieldTestBase { $button['value'] = 'DUMMY'; } } - $this->drupalPostForm(NULL, array(), t('Remove')); + $this->drupalPostForm(NULL, [], t('Remove')); break; case 'js': // drupalPostAjaxForm() lets us target the button precisely, so we don't // require the workaround used above for nojs. - $this->drupalPostAjaxForm(NULL, array(), array($button_name => t('Remove'))); + $this->drupalPostAjaxForm(NULL, [], [$button_name => t('Remove')]); break; } $num_expected_remove_buttons--; @@ -224,38 +224,38 @@ class FileFieldWidgetTest extends FileFieldTestBase { // Ensure an "Upload" button for the current field is displayed with the // correct name. $upload_button_name = $current_field_name . '_' . $remaining . '_upload_button'; - $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name)); - $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type))); + $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', [':name' => $upload_button_name]); + $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', ['%type' => $type])); // Ensure only at most one button per field is displayed. $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]'); $expected = $current_field_name == $field_name ? 1 : 2; - $this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', array('%type' => $type))); + $this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', ['%type' => $type])); } } // Ensure the page now has no Remove buttons. - $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type))); + $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', ['%type' => $type])); // Save the node and ensure it does not have any files. - $this->drupalPostForm(NULL, array('title[0][value]' => $this->randomMachineName()), t('Save and publish')); - $matches = array(); + $this->drupalPostForm(NULL, ['title[0][value]' => $this->randomMachineName()], t('Save and publish')); + $matches = []; preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches); $nid = $matches[1]; - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertTrue(empty($node->{$field_name}->target_id), 'Node was successfully saved without any files.'); } - $upload_files_node_creation = array($test_file, $test_file); + $upload_files_node_creation = [$test_file, $test_file]; // Try to upload multiple files, but fewer than the maximum. $nid = $this->uploadNodeFiles($upload_files_node_creation, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertEqual(count($node->{$field_name}), count($upload_files_node_creation), 'Node was successfully saved with mulitple files.'); // Try to upload more files than allowed on revision. - $upload_files_node_revision = array($test_file, $test_file, $test_file, $test_file); + $upload_files_node_revision = [$test_file, $test_file, $test_file, $test_file]; $this->uploadNodeFiles($upload_files_node_revision, $field_name, $nid, 1); $args = [ '%field' => $field_name, @@ -264,7 +264,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { '%list' => implode(', ', array_fill(0, 3, $test_file->getFilename())), ]; $this->assertRaw(t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args)); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertEqual(count($node->{$field_name}), $cardinality, 'More files than allowed could not be saved to node.'); @@ -274,14 +274,14 @@ class FileFieldWidgetTest extends FileFieldTestBase { 'type' => $type_name ]); $this->uploadNodeFile($test_file, $field_name, $node->id(), 1); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully revised to maximum number of files.'); // Try to upload exactly the allowed number of files, new node. $upload_files = array_fill(0, $cardinality, $test_file); $nid = $this->uploadNodeFiles($upload_files, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully saved with maximum number of files.'); @@ -304,7 +304,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { function testPrivateFileSetting() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); // Grant the admin user required permissions. - user_role_grant_permissions($this->adminUser->roles[0]->target_id, array('administer node fields')); + user_role_grant_permissions($this->adminUser->roles[0]->target_id, ['administer node fields']); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); @@ -315,10 +315,10 @@ class FileFieldWidgetTest extends FileFieldTestBase { $test_file = $this->getTestFile('text'); // Change the field setting to make its files private, and upload a file. - $edit = array('settings[uri_scheme]' => 'private'); + $edit = ['settings[uri_scheme]' => 'private']; $this->drupalPostForm("admin/structure/types/manage/$type_name/fields/$field_id/storage", $edit, t('Save field settings')); $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertFileExists($node_file, 'New file saved to disk on node creation.'); @@ -342,41 +342,41 @@ class FileFieldWidgetTest extends FileFieldTestBase { * Tests that download restrictions on private files work on comments. */ function testPrivateFileComment() { - $user = $this->drupalCreateUser(array('access comments')); + $user = $this->drupalCreateUser(['access comments']); // Grant the admin user required comment permissions. $roles = $this->adminUser->getRoles(); - user_role_grant_permissions($roles[1], array('administer comment fields', 'administer comments')); + user_role_grant_permissions($roles[1], ['administer comment fields', 'administer comments']); // Revoke access comments permission from anon user, grant post to // authenticated. - user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments')); - user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array('post comments', 'skip comment approval')); + user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']); + user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['post comments', 'skip comment approval']); // Create a new field. $this->addDefaultCommentField('node', 'article'); $name = strtolower($this->randomMachineName()); $label = $this->randomMachineName(); - $storage_edit = array('settings[uri_scheme]' => 'private'); + $storage_edit = ['settings[uri_scheme]' => 'private']; $this->fieldUIAddNewField('admin/structure/comment/manage/comment', $name, $label, 'file', $storage_edit); // Manually clear cache on the tester side. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create node. - $edit = array( + $edit = [ 'title[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm('node/add/article', $edit, t('Save and publish')); $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); // Add a comment with a file. $text_file = $this->getTestFile('text'); - $edit = array( + $edit = [ 'files[field_' . $name . '_' . 0 . ']' => drupal_realpath($text_file->getFileUri()), 'comment_body[0][value]' => $comment_body = $this->randomMachineName(), - ); + ]; $this->drupalPostForm('node/' . $node->id(), $edit, t('Save')); // Get the comment ID. @@ -402,7 +402,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { // Unpublishes node. $this->drupalLogin($this->adminUser); - $this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save and unpublish')); + $this->drupalPostForm('node/' . $node->id() . '/edit', [], t('Save and unpublish')); // Ensures normal user can no longer download the file. $this->drupalLogin($user); @@ -417,11 +417,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); $this->createFileField($field_name, 'node', $type_name); - $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt')); + $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']); - foreach (array('nojs', 'js') as $type) { + foreach (['nojs', 'js'] as $type) { // Create node and prepare files for upload. - $node = $this->drupalCreateNode(array('type' => 'article')); + $node = $this->drupalCreateNode(['type' => 'article']); $nid = $node->id(); $this->drupalGet("node/$nid/edit"); $test_file_text = $this->getTestFile('text'); @@ -436,11 +436,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { break; case 'js': $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]'); - $this->drupalPostAjaxForm(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value'])); + $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]); break; } - $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt')); - $this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', array('%type' => $type))); + $error_message = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => 'txt']); + $this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', ['%type' => $type])); // Upload file with correct extension, check that error message is removed. $edit[$name] = drupal_realpath($test_file_text->getFileUri()); @@ -450,10 +450,10 @@ class FileFieldWidgetTest extends FileFieldTestBase { break; case 'js': $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]'); - $this->drupalPostAjaxForm(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value'])); + $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]); break; } - $this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', array('%type' => $type))); + $this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', ['%type' => $type])); } } @@ -498,11 +498,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { $victim_user = $this->drupalCreateUser(); // Create an attacker user. - $attacker_user = $this->drupalCreateUser(array( + $attacker_user = $this->drupalCreateUser([ 'access content', 'create article content', 'edit any article content', - )); + ]); // Log in as the attacker user. $this->drupalLogin($attacker_user); @@ -522,11 +522,11 @@ class FileFieldWidgetTest extends FileFieldTestBase { $attacker_user = User::getAnonymousUser(); // Set up permissions for anonymous attacker user. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access content' => TRUE, 'create article content' => TRUE, 'edit any article content' => TRUE, - )); + ]); // Log out so as to be the anonymous attacker user. $this->drupalLogout(); @@ -549,7 +549,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { $this->createFileField($field_name, 'node', $type_name); $test_file = $this->getTestFile('text'); - foreach (array('nojs', 'js') as $type) { + foreach (['nojs', 'js'] as $type) { // Create a temporary file owned by the victim user. This will be as if // they had uploaded the file, but not saved the node they were editing // or creating. @@ -567,7 +567,7 @@ class FileFieldWidgetTest extends FileFieldTestBase { // Attach a file to a node. $edit['files[' . $field_name . '_0]'] = $this->container->get('file_system')->realpath($test_file->getFileUri()); - $this->drupalPostForm(Url::fromRoute('node.add', array('node_type' => $type_name)), $edit, t('Save')); + $this->drupalPostForm(Url::fromRoute('node.add', ['node_type' => $type_name]), $edit, t('Save')); $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); /** @var \Drupal\file\FileInterface $node_file */ diff --git a/core/modules/file/src/Tests/FileListingTest.php b/core/modules/file/src/Tests/FileListingTest.php index 708f1385f94..e163529ed26 100644 --- a/core/modules/file/src/Tests/FileListingTest.php +++ b/core/modules/file/src/Tests/FileListingTest.php @@ -18,7 +18,7 @@ class FileListingTest extends FileFieldTestBase { * * @var array */ - public static $modules = array('views', 'file', 'image', 'entity_test'); + public static $modules = ['views', 'file', 'image', 'entity_test']; /** * An authenticated user. @@ -30,9 +30,9 @@ class FileListingTest extends FileFieldTestBase { protected function setUp() { parent::setUp(); - $this->adminUser = $this->drupalCreateUser(array('access files overview', 'bypass node access')); + $this->adminUser = $this->drupalCreateUser(['access files overview', 'bypass node access']); $this->baseUser = $this->drupalCreateUser(); - $this->createFileField('file', 'node', 'article', array(), array('file_extensions' => 'txt png')); + $this->createFileField('file', 'node', 'article', [], ['file_extensions' => 'txt png']); } /** @@ -70,7 +70,7 @@ class FileListingTest extends FileFieldTestBase { $this->drupalLogin($this->adminUser); for ($i = 0; $i < 5; $i++) { - $nodes[] = $this->drupalCreateNode(array('type' => 'article')); + $nodes[] = $this->drupalCreateNode(['type' => 'article']); } $this->drupalGet('admin/content/files'); @@ -84,15 +84,15 @@ class FileListingTest extends FileFieldTestBase { $this->drupalGet('admin/content/files/usage/' . $file->id()); $this->assertResponse(200); - $this->assertTitle(t('File usage information for @file | Drupal', array('@file' => $file->getFilename()))); + $this->assertTitle(t('File usage information for @file | Drupal', ['@file' => $file->getFilename()])); foreach ($nodes as &$node) { $this->drupalGet('node/' . $node->id() . '/edit'); $file = $this->getTestFile('image'); - $edit = array( + $edit = [ 'files[file_0]' => drupal_realpath($file->getFileUri()), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); $node = Node::load($node->id()); } @@ -122,7 +122,7 @@ class FileListingTest extends FileFieldTestBase { $usage = $this->sumUsages($file_usage->listUsage($file)); $this->assertRaw('admin/content/files/usage/' . $file->id() . '">' . $usage); - $result = $this->xpath("//td[contains(@class, 'views-field-status') and contains(text(), :value)]", array(':value' => t('Temporary'))); + $result = $this->xpath("//td[contains(@class, 'views-field-status') and contains(text(), :value)]", [':value' => t('Temporary')]); $this->assertEqual(1, count($result), 'Unused file marked as temporary.'); // Test file usage page. @@ -155,7 +155,7 @@ class FileListingTest extends FileFieldTestBase { // Create a bundle and attach a File field to the bundle. $bundle = $this->randomMachineName(); entity_test_create_bundle($bundle, NULL, 'entity_test_constraints'); - $this->createFileField('field_test_file', 'entity_test_constraints', $bundle, array(), array('file_extensions' => 'txt png')); + $this->createFileField('field_test_file', 'entity_test_constraints', $bundle, [], ['file_extensions' => 'txt png']); // Create file to attach to entity. $file = File::create([ @@ -169,18 +169,18 @@ class FileListingTest extends FileFieldTestBase { // Create entity and attach the created file. $entity_name = $this->randomMachineName(); - $entity = EntityTestConstraints::create(array( + $entity = EntityTestConstraints::create([ 'uid' => 1, 'name' => $entity_name, 'type' => $bundle, - 'field_test_file' => array( + 'field_test_file' => [ 'target_id' => $file->id(), - ), - )); + ], + ]); $entity->save(); // Create node entity and attach the created file. - $node = $this->drupalCreateNode(array('type' => 'article', 'file' => $file)); + $node = $this->drupalCreateNode(['type' => 'article', 'file' => $file]); $node->save(); // Load the file usage page for the created and attached file. diff --git a/core/modules/file/src/Tests/FileManagedFileElementTest.php b/core/modules/file/src/Tests/FileManagedFileElementTest.php index 07102a04df9..994803e0be6 100644 --- a/core/modules/file/src/Tests/FileManagedFileElementTest.php +++ b/core/modules/file/src/Tests/FileManagedFileElementTest.php @@ -21,16 +21,16 @@ class FileManagedFileElementTest extends FileFieldTestBase { // Perform the tests with all permutations of $form['#tree'], // $element['#extended'], and $element['#multiple']. $test_file = $this->getTestFile('text'); - foreach (array(0, 1) as $tree) { - foreach (array(0, 1) as $extended) { - foreach (array(0, 1) as $multiple) { + foreach ([0, 1] as $tree) { + foreach ([0, 1] as $extended) { + foreach ([0, 1] as $multiple) { $path = 'file/test/' . $tree . '/' . $extended . '/' . $multiple; $input_base_name = $tree ? 'nested_file' : 'file'; $file_field_name = $multiple ? 'files[' . $input_base_name . '][]' : 'files[' . $input_base_name . ']'; // Submit without a file. - $this->drupalPostForm($path, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array()))), 'Submitted without a file.'); + $this->drupalPostForm($path, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => implode(',', [])]), 'Submitted without a file.'); // Submit with a file, but with an invalid form token. Ensure the file // was not saved. @@ -46,22 +46,22 @@ class FileManagedFileElementTest extends FileFieldTestBase { // Submit a new file, without using the Upload button. $last_fid_prior = $this->getLastFileId(); - $edit = array($file_field_name => drupal_realpath($test_file->getFileUri())); + $edit = [$file_field_name => drupal_realpath($test_file->getFileUri())]; $this->drupalPostForm($path, $edit, t('Save')); $last_fid = $this->getLastFileId(); $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.'); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Submit handler has correct file info.'); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => implode(',', [$last_fid])]), 'Submit handler has correct file info.'); // Submit no new input, but with a default file. - $this->drupalPostForm($path . '/' . $last_fid, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Empty submission did not change an existing file.'); + $this->drupalPostForm($path . '/' . $last_fid, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => implode(',', [$last_fid])]), 'Empty submission did not change an existing file.'); // Now, test the Upload and Remove buttons, with and without Ajax. - foreach (array(FALSE, TRUE) as $ajax) { + foreach ([FALSE, TRUE] as $ajax) { // Upload, then Submit. $last_fid_prior = $this->getLastFileId(); $this->drupalGet($path); - $edit = array($file_field_name => drupal_realpath($test_file->getFileUri())); + $edit = [$file_field_name => drupal_realpath($test_file->getFileUri())]; if ($ajax) { $this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button'); } @@ -70,15 +70,15 @@ class FileManagedFileElementTest extends FileFieldTestBase { } $last_fid = $this->getLastFileId(); $this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.'); - $this->drupalPostForm(NULL, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Submit handler has correct file info.'); + $this->drupalPostForm(NULL, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => implode(',', [$last_fid])]), 'Submit handler has correct file info.'); // Remove, then Submit. $remove_button_title = $multiple ? t('Remove selected') : t('Remove'); - $remove_edit = array(); + $remove_edit = []; if ($multiple) { $selected_checkbox = ($tree ? 'nested[file]' : 'file') . '[file_' . $last_fid . '][selected]'; - $remove_edit = array($selected_checkbox => '1'); + $remove_edit = [$selected_checkbox => '1']; } $this->drupalGet($path . '/' . $last_fid); if ($ajax) { @@ -87,22 +87,22 @@ class FileManagedFileElementTest extends FileFieldTestBase { else { $this->drupalPostForm(NULL, $remove_edit, $remove_button_title); } - $this->drupalPostForm(NULL, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => '')), 'Submission after file removal was successful.'); + $this->drupalPostForm(NULL, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => '']), 'Submission after file removal was successful.'); // Upload, then Remove, then Submit. $this->drupalGet($path); - $edit = array($file_field_name => drupal_realpath($test_file->getFileUri())); + $edit = [$file_field_name => drupal_realpath($test_file->getFileUri())]; if ($ajax) { $this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button'); } else { $this->drupalPostForm(NULL, $edit, t('Upload')); } - $remove_edit = array(); + $remove_edit = []; if ($multiple) { $selected_checkbox = ($tree ? 'nested[file]' : 'file') . '[file_' . $this->getLastFileId() . '][selected]'; - $remove_edit = array($selected_checkbox => '1'); + $remove_edit = [$selected_checkbox => '1']; } if ($ajax) { $this->drupalPostAjaxForm(NULL, $remove_edit, $input_base_name . '_remove_button'); @@ -111,8 +111,8 @@ class FileManagedFileElementTest extends FileFieldTestBase { $this->drupalPostForm(NULL, $remove_edit, $remove_button_title); } - $this->drupalPostForm(NULL, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => '')), 'Submission after file upload and removal was successful.'); + $this->drupalPostForm(NULL, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => '']), 'Submission after file upload and removal was successful.'); } } } @@ -120,8 +120,8 @@ class FileManagedFileElementTest extends FileFieldTestBase { // The multiple file upload has additional conditions that need checking. $path = 'file/test/1/1/1'; - $edit = array('files[nested_file][]' => drupal_realpath($test_file->getFileUri())); - $fid_list = array(); + $edit = ['files[nested_file][]' => drupal_realpath($test_file->getFileUri())]; + $fid_list = []; $this->drupalGet($path); @@ -136,13 +136,13 @@ class FileManagedFileElementTest extends FileFieldTestBase { $this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[1] . '][selected]"]', NULL, 'Second file successfully uploaded to multiple file element.'); // Save the entire form. - $this->drupalPostForm(NULL, array(), t('Save')); - $this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', $fid_list))), 'Two files saved into a single multiple file element.'); + $this->drupalPostForm(NULL, [], t('Save')); + $this->assertRaw(t('The file ids are %fids.', ['%fids' => implode(',', $fid_list)]), 'Two files saved into a single multiple file element.'); // Delete only the first file. - $edit = array( + $edit = [ 'nested[file][file_' . $fid_list[0] . '][selected]' => '1', - ); + ]; $this->drupalPostForm($path . '/' . implode(',', $fid_list), $edit, t('Remove selected')); // Check that the first file has been deleted but not the second. @@ -181,7 +181,7 @@ class FileManagedFileElementTest extends FileFieldTestBase { $edit = [$file_field_name => drupal_realpath($test_file->getFileUri())]; $this->drupalPostForm(NULL, $edit, t('Upload')); - $this->drupalPostForm(NULL, array(), t('Save')); + $this->drupalPostForm(NULL, [], t('Save')); $fid = $this->getLastFileId(); /** @var $file \Drupal\file\FileInterface */ diff --git a/core/modules/file/src/Tests/FileManagedTestBase.php b/core/modules/file/src/Tests/FileManagedTestBase.php index 711d8a41f02..8bd85bdc7ab 100644 --- a/core/modules/file/src/Tests/FileManagedTestBase.php +++ b/core/modules/file/src/Tests/FileManagedTestBase.php @@ -20,7 +20,7 @@ abstract class FileManagedTestBase extends WebTestBase { * * @var array */ - public static $modules = array('file_test', 'file'); + public static $modules = ['file_test', 'file']; protected function setUp() { parent::setUp(); @@ -45,16 +45,16 @@ abstract class FileManagedTestBase extends WebTestBase { // Determine if there were any expected that were not called. $uncalled = array_diff($expected, $actual); if (count($uncalled)) { - $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)))); + $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)])); } else { - $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? '(none)' : implode(', ', $expected)))); + $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%expected' => empty($expected) ? '(none)' : implode(', ', $expected)])); } // Determine if there were any unexpected calls. $unexpected = array_diff($actual, $expected); if (count($unexpected)) { - $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)))); + $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)])); } else { $this->assertTrue(TRUE, 'No unexpected hooks were called.'); @@ -76,13 +76,13 @@ abstract class FileManagedTestBase extends WebTestBase { if (!isset($message)) { if ($actual_count == $expected_count) { - $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook)); + $message = format_string('hook_file_@name was called correctly.', ['@name' => $hook]); } elseif ($expected_count == 0) { - $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count)); + $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', ['@name' => $hook, '@count' => $actual_count]); } else { - $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count)); + $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]); } } $this->assertEqual($actual_count, $expected_count, $message); @@ -97,13 +97,13 @@ abstract class FileManagedTestBase extends WebTestBase { * File object to compare. */ function assertFileUnchanged(FileInterface $before, FileInterface $after) { - $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', array('%file1' => $before->id(), '%file2' => $after->id())), 'File unchanged'); - $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', array('%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id())), 'File unchanged'); - $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', array('%file1' => $before->getFilename(), '%file2' => $after->getFilename())), 'File unchanged'); - $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', array('%file1' => $before->getFileUri(), '%file2' => $after->getFileUri())), 'File unchanged'); - $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->getMimeType(), '%file2' => $after->getMimeType())), 'File unchanged'); - $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', array('%file1' => $before->getSize(), '%file2' => $after->getSize())), 'File unchanged'); - $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', array('%file1' => $before->isPermanent(), '%file2' => $after->isPermanent())), 'File unchanged'); + $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged'); + $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', ['%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id()]), 'File unchanged'); + $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged'); + $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged'); + $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged'); + $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged'); + $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%file1' => $before->isPermanent(), '%file2' => $after->isPermanent()]), 'File unchanged'); } /** @@ -115,8 +115,8 @@ abstract class FileManagedTestBase extends WebTestBase { * File object to compare. */ function assertDifferentFile(FileInterface $file1, FileInterface $file2) { - $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->id(), '%file2' => $file2->id())), 'Different file'); - $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Different file'); + $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file'); + $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Different file'); } /** @@ -128,8 +128,8 @@ abstract class FileManagedTestBase extends WebTestBase { * File object to compare. */ function assertSameFile(FileInterface $file1, FileInterface $file2) { - $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->id(), '%file2-fid' => $file2->id())), 'Same file'); - $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Same file'); + $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file'); + $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Same file'); } /** diff --git a/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php b/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php index 7987bcf3420..5f1e7073df8 100644 --- a/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php +++ b/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php @@ -14,7 +14,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { /** * {@inheritdoc} */ - public static $modules = array('language', 'content_translation'); + public static $modules = ['language', 'content_translation']; /** * The name of the file field used in the test. @@ -39,7 +39,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->createFileField($this->fieldName, 'node', 'page'); // Create and log in user. - $permissions = array( + $permissions = [ 'access administration pages', 'administer content translation', 'administer content types', @@ -49,25 +49,25 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { 'edit any page content', 'translate any entity', 'delete any page content', - ); + ]; $admin_user = $this->drupalCreateUser($permissions); $this->drupalLogin($admin_user); // Add a second and third language. - $edit = array(); + $edit = []; $edit['predefined_langcode'] = 'fr'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); - $edit = array(); + $edit = []; $edit['predefined_langcode'] = 'nl'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); // Enable translation for "Basic page" nodes. - $edit = array( + $edit = [ 'entity_types[node]' => 1, 'settings[node][page][translatable]' => 1, "settings[node][page][fields][$this->fieldName]" => 1, - ); + ]; $this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration')); \Drupal::entityManager()->clearCachedDefinitions(); } @@ -81,20 +81,20 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node file field is translatable.'); // Create a default language node. - $default_language_node = $this->drupalCreateNode(array('type' => 'page', 'title' => 'Lost in translation')); + $default_language_node = $this->drupalCreateNode(['type' => 'page', 'title' => 'Lost in translation']); // Edit the node to upload a file. - $edit = array(); + $edit = []; $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri); $this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save')); $first_fid = $this->getLastFileId(); // Translate the node into French: remove the existing file. - $this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/fr', array(), t('Remove')); + $this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/fr', [], t('Remove')); // Upload a different file. - $edit = array(); + $edit = []; $edit['title[0][value]'] = 'Bill Murray'; $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri); @@ -117,10 +117,10 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($file->isPermanent()); // Translate the node into dutch: remove the existing file. - $this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/nl', array(), t('Remove')); + $this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/nl', [], t('Remove')); // Upload a different file. - $edit = array(); + $edit = []; $edit['title[0][value]'] = 'Scarlett Johansson'; $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[2]->uri); @@ -145,10 +145,10 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($file->isPermanent()); // Edit the second translation: remove the existing file. - $this->drupalPostForm('fr/node/' . $default_language_node->id() . '/edit', array(), t('Remove')); + $this->drupalPostForm('fr/node/' . $default_language_node->id() . '/edit', [], t('Remove')); // Upload a different file. - $edit = array(); + $edit = []; $edit['title[0][value]'] = 'David Bowie'; $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[3]->uri); @@ -169,7 +169,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($file->isPermanent()); // Delete the third translation. - $this->drupalPostForm('nl/node/' . $default_language_node->id() . '/delete', array(), t('Delete Dutch translation')); + $this->drupalPostForm('nl/node/' . $default_language_node->id() . '/delete', [], t('Delete Dutch translation')); \Drupal::entityTypeManager()->getStorage('file')->resetCache(); @@ -185,7 +185,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($file->isTemporary()); // Delete the all translations. - $this->drupalPostForm('node/' . $default_language_node->id() . '/delete', array(), t('Delete all translations')); + $this->drupalPostForm('node/' . $default_language_node->id() . '/delete', [], t('Delete all translations')); \Drupal::entityTypeManager()->getStorage('file')->resetCache(); diff --git a/core/modules/file/src/Tests/FilePrivateTest.php b/core/modules/file/src/Tests/FilePrivateTest.php index 2705ef205b6..9ed4a9e68d5 100644 --- a/core/modules/file/src/Tests/FilePrivateTest.php +++ b/core/modules/file/src/Tests/FilePrivateTest.php @@ -19,7 +19,7 @@ class FilePrivateTest extends FileFieldTestBase { * * @var array */ - public static $modules = array('node_access_test', 'field_test'); + public static $modules = ['node_access_test', 'field_test']; protected function setUp() { parent::setUp(); @@ -35,11 +35,11 @@ class FilePrivateTest extends FileFieldTestBase { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); - $this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private')); + $this->createFileField($field_name, 'node', $type_name, ['uri_scheme' => 'private']); $test_file = $this->getTestFile('text'); - $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE)); - \Drupal::entityManager()->getStorage('node')->resetCache(array($nid)); + $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, ['private' => TRUE]); + \Drupal::entityManager()->getStorage('node')->resetCache([$nid]); /* @var \Drupal\node\NodeInterface $node */ $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); @@ -56,11 +56,11 @@ class FilePrivateTest extends FileFieldTestBase { // Create a field with no view access. See // field_test_entity_field_access(). $no_access_field_name = 'field_no_view_access'; - $this->createFileField($no_access_field_name, 'node', $type_name, array('uri_scheme' => 'private')); + $this->createFileField($no_access_field_name, 'node', $type_name, ['uri_scheme' => 'private']); // Test with the field that should deny access through field access. $this->drupalLogin($this->adminUser); - $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE)); - \Drupal::entityManager()->getStorage('node')->resetCache(array($nid)); + $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, ['private' => TRUE]); + \Drupal::entityManager()->getStorage('node')->resetCache([$nid]); $node = $node_storage->load($nid); $node_file = File::load($node->{$no_access_field_name}->target_id); @@ -70,7 +70,7 @@ class FilePrivateTest extends FileFieldTestBase { $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.'); // Attempt to reuse the file when editing a node. - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); $new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']); @@ -80,17 +80,17 @@ class FilePrivateTest extends FileFieldTestBase { $this->assertUrl('node/' . $new_node->id() . '/edit'); // Check that we got the expected constraint form error. $constraint = new ReferenceAccessConstraint(); - $this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id()))); + $this->assertRaw(SafeMarkup::format($constraint->message, ['%type' => 'file', '%id' => $node_file->id()])); // Attempt to reuse the existing file when creating a new node, and confirm // that access is still denied. - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $edit[$field_name . '[0][fids]'] = $node_file->id(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); $new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']); $this->assertTrue(empty($new_node), 'Node was not created.'); $this->assertUrl('node/add/' . $type_name); - $this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id()))); + $this->assertRaw(SafeMarkup::format($constraint->message, ['%type' => 'file', '%id' => $node_file->id()])); // Now make file_test_file_download() return everything. \Drupal::state()->set('file_test.allow_all', TRUE); diff --git a/core/modules/file/src/Tests/FileTokenReplaceTest.php b/core/modules/file/src/Tests/FileTokenReplaceTest.php index dfb9e51d49c..143ded4b603 100644 --- a/core/modules/file/src/Tests/FileTokenReplaceTest.php +++ b/core/modules/file/src/Tests/FileTokenReplaceTest.php @@ -35,12 +35,12 @@ class FileTokenReplaceTest extends FileFieldTestBase { $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Load the node and the file. - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $file = File::load($node->{$field_name}->target_id); // Generate and test sanitized tokens. - $tests = array(); + $tests = []; $tests['[file:fid]'] = $file->id(); $tests['[file:name]'] = Html::escape($file->getFilename()); $tests['[file:path]'] = Html::escape($file->getFileUri()); @@ -77,8 +77,8 @@ class FileTokenReplaceTest extends FileFieldTestBase { foreach ($tests as $input => $expected) { $bubbleable_metadata = new BubbleableMetadata(); - $output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()), $bubbleable_metadata); - $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input))); + $output = $token_service->replace($input, ['file' => $file], ['langcode' => $language_interface->getId()], $bubbleable_metadata); + $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', ['%token' => $input])); $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]); } @@ -89,8 +89,8 @@ class FileTokenReplaceTest extends FileFieldTestBase { $tests['[file:size]'] = format_size($file->getSize()); foreach ($tests as $input => $expected) { - $output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE)); - $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input))); + $output = $token_service->replace($input, ['file' => $file], ['langcode' => $language_interface->getId(), 'sanitize' => FALSE]); + $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', ['%token' => $input])); } } diff --git a/core/modules/file/src/Tests/PrivateFileOnTranslatedEntityTest.php b/core/modules/file/src/Tests/PrivateFileOnTranslatedEntityTest.php index 15039edcbd7..da5abb5bd73 100644 --- a/core/modules/file/src/Tests/PrivateFileOnTranslatedEntityTest.php +++ b/core/modules/file/src/Tests/PrivateFileOnTranslatedEntityTest.php @@ -15,7 +15,7 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { /** * {@inheritdoc} */ - public static $modules = array('language', 'content_translation'); + public static $modules = ['language', 'content_translation']; /** * The name of the file field used in the test. @@ -31,14 +31,14 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { parent::setUp(); // Create the "Basic page" node type. - $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); + $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); // Create a file field on the "Basic page" node type. $this->fieldName = strtolower($this->randomMachineName()); - $this->createFileField($this->fieldName, 'node', 'page', array('uri_scheme' => 'private')); + $this->createFileField($this->fieldName, 'node', 'page', ['uri_scheme' => 'private']); // Create and log in user. - $permissions = array( + $permissions = [ 'access administration pages', 'administer content translation', 'administer content types', @@ -47,21 +47,21 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { 'create page content', 'edit any page content', 'translate any entity', - ); + ]; $admin_user = $this->drupalCreateUser($permissions); $this->drupalLogin($admin_user); // Add a second language. - $edit = array(); + $edit = []; $edit['predefined_langcode'] = 'fr'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); // Enable translation for "Basic page" nodes. - $edit = array( + $edit = [ 'entity_types[node]' => 1, 'settings[node][page][translatable]' => 1, "settings[node][page][fields][$this->fieldName]" => 1, - ); + ]; $this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration')); \Drupal::entityManager()->clearCachedDefinitions(); } @@ -75,10 +75,10 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { $this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node file field is translatable.'); // Create a default language node. - $default_language_node = $this->drupalCreateNode(array('type' => 'page')); + $default_language_node = $this->drupalCreateNode(['type' => 'page']); // Edit the node to upload a file. - $edit = array(); + $edit = []; $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri); $this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save')); @@ -88,7 +88,7 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { $this->rebuildContainer(); // Ensure the file can be downloaded. - \Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id())); + \Drupal::entityManager()->getStorage('node')->resetCache([$default_language_node->id()]); $node = Node::load($default_language_node->id()); $node_file = File::load($node->{$this->fieldName}->target_id); $this->drupalGet(file_create_url($node_file->getFileUri())); @@ -99,10 +99,10 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { $this->clickLink(t('Add')); // Remove the existing file. - $this->drupalPostForm(NULL, array(), t('Remove')); + $this->drupalPostForm(NULL, [], t('Remove')); // Upload a different file. - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri); @@ -110,7 +110,7 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase { $last_fid = $this->getLastFileId(); // Verify the translation was created. - \Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id())); + \Drupal::entityManager()->getStorage('node')->resetCache([$default_language_node->id()]); $default_language_node = Node::load($default_language_node->id()); $this->assertTrue($default_language_node->hasTranslation('fr'), 'Node found in database.'); $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.'); diff --git a/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php b/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php index b1ee6a65de1..d468ed326f5 100644 --- a/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php +++ b/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php @@ -14,7 +14,7 @@ class RemoteFileSaveUploadTest extends SaveUploadTest { * * @var array */ - public static $modules = array('file_test'); + public static $modules = ['file_test']; protected function setUp() { parent::setUp(); diff --git a/core/modules/file/src/Tests/SaveUploadTest.php b/core/modules/file/src/Tests/SaveUploadTest.php index 3aaa5cff049..14071737f0b 100644 --- a/core/modules/file/src/Tests/SaveUploadTest.php +++ b/core/modules/file/src/Tests/SaveUploadTest.php @@ -15,7 +15,7 @@ class SaveUploadTest extends FileManagedTestBase { * * @var array */ - public static $modules = array('dblog'); + public static $modules = ['dblog']; /** * An image file path for uploading. @@ -43,7 +43,7 @@ class SaveUploadTest extends FileManagedTestBase { protected function setUp() { parent::setUp(); - $account = $this->drupalCreateUser(array('access site reports')); + $account = $this->drupalCreateUser(['access site reports']); $this->drupalLogin($account); $image_files = $this->drupalGetTestFiles('image'); @@ -58,17 +58,17 @@ class SaveUploadTest extends FileManagedTestBase { $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField(); // Upload with replace to guarantee there's something there. - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called then clean out the hook // counters. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); file_test_reset(); } @@ -88,14 +88,14 @@ class SaveUploadTest extends FileManagedTestBase { // Upload a second file. $image2 = current($this->drupalGetTestFiles('image')); - $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri)); + $edit = ['files[file_test_upload]' => drupal_realpath($image2->uri)]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!')); $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField(); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); $file2 = File::load($max_fid_after); $this->assertTrue($file2, 'Loaded the file'); @@ -103,7 +103,7 @@ class SaveUploadTest extends FileManagedTestBase { $this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.'); // Load both files using File::loadMultiple(). - $files = File::loadMultiple(array($file1->id(), $file2->id())); + $files = File::loadMultiple([$file1->id(), $file2->id()]); $this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully'); $this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully'); @@ -111,10 +111,10 @@ class SaveUploadTest extends FileManagedTestBase { $image3 = current($this->drupalGetTestFiles('image')); $image3_realpath = drupal_realpath($image3->uri); $dir = $this->randomMachineName(); - $edit = array( + $edit = [ 'files[file_test_upload]' => $image3_realpath, 'file_subdir' => $dir, - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!')); @@ -130,11 +130,11 @@ class SaveUploadTest extends FileManagedTestBase { // implicitly tested at the testNormal() test. Here we tell // file_save_upload() to only allow ".foo". $extensions = 'foo'; - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'extensions' => $extensions, - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); @@ -143,18 +143,18 @@ class SaveUploadTest extends FileManagedTestBase { $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate')); + $this->assertFileHooksCalled(['validate']); // Reset the hook counters. file_test_reset(); $extensions = 'foo ' . $this->imageExtension; // Now tell file_save_upload() to allow the extension of our test image. - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'extensions' => $extensions, - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); @@ -162,24 +162,24 @@ class SaveUploadTest extends FileManagedTestBase { $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'load', 'update')); + $this->assertFileHooksCalled(['validate', 'load', 'update']); // Reset the hook counters. file_test_reset(); // Now tell file_save_upload() to allow any extension. - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'allow_all_extensions' => TRUE, - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'load', 'update')); + $this->assertFileHooksCalled(['validate', 'load', 'update']); } /** @@ -189,12 +189,12 @@ class SaveUploadTest extends FileManagedTestBase { $config = $this->config('system.file'); // Allow the .php extension and make sure it gets renamed to .txt for // safety. Also check to make sure its MIME type was changed. - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->phpfile->uri), 'is_image_file' => FALSE, 'extensions' => 'php', - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); @@ -204,7 +204,7 @@ class SaveUploadTest extends FileManagedTestBase { $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); // Ensure dangerous files are not renamed when insecure uploads is TRUE. // Turn on insecure uploads. @@ -215,11 +215,11 @@ class SaveUploadTest extends FileManagedTestBase { $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.'); - $this->assertRaw(t('File name is @filename', array('@filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.'); + $this->assertRaw(t('File name is @filename', ['@filename' => $this->phpfile->filename]), 'Dangerous file was not renamed when insecure uploads is TRUE.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); // Turn off insecure uploads. $config->set('allow_insecure_uploads', 0)->save(); @@ -237,10 +237,10 @@ class SaveUploadTest extends FileManagedTestBase { file_test_reset(); $extensions = $this->imageExtension; - $edit = array( + $edit = [ 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'extensions' => $extensions, - ); + ]; $munged_filename = $this->image->getFilename(); $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.')); @@ -249,84 +249,84 @@ class SaveUploadTest extends FileManagedTestBase { $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.'); - $this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.'); + $this->assertRaw(t('File name is @filename', ['@filename' => $munged_filename]), 'File was successfully munged.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); // Ensure we don't munge files if we're allowing any extension. // Reset the hook counters. file_test_reset(); - $edit = array( + $edit = [ 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'allow_all_extensions' => TRUE, - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.'); - $this->assertRaw(t('File name is @filename', array('@filename' => $this->image->getFilename())), 'File was not munged when allowing any extension.'); + $this->assertRaw(t('File name is @filename', ['@filename' => $this->image->getFilename()]), 'File was not munged when allowing any extension.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); } /** * Test renaming when uploading over a file that already exists. */ function testExistingRename() { - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_RENAME, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()) - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'insert')); + $this->assertFileHooksCalled(['validate', 'insert']); } /** * Test replacement when uploading over a file that already exists. */ function testExistingReplace() { - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()) - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('validate', 'load', 'update')); + $this->assertFileHooksCalled(['validate', 'load', 'update']); } /** * Test for failure when uploading over a file that already exists. */ function testExistingError() { - $edit = array( + $edit = [ 'file_test_replace' => FILE_EXISTS_ERROR, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()) - ); + ]; $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.'); // Check that the no hooks were called while failing. - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); } /** * Test for no failures when not uploading a file. */ function testNoUpload() { - $this->drupalPostForm('file-test/upload', array(), t('Submit')); + $this->drupalPostForm('file-test/upload', [], t('Submit')); $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.'); } @@ -339,10 +339,10 @@ class SaveUploadTest extends FileManagedTestBase { drupal_mkdir('temporary://' . $test_directory, 0000); $this->assertTrue(is_dir('temporary://' . $test_directory)); - $edit = array( + $edit = [ 'file_subdir' => $test_directory, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()) - ); + ]; \Drupal::state()->set('file_test.disable_error_collection', TRUE); $this->drupalPostForm('file-test/upload', $edit, t('Submit')); @@ -353,10 +353,10 @@ class SaveUploadTest extends FileManagedTestBase { // Uploading failed. Now check the log. $this->drupalGet('admin/reports/dblog'); $this->assertResponse(200); - $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', array( + $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', [ '@file' => $this->image->getFilename(), '@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename() - )), 'Found upload error log entry.'); + ]), 'Found upload error log entry.'); } } diff --git a/core/modules/file/src/Tests/Views/RelationshipUserFileDataTest.php b/core/modules/file/src/Tests/Views/RelationshipUserFileDataTest.php index db49ae1e1dd..6a5f53b5d36 100644 --- a/core/modules/file/src/Tests/Views/RelationshipUserFileDataTest.php +++ b/core/modules/file/src/Tests/Views/RelationshipUserFileDataTest.php @@ -21,25 +21,25 @@ class RelationshipUserFileDataTest extends ViewTestBase { * * @var array */ - public static $modules = array('file', 'file_test_views', 'user'); + public static $modules = ['file', 'file_test_views', 'user']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_file_user_file_data'); + public static $testViews = ['test_file_user_file_data']; protected function setUp() { parent::setUp(); // Create the user profile field and instance. - FieldStorageConfig::create(array( + FieldStorageConfig::create([ 'entity_type' => 'user', 'field_name' => 'user_file', 'type' => 'file', 'translatable' => '0', - ))->save(); + ])->save(); FieldConfig::create([ 'label' => 'User File', 'description' => '', @@ -49,7 +49,7 @@ class RelationshipUserFileDataTest extends ViewTestBase { 'required' => 0, ])->save(); - ViewTestData::createTestViews(get_class($this), array('file_test_views')); + ViewTestData::createTestViews(get_class($this), ['file_test_views']); } /** @@ -84,12 +84,12 @@ class RelationshipUserFileDataTest extends ViewTestBase { ]; $this->assertIdentical($expected, $view->getDependencies()); $this->executeView($view); - $expected_result = array( - array( + $expected_result = [ + [ 'file_managed_user__user_file_fid' => '2', - ), - ); - $column_map = array('file_managed_user__user_file_fid' => 'file_managed_user__user_file_fid'); + ], + ]; + $column_map = ['file_managed_user__user_file_fid' => 'file_managed_user__user_file_fid']; $this->assertIdenticalResultset($view, $expected_result, $column_map); } diff --git a/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php b/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php index 760a4f4fd4e..9dc9d3595e6 100644 --- a/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php +++ b/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php @@ -36,7 +36,7 @@ class FileModuleTestForm extends FormBase { public function buildForm(array $form, FormStateInterface $form_state, $tree = TRUE, $extended = TRUE, $multiple = FALSE, $default_fids = NULL) { $form['#tree'] = (bool) $tree; - $form['nested']['file'] = array( + $form['nested']['file'] = [ '#type' => 'managed_file', '#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']), '#upload_location' => 'public://test', @@ -44,21 +44,21 @@ class FileModuleTestForm extends FormBase { '#extended' => (bool) $extended, '#size' => 13, '#multiple' => (bool) $multiple, - ); + ]; if ($default_fids) { $default_fids = explode(',', $default_fids); - $form['nested']['file']['#default_value'] = $extended ? array('fids' => $default_fids) : $default_fids; + $form['nested']['file']['#default_value'] = $extended ? ['fids' => $default_fids] : $default_fids; } - $form['textfield'] = array( + $form['textfield'] = [ '#type' => 'textfield', '#title' => $this->t('Type a value and ensure it stays'), - ); + ]; - $form['submit'] = array( + $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save'), - ); + ]; return $form; } @@ -68,7 +68,7 @@ class FileModuleTestForm extends FormBase { */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form['#tree']) { - $uploads = $form_state->getValue(array('nested', 'file')); + $uploads = $form_state->getValue(['nested', 'file']); } else { $uploads = $form_state->getValue('file'); @@ -78,12 +78,12 @@ class FileModuleTestForm extends FormBase { $uploads = $uploads['fids']; } - $fids = array(); + $fids = []; foreach ($uploads as $fid) { $fids[] = $fid; } - drupal_set_message($this->t('The file ids are %fids.', array('%fids' => implode(',', $fids)))); + drupal_set_message($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)])); } } diff --git a/core/modules/file/tests/file_test/file_test.module b/core/modules/file/tests/file_test/file_test.module index 4a6fbcbdbaf..0baa0cbd084 100644 --- a/core/modules/file/tests/file_test/file_test.module +++ b/core/modules/file/tests/file_test/file_test.module @@ -21,23 +21,23 @@ const FILE_URL_TEST_CDN_2 = 'http://cdn2.example.com'; */ function file_test_reset() { // Keep track of calls to these hooks - $results = array( - 'load' => array(), - 'validate' => array(), - 'download' => array(), - 'insert' => array(), - 'update' => array(), - 'copy' => array(), - 'move' => array(), - 'delete' => array(), - ); + $results = [ + 'load' => [], + 'validate' => [], + 'download' => [], + 'insert' => [], + 'update' => [], + 'copy' => [], + 'move' => [], + 'delete' => [], + ]; \Drupal::state()->set('file_test.results', $results); // These hooks will return these values, see file_test_set_return(). - $return = array( - 'validate' => array(), + $return = [ + 'validate' => [], 'download' => NULL, - ); + ]; \Drupal::state()->set('file_test.return', $return); } @@ -56,7 +56,7 @@ function file_test_reset() { * @see file_test_reset() */ function file_test_get_calls($op) { - $results = \Drupal::state()->get('file_test.results') ?: array(); + $results = \Drupal::state()->get('file_test.results') ?: []; return $results[$op]; } @@ -69,7 +69,7 @@ function file_test_get_calls($op) { * passed to each call. */ function file_test_get_all_calls() { - return \Drupal::state()->get('file_test.results') ?: array(); + return \Drupal::state()->get('file_test.results') ?: []; } /** @@ -86,7 +86,7 @@ function file_test_get_all_calls() { */ function _file_test_log_call($op, $args) { if (\Drupal::state()->get('file_test.count_hook_invocations', TRUE)) { - $results = \Drupal::state()->get('file_test.results') ?: array(); + $results = \Drupal::state()->get('file_test.results') ?: []; $results[$op][] = $args; \Drupal::state()->set('file_test.results', $results); } @@ -105,7 +105,7 @@ function _file_test_log_call($op, $args) { * @see file_test_reset() */ function _file_test_get_return($op) { - $return = \Drupal::state()->get('file_test.return') ?: array($op => NULL); + $return = \Drupal::state()->get('file_test.return') ?: [$op => NULL]; return $return[$op]; } @@ -121,7 +121,7 @@ function _file_test_get_return($op) { * @see file_test_reset() */ function file_test_set_return($op, $value) { - $return = \Drupal::state()->get('file_test.return') ?: array(); + $return = \Drupal::state()->get('file_test.return') ?: []; $return[$op] = $value; \Drupal::state()->set('file_test.return', $return); } @@ -131,7 +131,7 @@ function file_test_set_return($op, $value) { */ function file_test_file_load($files) { foreach ($files as $file) { - _file_test_log_call('load', array($file->id())); + _file_test_log_call('load', [$file->id()]); // Assign a value on the object so that we can test that the $file is passed // by reference. $file->file_test['loaded'] = TRUE; @@ -142,7 +142,7 @@ function file_test_file_load($files) { * Implements hook_file_validate(). */ function file_test_file_validate(File $file) { - _file_test_log_call('validate', array($file->id())); + _file_test_log_call('validate', [$file->id()]); return _file_test_get_return('validate'); } @@ -151,11 +151,11 @@ function file_test_file_validate(File $file) { */ function file_test_file_download($uri) { if (\Drupal::state()->get('file_test.allow_all', FALSE)) { - $files = entity_load_multiple_by_properties('file', array('uri' => $uri)); + $files = entity_load_multiple_by_properties('file', ['uri' => $uri]); $file = reset($files); return file_get_content_headers($file); } - _file_test_log_call('download', array($uri)); + _file_test_log_call('download', [$uri]); return _file_test_get_return('download'); } @@ -163,35 +163,35 @@ function file_test_file_download($uri) { * Implements hook_ENTITY_TYPE_insert() for file entities. */ function file_test_file_insert(File $file) { - _file_test_log_call('insert', array($file->id())); + _file_test_log_call('insert', [$file->id()]); } /** * Implements hook_ENTITY_TYPE_update() for file entities. */ function file_test_file_update(File $file) { - _file_test_log_call('update', array($file->id())); + _file_test_log_call('update', [$file->id()]); } /** * Implements hook_file_copy(). */ function file_test_file_copy(File $file, $source) { - _file_test_log_call('copy', array($file->id(), $source->id())); + _file_test_log_call('copy', [$file->id(), $source->id()]); } /** * Implements hook_file_move(). */ function file_test_file_move(File $file, File $source) { - _file_test_log_call('move', array($file->id(), $source->id())); + _file_test_log_call('move', [$file->id(), $source->id()]); } /** * Implements hook_ENTITY_TYPE_predelete() for file entities. */ function file_test_file_predelete(File $file) { - _file_test_log_call('delete', array($file->id())); + _file_test_log_call('delete', [$file->id()]); } /** @@ -206,11 +206,11 @@ function file_test_file_url_alter(&$uri) { } // Test alteration of file URLs to use a CDN. elseif ($alter_mode == 'cdn') { - $cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png'); + $cdn_extensions = ['css', 'js', 'gif', 'jpg', 'jpeg', 'png']; // Most CDNs don't support private file transfers without a lot of hassle, // so don't support this in the common case. - $schemes = array('public'); + $schemes = ['public']; $scheme = file_uri_scheme($uri); @@ -323,7 +323,7 @@ function file_test_validator(File $file, $errors) { * If $filepath is NULL, an array of all previous $filepath parameters */ function file_test_file_scan_callback($filepath = NULL) { - $files = &drupal_static(__FUNCTION__, array()); + $files = &drupal_static(__FUNCTION__, []); if (isset($filepath)) { $files[] = $filepath; } diff --git a/core/modules/file/tests/file_test/src/Form/FileTestForm.php b/core/modules/file/tests/file_test/src/Form/FileTestForm.php index 628bb55dba0..f43e20a8e90 100644 --- a/core/modules/file/tests/file_test/src/Form/FileTestForm.php +++ b/core/modules/file/tests/file_test/src/Form/FileTestForm.php @@ -21,48 +21,48 @@ class FileTestForm implements FormInterface { * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { - $form['file_test_upload'] = array( + $form['file_test_upload'] = [ '#type' => 'file', '#title' => t('Upload a file'), - ); - $form['file_test_replace'] = array( + ]; + $form['file_test_replace'] = [ '#type' => 'select', '#title' => t('Replace existing image'), - '#options' => array( + '#options' => [ FILE_EXISTS_RENAME => t('Appends number until name is unique'), FILE_EXISTS_REPLACE => t('Replace the existing file'), FILE_EXISTS_ERROR => t('Fail with an error'), - ), + ], '#default_value' => FILE_EXISTS_RENAME, - ); - $form['file_subdir'] = array( + ]; + $form['file_subdir'] = [ '#type' => 'textfield', '#title' => t('Subdirectory for test file'), '#default_value' => '', - ); + ]; - $form['extensions'] = array( + $form['extensions'] = [ '#type' => 'textfield', '#title' => t('Allowed extensions.'), '#default_value' => '', - ); + ]; - $form['allow_all_extensions'] = array( + $form['allow_all_extensions'] = [ '#type' => 'checkbox', '#title' => t('Allow all extensions?'), '#default_value' => FALSE, - ); + ]; - $form['is_image_file'] = array( + $form['is_image_file'] = [ '#type' => 'checkbox', '#title' => t('Is this an image file?'), '#default_value' => TRUE, - ); + ]; - $form['submit'] = array( + $form['submit'] = [ '#type' => 'submit', '#value' => t('Submit'), - ); + ]; return $form; } @@ -86,16 +86,16 @@ class FileTestForm implements FormInterface { } // Setup validators. - $validators = array(); + $validators = []; if ($form_state->getValue('is_image_file')) { - $validators['file_validate_is_image'] = array(); + $validators['file_validate_is_image'] = []; } if ($form_state->getValue('allow_all_extensions')) { - $validators['file_validate_extensions'] = array(); + $validators['file_validate_extensions'] = []; } elseif (!$form_state->isValueEmpty('extensions')) { - $validators['file_validate_extensions'] = array($form_state->getValue('extensions')); + $validators['file_validate_extensions'] = [$form_state->getValue('extensions')]; } // The test for drupal_move_uploaded_file() triggering a warning is @@ -108,9 +108,9 @@ class FileTestForm implements FormInterface { $file = file_save_upload('file_test_upload', $validators, $destination, 0, $form_state->getValue('file_test_replace')); if ($file) { $form_state->setValue('file_test_upload', $file); - drupal_set_message(t('File @filepath was uploaded.', array('@filepath' => $file->getFileUri()))); - drupal_set_message(t('File name is @filename.', array('@filename' => $file->getFilename()))); - drupal_set_message(t('File MIME type is @mimetype.', array('@mimetype' => $file->getMimeType()))); + drupal_set_message(t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()])); + drupal_set_message(t('File name is @filename.', ['@filename' => $file->getFilename()])); + drupal_set_message(t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()])); drupal_set_message(t('You WIN!')); } elseif ($file === FALSE) { diff --git a/core/modules/file/tests/src/Functional/FileFieldTestBase.php b/core/modules/file/tests/src/Functional/FileFieldTestBase.php index 9cc981bd46f..af3747bcc50 100644 --- a/core/modules/file/tests/src/Functional/FileFieldTestBase.php +++ b/core/modules/file/tests/src/Functional/FileFieldTestBase.php @@ -18,7 +18,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { * * @var array */ - public static $modules = array('node', 'file', 'file_module_test', 'field_ui'); + public static $modules = ['node', 'file', 'file_module_test', 'field_ui']; /** * An user with administration permissions. @@ -29,9 +29,9 @@ abstract class FileFieldTestBase extends BrowserTestBase { protected function setUp() { parent::setUp(); - $this->adminUser = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access')); + $this->adminUser = $this->drupalCreateUser(['access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access']); $this->drupalLogin($this->adminUser); - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); } /** @@ -73,14 +73,14 @@ abstract class FileFieldTestBase extends BrowserTestBase { * @param array $widget_settings * A list of widget settings that will be added to the widget defaults. */ - function createFileField($name, $entity_type, $bundle, $storage_settings = array(), $field_settings = array(), $widget_settings = array()) { - $field_storage = FieldStorageConfig::create(array( + function createFileField($name, $entity_type, $bundle, $storage_settings = [], $field_settings = [], $widget_settings = []) { + $field_storage = FieldStorageConfig::create([ 'entity_type' => $entity_type, 'field_name' => $name, 'type' => 'file', 'settings' => $storage_settings, 'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1, - )); + ]); $field_storage->save(); $this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings); @@ -101,44 +101,44 @@ abstract class FileFieldTestBase extends BrowserTestBase { * @param array $widget_settings * A list of widget settings that will be added to the widget defaults. */ - function attachFileField($name, $entity_type, $bundle, $field_settings = array(), $widget_settings = array()) { - $field = array( + function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) { + $field = [ 'field_name' => $name, 'label' => $name, 'entity_type' => $entity_type, 'bundle' => $bundle, 'required' => !empty($field_settings['required']), 'settings' => $field_settings, - ); + ]; FieldConfig::create($field)->save(); entity_get_form_display($entity_type, $bundle, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'type' => 'file_generic', 'settings' => $widget_settings, - )) + ]) ->save(); // Assign display settings. entity_get_display($entity_type, $bundle, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'label' => 'hidden', 'type' => 'file_default', - )) + ]) ->save(); } /** * Updates an existing file field with new settings. */ - function updateFileField($name, $type_name, $field_settings = array(), $widget_settings = array()) { + function updateFileField($name, $type_name, $field_settings = [], $widget_settings = []) { $field = FieldConfig::loadByName('node', $type_name, $name); $field->setSettings(array_merge($field->getSettings(), $field_settings)); $field->save(); entity_get_form_display('node', $type_name, 'default') - ->setComponent($name, array( + ->setComponent($name, [ 'settings' => $widget_settings, - )) + ]) ->save(); } @@ -160,7 +160,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { * @return int * The node id. */ - function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) { + function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) { return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras); } @@ -182,16 +182,16 @@ abstract class FileFieldTestBase extends BrowserTestBase { * @return int * The node id. */ - function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) { - $edit = array( + function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) { + $edit = [ 'title[0][value]' => $this->randomMachineName(), 'revision' => (string) (int) $new_revision, - ); + ]; $node_storage = $this->container->get('entity.manager')->getStorage('node'); if (is_numeric($nid_or_type)) { $nid = $nid_or_type; - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); } else { @@ -202,7 +202,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { // Save at least one revision to better simulate a real site. $node->setNewRevision(); $node->save(); - $node_storage->resetCache(array($nid)); + $node_storage->resetCache([$nid]); $node = $node_storage->load($nid); $this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.'); } @@ -235,11 +235,11 @@ abstract class FileFieldTestBase extends BrowserTestBase { * Note that if replacing a file, it must first be removed then added again. */ function removeNodeFile($nid, $new_revision = TRUE) { - $edit = array( + $edit = [ 'revision' => (string) (int) $new_revision, - ); + ]; - $this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove')); + $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove')); $this->drupalPostForm(NULL, $edit, t('Save and keep published')); } @@ -247,12 +247,12 @@ abstract class FileFieldTestBase extends BrowserTestBase { * Replaces a file within a node. */ function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) { - $edit = array( + $edit = [ 'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()), 'revision' => (string) (int) $new_revision, - ); + ]; - $this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove')); + $this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove')); $this->drupalPostForm(NULL, $edit, t('Save and keep published')); } @@ -268,7 +268,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { * (optional) A message to display with the assertion. */ public static function assertFileExists($file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]); $filename = $file instanceof FileInterface ? $file->getFileUri() : $file; parent::assertFileExists($filename, $message); } @@ -279,7 +279,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { function assertFileEntryExists($file, $message = NULL) { $this->container->get('entity.manager')->getStorage('file')->resetCache(); $db_file = File::load($file->id()); - $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]); $this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message); } @@ -295,7 +295,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { * (optional) A message to display with the assertion. */ public static function assertFileNotExists($file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]); $filename = $file instanceof FileInterface ? $file->getFileUri() : $file; parent::assertFileNotExists($filename, $message); } @@ -305,7 +305,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { */ function assertFileEntryNotExists($file, $message) { $this->container->get('entity.manager')->getStorage('file')->resetCache(); - $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]); $this->assertFalse(File::load($file->id()), $message); } @@ -313,7 +313,7 @@ abstract class FileFieldTestBase extends BrowserTestBase { * Asserts that a file's status is set to permanent in the database. */ function assertFileIsPermanent(FileInterface $file, $message = NULL) { - $message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->getFileUri())); + $message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]); $this->assertTrue($file->isPermanent(), $message); } diff --git a/core/modules/file/tests/src/Functional/FileManagedAccessTest.php b/core/modules/file/tests/src/Functional/FileManagedAccessTest.php index 97f77b6837c..fc6d85cb36c 100644 --- a/core/modules/file/tests/src/Functional/FileManagedAccessTest.php +++ b/core/modules/file/tests/src/Functional/FileManagedAccessTest.php @@ -16,20 +16,20 @@ class FileManagedAccessTest extends FileManagedTestBase { */ function testFileAccess() { // Create a new file entity. - $file = File::create(array( + $file = File::create([ 'uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'public://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, - )); + ]); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); // Create authenticated user to check file access. - $account = $this->createUser(array('access site reports')); + $account = $this->createUser(['access site reports']); $this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user'); $this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user'); @@ -41,20 +41,20 @@ class FileManagedAccessTest extends FileManagedTestBase { $this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user'); // Create a new file entity. - $file = File::create(array( + $file = File::create([ 'uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'private://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, - )); + ]); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); // Create authenticated user to check file access. - $account = $this->createUser(array('access site reports')); + $account = $this->createUser(['access site reports']); $this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user'); $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user'); diff --git a/core/modules/file/tests/src/Functional/FileManagedTestBase.php b/core/modules/file/tests/src/Functional/FileManagedTestBase.php index 6bd57dd39c6..0adbe2c36b4 100644 --- a/core/modules/file/tests/src/Functional/FileManagedTestBase.php +++ b/core/modules/file/tests/src/Functional/FileManagedTestBase.php @@ -17,7 +17,7 @@ abstract class FileManagedTestBase extends BrowserTestBase { * * @var array */ - public static $modules = array('file_test', 'file'); + public static $modules = ['file_test', 'file']; protected function setUp() { parent::setUp(); @@ -42,16 +42,16 @@ abstract class FileManagedTestBase extends BrowserTestBase { // Determine if there were any expected that were not called. $uncalled = array_diff($expected, $actual); if (count($uncalled)) { - $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)))); + $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)])); } else { - $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? '(none)' : implode(', ', $expected)))); + $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%expected' => empty($expected) ? '(none)' : implode(', ', $expected)])); } // Determine if there were any unexpected calls. $unexpected = array_diff($actual, $expected); if (count($unexpected)) { - $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)))); + $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)])); } else { $this->assertTrue(TRUE, 'No unexpected hooks were called.'); @@ -73,13 +73,13 @@ abstract class FileManagedTestBase extends BrowserTestBase { if (!isset($message)) { if ($actual_count == $expected_count) { - $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook)); + $message = format_string('hook_file_@name was called correctly.', ['@name' => $hook]); } elseif ($expected_count == 0) { - $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count)); + $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', ['@name' => $hook, '@count' => $actual_count]); } else { - $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count)); + $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]); } } $this->assertEqual($actual_count, $expected_count, $message); @@ -94,13 +94,13 @@ abstract class FileManagedTestBase extends BrowserTestBase { * File object to compare. */ function assertFileUnchanged(FileInterface $before, FileInterface $after) { - $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', array('%file1' => $before->id(), '%file2' => $after->id())), 'File unchanged'); - $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', array('%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id())), 'File unchanged'); - $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', array('%file1' => $before->getFilename(), '%file2' => $after->getFilename())), 'File unchanged'); - $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', array('%file1' => $before->getFileUri(), '%file2' => $after->getFileUri())), 'File unchanged'); - $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->getMimeType(), '%file2' => $after->getMimeType())), 'File unchanged'); - $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', array('%file1' => $before->getSize(), '%file2' => $after->getSize())), 'File unchanged'); - $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', array('%file1' => $before->isPermanent(), '%file2' => $after->isPermanent())), 'File unchanged'); + $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged'); + $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', ['%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id()]), 'File unchanged'); + $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged'); + $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged'); + $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged'); + $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged'); + $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%file1' => $before->isPermanent(), '%file2' => $after->isPermanent()]), 'File unchanged'); } /** @@ -112,8 +112,8 @@ abstract class FileManagedTestBase extends BrowserTestBase { * File object to compare. */ function assertDifferentFile(FileInterface $file1, FileInterface $file2) { - $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->id(), '%file2' => $file2->id())), 'Different file'); - $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Different file'); + $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file'); + $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Different file'); } /** @@ -125,8 +125,8 @@ abstract class FileManagedTestBase extends BrowserTestBase { * File object to compare. */ function assertSameFile(FileInterface $file1, FileInterface $file2) { - $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->id(), '%file2-fid' => $file2->id())), 'Same file'); - $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Same file'); + $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file'); + $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Same file'); } /** diff --git a/core/modules/file/tests/src/Kernel/AccessTest.php b/core/modules/file/tests/src/Kernel/AccessTest.php index c2fa65bacb0..c71d7e80e75 100644 --- a/core/modules/file/tests/src/Kernel/AccessTest.php +++ b/core/modules/file/tests/src/Kernel/AccessTest.php @@ -49,7 +49,7 @@ class AccessTest extends KernelTestBase { $this->installEntitySchema('file'); $this->installEntitySchema('user'); - $this->installSchema('file', array('file_usage')); + $this->installSchema('file', ['file_usage']); $this->installSchema('system', 'sequences'); $this->user1 = User::create([ @@ -64,11 +64,11 @@ class AccessTest extends KernelTestBase { ]); $this->user2->save(); - $this->file = File::create(array( + $this->file = File::create([ 'uid' => $this->user1->id(), 'filename' => 'druplicon.txt', 'filemime' => 'text/plain', - )); + ]); } /** diff --git a/core/modules/file/tests/src/Kernel/CopyTest.php b/core/modules/file/tests/src/Kernel/CopyTest.php index 8836bd48420..4c8d41fbec4 100644 --- a/core/modules/file/tests/src/Kernel/CopyTest.php +++ b/core/modules/file/tests/src/Kernel/CopyTest.php @@ -27,7 +27,7 @@ class CopyTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file were copied correctly.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('copy', 'insert')); + $this->assertFileHooksCalled(['copy', 'insert']); $this->assertDifferentFile($source, $result); $this->assertEqual($result->getFileUri(), $desired_uri, 'The copied file entity has the desired filepath.'); @@ -59,7 +59,7 @@ class CopyTest extends FileManagedUnitTestBase { $this->assertNotEqual($result->getFileUri(), $source->getFileUri(), 'Returned file path has changed from the original.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('copy', 'insert')); + $this->assertFileHooksCalled(['copy', 'insert']); // Load all the affected files to check the changes that actually made it // to the database. @@ -99,7 +99,7 @@ class CopyTest extends FileManagedUnitTestBase { $this->assertDifferentFile($source, $result); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('load', 'copy', 'update')); + $this->assertFileHooksCalled(['load', 'copy', 'update']); // Load all the affected files to check the changes that actually made it // to the database. @@ -136,7 +136,7 @@ class CopyTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); $this->assertFileUnchanged($source, File::load($source->id())); $this->assertFileUnchanged($target, File::load($target->id())); diff --git a/core/modules/file/tests/src/Kernel/DeleteTest.php b/core/modules/file/tests/src/Kernel/DeleteTest.php index b88057121d2..6d992a5423d 100644 --- a/core/modules/file/tests/src/Kernel/DeleteTest.php +++ b/core/modules/file/tests/src/Kernel/DeleteTest.php @@ -19,7 +19,7 @@ class DeleteTest extends FileManagedUnitTestBase { // Check that deletion removes the file and database record. $this->assertTrue(is_file($file->getFileUri()), 'File exists.'); $file->delete(); - $this->assertFileHooksCalled(array('delete')); + $this->assertFileHooksCalled(['delete']); $this->assertFalse(file_exists($file->getFileUri()), 'Test file has actually been deleted.'); $this->assertFalse(File::load($file->id()), 'File was removed from the database.'); } @@ -35,7 +35,7 @@ class DeleteTest extends FileManagedUnitTestBase { $file_usage->delete($file, 'testing', 'test', 1); $usage = $file_usage->listUsage($file); - $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.'); + $this->assertEqual($usage['testing']['test'], [1 => 1], 'Test file is still in use.'); $this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.'); $this->assertTrue(File::load($file->id()), 'File still exists in the database.'); @@ -44,7 +44,7 @@ class DeleteTest extends FileManagedUnitTestBase { $file_usage->delete($file, 'testing', 'test', 1); $usage = $file_usage->listUsage($file); - $this->assertFileHooksCalled(array('load', 'update')); + $this->assertFileHooksCalled(['load', 'update']); $this->assertTrue(empty($usage), 'File usage data was removed.'); $this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.'); $file = File::load($file->id()); @@ -56,15 +56,15 @@ class DeleteTest extends FileManagedUnitTestBase { // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed') - ->fields(array( + ->fields([ 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), - )) + ]) ->condition('fid', $file->id()) ->execute(); \Drupal::service('cron')->run(); // file_cron() loads - $this->assertFileHooksCalled(array('delete')); + $this->assertFileHooksCalled(['delete']); $this->assertFalse(file_exists($file->getFileUri()), 'File has been deleted after its last usage was removed.'); $this->assertFalse(File::load($file->id()), 'File was removed from the database.'); } diff --git a/core/modules/file/tests/src/Kernel/FileItemTest.php b/core/modules/file/tests/src/Kernel/FileItemTest.php index 747d5da703e..8219af15d9c 100644 --- a/core/modules/file/tests/src/Kernel/FileItemTest.php +++ b/core/modules/file/tests/src/Kernel/FileItemTest.php @@ -23,7 +23,7 @@ class FileItemTest extends FieldKernelTestBase { * * @var array */ - public static $modules = array('file'); + public static $modules = ['file']; /** * Created file entity. @@ -43,20 +43,20 @@ class FileItemTest extends FieldKernelTestBase { parent::setUp(); $this->installEntitySchema('file'); - $this->installSchema('file', array('file_usage')); + $this->installSchema('file', ['file_usage']); - FieldStorageConfig::create(array( + FieldStorageConfig::create([ 'field_name' => 'file_test', 'entity_type' => 'entity_test', 'type' => 'file', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, - ))->save(); + ])->save(); $this->directory = $this->getRandomGenerator()->name(8); FieldConfig::create([ 'entity_type' => 'entity_test', 'field_name' => 'file_test', 'bundle' => 'entity_test', - 'settings' => array('file_directory' => $this->directory), + 'settings' => ['file_directory' => $this->directory], ])->save(); file_put_contents('public://example.txt', $this->randomMachineName()); $this->file = File::create([ @@ -131,7 +131,7 @@ class FileItemTest extends FieldKernelTestBase { 'weight' => 1, ])->save(); $entity = EntityTest::create(); - $entity->file_test = array('entity' => $file3); + $entity->file_test = ['entity' => $file3]; $uri = $file3->getFileUri(); $output = entity_view($entity, 'default'); \Drupal::service('renderer')->renderRoot($output); diff --git a/core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php b/core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php index 4db377ded9b..3035b7cb218 100644 --- a/core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php +++ b/core/modules/file/tests/src/Kernel/FileManagedUnitTestBase.php @@ -18,17 +18,17 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { * * @var array */ - public static $modules = array('file_test', 'file', 'system', 'field', 'user'); + public static $modules = ['file_test', 'file', 'system', 'field', 'user']; protected function setUp() { parent::setUp(); // Clear out any hook calls. file_test_reset(); - $this->installConfig(array('system')); + $this->installConfig(['system']); $this->installEntitySchema('file'); $this->installEntitySchema('user'); - $this->installSchema('file', array('file_usage')); + $this->installSchema('file', ['file_usage']); // Make sure that a user with uid 1 exists, self::createFile() relies on // it. @@ -55,16 +55,16 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { // Determine if there were any expected that were not called. $uncalled = array_diff($expected, $actual); if (count($uncalled)) { - $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)))); + $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)])); } else { - $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? '(none)' : implode(', ', $expected)))); + $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', ['%expected' => empty($expected) ? '(none)' : implode(', ', $expected)])); } // Determine if there were any unexpected calls. $unexpected = array_diff($actual, $expected); if (count($unexpected)) { - $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)))); + $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)])); } else { $this->assertTrue(TRUE, 'No unexpected hooks were called.'); @@ -86,13 +86,13 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { if (!isset($message)) { if ($actual_count == $expected_count) { - $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook)); + $message = format_string('hook_file_@name was called correctly.', ['@name' => $hook]); } elseif ($expected_count == 0) { - $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count)); + $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', ['@name' => $hook, '@count' => $actual_count]); } else { - $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count)); + $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]); } } $this->assertEqual($actual_count, $expected_count, $message); @@ -107,13 +107,13 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { * File object to compare. */ function assertFileUnchanged(FileInterface $before, FileInterface $after) { - $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', array('%file1' => $before->id(), '%file2' => $after->id())), 'File unchanged'); - $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', array('%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id())), 'File unchanged'); - $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', array('%file1' => $before->getFilename(), '%file2' => $after->getFilename())), 'File unchanged'); - $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', array('%file1' => $before->getFileUri(), '%file2' => $after->getFileUri())), 'File unchanged'); - $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->getMimeType(), '%file2' => $after->getMimeType())), 'File unchanged'); - $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', array('%file1' => $before->getSize(), '%file2' => $after->getSize())), 'File unchanged'); - $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', array('%file1' => $before->isPermanent(), '%file2' => $after->isPermanent())), 'File unchanged'); + $this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', ['%file1' => $before->id(), '%file2' => $after->id()]), 'File unchanged'); + $this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', ['%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id()]), 'File unchanged'); + $this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', ['%file1' => $before->getFilename(), '%file2' => $after->getFilename()]), 'File unchanged'); + $this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', ['%file1' => $before->getFileUri(), '%file2' => $after->getFileUri()]), 'File unchanged'); + $this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', ['%file1' => $before->getMimeType(), '%file2' => $after->getMimeType()]), 'File unchanged'); + $this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', ['%file1' => $before->getSize(), '%file2' => $after->getSize()]), 'File unchanged'); + $this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', ['%file1' => $before->isPermanent(), '%file2' => $after->isPermanent()]), 'File unchanged'); } /** @@ -125,8 +125,8 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { * File object to compare. */ function assertDifferentFile(FileInterface $file1, FileInterface $file2) { - $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->id(), '%file2' => $file2->id())), 'Different file'); - $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Different file'); + $this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', ['%file1' => $file1->id(), '%file2' => $file2->id()]), 'Different file'); + $this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Different file'); } /** @@ -138,8 +138,8 @@ abstract class FileManagedUnitTestBase extends KernelTestBase { * File object to compare. */ function assertSameFile(FileInterface $file1, FileInterface $file2) { - $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->id(), '%file2-fid' => $file2->id())), 'Same file'); - $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Same file'); + $this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', ['%file1' => $file1->id(), '%file2-fid' => $file2->id()]), 'Same file'); + $this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', ['%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri()]), 'Same file'); } /** diff --git a/core/modules/file/tests/src/Kernel/LoadTest.php b/core/modules/file/tests/src/Kernel/LoadTest.php index c523d43bfda..8cbaccc2c90 100644 --- a/core/modules/file/tests/src/Kernel/LoadTest.php +++ b/core/modules/file/tests/src/Kernel/LoadTest.php @@ -15,25 +15,25 @@ class LoadTest extends FileManagedUnitTestBase { */ function testLoadMissingFid() { $this->assertFalse(File::load(-1), 'Try to load an invalid fid fails.'); - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); } /** * Try to load a non-existent file by URI. */ function testLoadMissingFilepath() { - $files = entity_load_multiple_by_properties('file', array('uri' => 'foobar://misc/druplicon.png')); + $files = entity_load_multiple_by_properties('file', ['uri' => 'foobar://misc/druplicon.png']); $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails."); - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); } /** * Try to load a non-existent file by status. */ function testLoadInvalidStatus() { - $files = entity_load_multiple_by_properties('file', array('status' => -99)); + $files = entity_load_multiple_by_properties('file', ['status' => -99]); $this->assertFalse(reset($files), 'Trying to load a file with an invalid status fails.'); - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); } /** @@ -62,7 +62,7 @@ class LoadTest extends FileManagedUnitTestBase { // Load by path. file_test_reset(); - $by_path_files = entity_load_multiple_by_properties('file', array('uri' => $file->getFileUri())); + $by_path_files = entity_load_multiple_by_properties('file', ['uri' => $file->getFileUri()]); $this->assertFileHookCalled('load'); $this->assertEqual(1, count($by_path_files), 'entity_load_multiple_by_properties() returned an array of the correct size.'); $by_path_file = reset($by_path_files); @@ -71,8 +71,8 @@ class LoadTest extends FileManagedUnitTestBase { // Load by fid. file_test_reset(); - $by_fid_files = File::loadMultiple(array($file->id())); - $this->assertFileHooksCalled(array()); + $by_fid_files = File::loadMultiple([$file->id()]); + $this->assertFileHooksCalled([]); $this->assertEqual(1, count($by_fid_files), '\Drupal\file\Entity\File::loadMultiple() returned an array of the correct size.'); $by_fid_file = reset($by_fid_files); $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.'); diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateFileTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateFileTest.php index 7e1cff91b5b..024db2136e3 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateFileTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateFileTest.php @@ -79,12 +79,12 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter // Update the file_directory_path. Database::getConnection('default', 'migrate') ->update('variable') - ->fields(array('value' => serialize('files/test'))) + ->fields(['value' => serialize('files/test')]) ->condition('name', 'file_directory_path') ->execute(); Database::getConnection('default', 'migrate') ->update('variable') - ->fields(array('value' => serialize(file_directory_temp()))) + ->fields(['value' => serialize(file_directory_temp())]) ->condition('name', 'file_directory_temp') ->execute(); @@ -122,10 +122,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter $db->update('files') ->condition('fid', 6) - ->fields(array( + ->fields([ 'filename' => static::$tempFilename, 'filepath' => $file_path, - )) + ]) ->execute(); $file = (array) $db->select('files') diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityDisplayTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityDisplayTest.php index a813b93cc76..c3b71ad4263 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityDisplayTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityDisplayTest.php @@ -38,7 +38,7 @@ class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase { $component = $display->getComponent('upload'); $this->assertTrue(is_null($component)); - $this->assertIdentical(array('node', 'page', 'default', 'upload'), $this->getMigration('d6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page'))); + $this->assertIdentical(['node', 'page', 'default', 'upload'], $this->getMigration('d6_upload_entity_display')->getIdMap()->lookupDestinationID(['page'])); } } diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityFormDisplayTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityFormDisplayTest.php index de0acbfd400..e9782aa9049 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityFormDisplayTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadEntityFormDisplayTest.php @@ -38,7 +38,7 @@ class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase { $component = $display->getComponent('upload'); $this->assertTrue(is_null($component)); - $this->assertIdentical(array('node', 'page', 'default', 'upload'), $this->getMigration('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page'))); + $this->assertIdentical(['node', 'page', 'default', 'upload'], $this->getMigration('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(['page'])); } } diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadFieldTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadFieldTest.php index 9d5c711d58b..918d6f3c55e 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadFieldTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadFieldTest.php @@ -26,7 +26,7 @@ class MigrateUploadFieldTest extends MigrateDrupal6TestBase { public function testUpload() { $field_storage = FieldStorageConfig::load('node.upload'); $this->assertIdentical('node.upload', $field_storage->id()); - $this->assertIdentical(array('node', 'upload'), $this->getMigration('d6_upload_field')->getIdMap()->lookupDestinationID(array(''))); + $this->assertIdentical(['node', 'upload'], $this->getMigration('d6_upload_field')->getIdMap()->lookupDestinationID([''])); } } diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadInstanceTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadInstanceTest.php index a835006afdf..18c4a71bcf4 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadInstanceTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadInstanceTest.php @@ -38,7 +38,7 @@ class MigrateUploadInstanceTest extends MigrateDrupal6TestBase { $field = FieldConfig::load('node.article.upload'); $this->assertTrue(is_null($field)); - $this->assertIdentical(array('node', 'page', 'upload'), $this->getMigration('d6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page'))); + $this->assertIdentical(['node', 'page', 'upload'], $this->getMigration('d6_upload_field_instance')->getIdMap()->lookupDestinationID(['page'])); } } diff --git a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadTest.php b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadTest.php index 463ce022d80..2ab104dae34 100644 --- a/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadTest.php +++ b/core/modules/file/tests/src/Kernel/Migrate/d6/MigrateUploadTest.php @@ -24,10 +24,10 @@ class MigrateUploadTest extends MigrateDrupal6TestBase { $this->installSchema('file', ['file_usage']); $this->installSchema('node', ['node_access']); - $id_mappings = array('d6_file' => array()); + $id_mappings = ['d6_file' => []]; // Create new file entities. for ($i = 1; $i <= 3; $i++) { - $file = File::create(array( + $file = File::create([ 'fid' => $i, 'uid' => 1, 'filename' => 'druplicon.txt', @@ -36,13 +36,13 @@ class MigrateUploadTest extends MigrateDrupal6TestBase { 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT, - )); + ]); $file->enforceIsNew(); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); - $id_mappings['d6_file'][] = array(array($i), array($i)); + $id_mappings['d6_file'][] = [[$i], [$i]]; } $this->prepareMigrations($id_mappings); diff --git a/core/modules/file/tests/src/Kernel/MoveTest.php b/core/modules/file/tests/src/Kernel/MoveTest.php index a56caeaecea..f2f10342827 100644 --- a/core/modules/file/tests/src/Kernel/MoveTest.php +++ b/core/modules/file/tests/src/Kernel/MoveTest.php @@ -28,10 +28,10 @@ class MoveTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file correctly written.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('move', 'load', 'update')); + $this->assertFileHooksCalled(['move', 'load', 'update']); // Make sure we got the same file back. - $this->assertEqual($source->id(), $result->id(), format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->id()))); + $this->assertEqual($source->id(), $result->id(), format_string("Source file id's' %fid is unchanged after move.", ['%fid' => $source->id()])); // Reload the file from the database and check that the changes were // actually saved. @@ -60,7 +60,7 @@ class MoveTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of file correctly written.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('move', 'load', 'update')); + $this->assertFileHooksCalled(['move', 'load', 'update']); // Compare the returned value to what made it into the database. $this->assertFileUnchanged($result, File::load($result->id())); @@ -95,7 +95,7 @@ class MoveTest extends FileManagedUnitTestBase { $this->assertTrue($result, 'File moved successfully.'); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load')); + $this->assertFileHooksCalled(['move', 'update', 'delete', 'load']); // Reload the file from the database and check that the changes were // actually saved. @@ -122,7 +122,7 @@ class MoveTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($source->getFileUri()), 'Contents of file were not altered.'); // Check that no hooks were called while failing. - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); // Load the file from the database and make sure it is identical to what // was returned. @@ -149,7 +149,7 @@ class MoveTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.'); // Check that no hooks were called while failing. - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); // Load the file from the database and make sure it is identical to what // was returned. diff --git a/core/modules/file/tests/src/Kernel/SaveDataTest.php b/core/modules/file/tests/src/Kernel/SaveDataTest.php index c5637d08d37..f92ef9a5cb7 100644 --- a/core/modules/file/tests/src/Kernel/SaveDataTest.php +++ b/core/modules/file/tests/src/Kernel/SaveDataTest.php @@ -26,7 +26,7 @@ class SaveDataTest extends FileManagedUnitTestBase { $this->assertTrue($result->isPermanent(), "The file's status was set to permanent."); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('insert')); + $this->assertFileHooksCalled(['insert']); // Verify that what was returned is what's in the database. $this->assertFileUnchanged($result, File::load($result->id())); @@ -51,7 +51,7 @@ class SaveDataTest extends FileManagedUnitTestBase { $this->assertTrue($result->isPermanent(), "The file's status was set to permanent."); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('insert')); + $this->assertFileHooksCalled(['insert']); // Verify that what was returned is what's in the database. $this->assertFileUnchanged($result, File::load($result->id())); @@ -75,7 +75,7 @@ class SaveDataTest extends FileManagedUnitTestBase { $this->assertTrue($result->isPermanent(), "The file's status was set to permanent."); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('insert')); + $this->assertFileHooksCalled(['insert']); // Ensure that the existing file wasn't overwritten. $this->assertDifferentFile($existing, $result); @@ -103,7 +103,7 @@ class SaveDataTest extends FileManagedUnitTestBase { $this->assertTrue($result->isPermanent(), "The file's status was set to permanent."); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('load', 'update')); + $this->assertFileHooksCalled(['load', 'update']); // Verify that the existing file was re-used. $this->assertSameFile($existing, $result); @@ -125,7 +125,7 @@ class SaveDataTest extends FileManagedUnitTestBase { $this->assertEqual($contents, file_get_contents($existing->getFileUri()), 'Contents of existing file were unchanged.'); // Check that no hooks were called while failing. - $this->assertFileHooksCalled(array()); + $this->assertFileHooksCalled([]); // Ensure that the existing file wasn't overwritten. $this->assertFileUnchanged($existing, File::load($existing->id())); diff --git a/core/modules/file/tests/src/Kernel/SaveTest.php b/core/modules/file/tests/src/Kernel/SaveTest.php index 69c7f2b7afd..8d91d81aa99 100644 --- a/core/modules/file/tests/src/Kernel/SaveTest.php +++ b/core/modules/file/tests/src/Kernel/SaveTest.php @@ -12,20 +12,20 @@ use Drupal\file\Entity\File; class SaveTest extends FileManagedUnitTestBase { function testFileSave() { // Create a new file entity. - $file = File::create(array( + $file = File::create([ 'uid' => 1, 'filename' => 'druplicon.txt', 'uri' => 'public://druplicon.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, - )); + ]); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('insert')); + $this->assertFileHooksCalled(['insert']); $this->assertTrue($file->id() > 0, 'A new file ID is set when saving a new file to the database.', 'File'); $loaded_file = File::load($file->id()); @@ -41,7 +41,7 @@ class SaveTest extends FileManagedUnitTestBase { $file->save(); // Check that the correct hooks were called. - $this->assertFileHooksCalled(array('load', 'update')); + $this->assertFileHooksCalled(['load', 'update']); $this->assertEqual($file->id(), $file->id(), 'The file ID of an existing file is not changed when updating the database.', 'File'); $this->assertTrue($file->getChangedTime() >= $file->getChangedTime(), "Timestamp didn't go backwards.", 'File'); @@ -52,13 +52,13 @@ class SaveTest extends FileManagedUnitTestBase { // Try to insert a second file with the same name apart from case insensitivity // to ensure the 'uri' index allows for filenames with different cases. - $uppercase_values = array( + $uppercase_values = [ 'uid' => 1, 'filename' => 'DRUPLICON.txt', 'uri' => 'public://DRUPLICON.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, - ); + ]; $uppercase_file = File::create($uppercase_values); file_put_contents($uppercase_file->getFileUri(), 'hello world'); $violations = $uppercase_file->validate(); @@ -79,7 +79,7 @@ class SaveTest extends FileManagedUnitTestBase { ->execute(); $this->assertEqual(1, count($fids)); - $this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids); + $this->assertEqual([$uppercase_file->id() => $uppercase_file->id()], $fids); } diff --git a/core/modules/file/tests/src/Kernel/UsageTest.php b/core/modules/file/tests/src/Kernel/UsageTest.php index 8e2601510b8..6752247d941 100644 --- a/core/modules/file/tests/src/Kernel/UsageTest.php +++ b/core/modules/file/tests/src/Kernel/UsageTest.php @@ -21,22 +21,22 @@ class UsageTest extends FileManagedUnitTestBase { function testGetUsage() { $file = $this->createFile(); db_insert('file_usage') - ->fields(array( + ->fields([ 'fid' => $file->id(), 'module' => 'testing', 'type' => 'foo', 'id' => 1, 'count' => 1 - )) + ]) ->execute(); db_insert('file_usage') - ->fields(array( + ->fields([ 'fid' => $file->id(), 'module' => 'testing', 'type' => 'bar', 'id' => 2, 'count' => 2 - )) + ]) ->execute(); $usage = $this->container->get('file.usage')->listUsage($file); @@ -81,19 +81,19 @@ class UsageTest extends FileManagedUnitTestBase { $file = $this->createFile(); $file_usage = $this->container->get('file.usage'); db_insert('file_usage') - ->fields(array( + ->fields([ 'fid' => $file->id(), 'module' => 'testing', 'type' => 'bar', 'id' => 2, 'count' => 3, - )) + ]) ->execute(); // Normal decrement. $file_usage->delete($file, 'testing', 'bar', 2); $count = db_select('file_usage', 'f') - ->fields('f', array('count')) + ->fields('f', ['count']) ->condition('f.fid', $file->id()) ->execute() ->fetchField(); @@ -102,7 +102,7 @@ class UsageTest extends FileManagedUnitTestBase { // Multiple decrement and removal. $file_usage->delete($file, 'testing', 'bar', 2, 2); $count = db_select('file_usage', 'f') - ->fields('f', array('count')) + ->fields('f', ['count']) ->condition('f.fid', $file->id()) ->execute() ->fetchField(); @@ -111,7 +111,7 @@ class UsageTest extends FileManagedUnitTestBase { // Non-existent decrement. $file_usage->delete($file, 'testing', 'bar', 2); $count = db_select('file_usage', 'f') - ->fields('f', array('count')) + ->fields('f', ['count']) ->condition('f.fid', $file->id()) ->execute() ->fetchField(); @@ -128,10 +128,10 @@ class UsageTest extends FileManagedUnitTestBase { // Temporary file that is old. $temp_old = file_save_data(''); db_update('file_managed') - ->fields(array( + ->fields([ 'status' => 0, 'changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1, - )) + ]) ->condition('fid', $temp_old->id()) ->execute(); $this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was created correctly.'); @@ -139,7 +139,7 @@ class UsageTest extends FileManagedUnitTestBase { // Temporary file that is new. $temp_new = file_save_data(''); db_update('file_managed') - ->fields(array('status' => 0)) + ->fields(['status' => 0]) ->condition('fid', $temp_new->id()) ->execute(); $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was created correctly.'); @@ -147,7 +147,7 @@ class UsageTest extends FileManagedUnitTestBase { // Permanent file that is old. $perm_old = file_save_data(''); db_update('file_managed') - ->fields(array('changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1)) + ->fields(['changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1]) ->condition('fid', $temp_old->id()) ->execute(); $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was created correctly.'); @@ -155,7 +155,7 @@ class UsageTest extends FileManagedUnitTestBase { // Permanent file that is new. $perm_new = file_save_data(''); $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was created correctly.'); - return array($temp_old, $temp_new, $perm_old, $perm_new); + return [$temp_old, $temp_new, $perm_old, $perm_new]; } /** diff --git a/core/modules/file/tests/src/Kernel/ValidateTest.php b/core/modules/file/tests/src/Kernel/ValidateTest.php index 0bfcfddd43e..2fc88176a7c 100644 --- a/core/modules/file/tests/src/Kernel/ValidateTest.php +++ b/core/modules/file/tests/src/Kernel/ValidateTest.php @@ -16,23 +16,23 @@ class ValidateTest extends FileManagedUnitTestBase { $file = $this->createFile(); // Empty validators. - $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.'); - $this->assertFileHooksCalled(array('validate')); + $this->assertEqual(file_validate($file, []), [], 'Validating an empty array works successfully.'); + $this->assertFileHooksCalled(['validate']); // Use the file_test.module's test validator to ensure that passing tests // return correctly. file_test_reset(); - file_test_set_return('validate', array()); - $passing = array('file_test_validator' => array(array())); - $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.'); - $this->assertFileHooksCalled(array('validate')); + file_test_set_return('validate', []); + $passing = ['file_test_validator' => [[]]]; + $this->assertEqual(file_validate($file, $passing), [], 'Validating passes.'); + $this->assertFileHooksCalled(['validate']); // Now test for failures in validators passed in and by hook_validate. file_test_reset(); - file_test_set_return('validate', array('Epic fail')); - $failing = array('file_test_validator' => array(array('Failed', 'Badly'))); - $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.'); - $this->assertFileHooksCalled(array('validate')); + file_test_set_return('validate', ['Epic fail']); + $failing = ['file_test_validator' => [['Failed', 'Badly']]]; + $this->assertEqual(file_validate($file, $failing), ['Failed', 'Badly', 'Epic fail'], 'Validating returns errors.'); + $this->assertFileHooksCalled(['validate']); } } diff --git a/core/modules/file/tests/src/Kernel/Views/ExtensionViewsFieldTest.php b/core/modules/file/tests/src/Kernel/Views/ExtensionViewsFieldTest.php index 221c011940b..867ab7aaa10 100644 --- a/core/modules/file/tests/src/Kernel/Views/ExtensionViewsFieldTest.php +++ b/core/modules/file/tests/src/Kernel/Views/ExtensionViewsFieldTest.php @@ -18,21 +18,21 @@ class ExtensionViewsFieldTest extends ViewsKernelTestBase { /** * {@inheritdoc} */ - public static $modules = array('file', 'file_test_views', 'user'); + public static $modules = ['file', 'file_test_views', 'user']; /** * Views used by this test. * * @var array */ - public static $testViews = array('file_extension_view'); + public static $testViews = ['file_extension_view']; /** * {@inheritdoc} */ protected function setUp($import_test_views = TRUE) { parent::setUp(); - ViewTestData::createTestViews(get_class($this), array('file_test_views')); + ViewTestData::createTestViews(get_class($this), ['file_test_views']); $this->installEntitySchema('file'); diff --git a/core/modules/file/tests/src/Unit/Plugin/migrate/process/d6/CckFileTest.php b/core/modules/file/tests/src/Unit/Plugin/migrate/process/d6/CckFileTest.php index 1ee73a83eee..1cce9898e8c 100644 --- a/core/modules/file/tests/src/Unit/Plugin/migrate/process/d6/CckFileTest.php +++ b/core/modules/file/tests/src/Unit/Plugin/migrate/process/d6/CckFileTest.php @@ -25,26 +25,26 @@ class CckFileTest extends UnitTestCase { $migration_plugin = $this->prophesize(MigrateProcessInterface::class); $migration_plugin->transform(1, $executable, $row, 'foo')->willReturn(1); - $plugin = new CckFile(array(), 'd6_cck_file', array(), $migration, $migration_plugin->reveal()); + $plugin = new CckFile([], 'd6_cck_file', [], $migration, $migration_plugin->reveal()); - $options = array( + $options = [ 'alt' => 'Foobaz', 'title' => 'Wambooli', - ); - $value = array( + ]; + $value = [ 'fid' => 1, 'list' => TRUE, 'data' => serialize($options), - ); + ]; $transformed = $plugin->transform($value, $executable, $row, 'foo'); - $expected = array( + $expected = [ 'target_id' => 1, 'display' => TRUE, 'description' => '', 'alt' => 'Foobaz', 'title' => 'Wambooli', - ); + ]; $this->assertSame($expected, $transformed); } |