Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -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()]);
}
}

View file

@ -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]);
}
}

View file

@ -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;

View file

@ -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');

View file

@ -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,
),
),
);
],
],
];
}

View file

@ -14,9 +14,10 @@ source:
source_base_path: ''
process:
# If you are using both this migration and d6_user_picture_file in a custom
# migration and executing migrations incrementally, it is recommended that
# you remove the fid mapping here to avoid potential ID conflicts.
fid: fid
# migration and executing migrations incrementally, it is strongly
# recommended that you remove the fid mapping to avoid potential ID
# conflicts. For that reason, this mapping is commented out by default.
# fid: fid
filename: filename
source_full_path:
-
@ -40,7 +41,8 @@ process:
- '@source_full_path'
- '@destination_full_path'
filemime: filemime
filesize: filesize
# No need to migrate filesize, it is computed when file entities are saved.
# filesize: filesize
status: status
changed: timestamp
uid: uid

View file

@ -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']);
}
}

View file

@ -49,6 +49,7 @@ class ManagedFile extends FormElement {
'#attached' => [
'library' => ['file/drupal.file'],
],
'#accept' => NULL,
];
}
@ -107,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;
@ -308,6 +309,9 @@ class ManagedFile extends FormElement {
'#weight' => -10,
'#error_no_message' => TRUE,
];
if (!empty($element['#accept'])) {
$element['upload']['#attributes'] = ['accept' => $element['#accept']];
}
if (!empty($fids) && $element['#files']) {
foreach ($element['#files'] as $delta => $file) {
@ -330,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()),
);
];
}
}
}

View file

@ -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());
}

View file

@ -21,9 +21,6 @@ class FileStorageSchema extends SqlContentEntityStorageSchema {
switch ($field_name) {
case 'status':
case 'changed':
$this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
break;
case 'uri':
$this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
break;

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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.

View file

@ -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 [];
}

View file

@ -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,
);
];
}
}

View file

@ -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;

View file

@ -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)) {

View file

@ -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']]));
}
}
@ -253,15 +253,15 @@ class FileItem extends EntityReferenceItem {
* Determines the URI for a file field.
*
* @param array $data
* An array of token objects to pass to token_replace().
* An array of token objects to pass to Token::replace().
*
* @return string
* An unsanitized file directory URI with tokens replaced. The result of
* the token replacement is then converted to plain text and returned.
*
* @see token_replace()
* @see \Drupal\Core\Utility\Token::replace()
*/
public function getUploadLocation($data = array()) {
public function getUploadLocation($data = []) {
return static::doGetUploadLocation($this->getSettings(), $data);
}
@ -271,11 +271,13 @@ class FileItem extends EntityReferenceItem {
* @param array $settings
* The array of field settings.
* @param array $data
* An array of token objects to pass to token_replace().
* An array of token objects to pass to Token::replace().
*
* @return string
* An unsanitized file directory URI with tokens replaced. The result of
* the token replacement is then converted to plain text and returned.
*
* @see \Drupal\Core\Utility\Token::replace()
*/
protected static function doGetUploadLocation(array $settings, $data = []) {
$destination = trim($settings['file_directory'], '/');
@ -294,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.
@ -304,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;
@ -329,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;
}

View file

@ -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;
@ -311,7 +311,7 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface {
*
* This method is assigned as a #value_callback in formElement() method.
*/
public static function value($element, $input = FALSE, FormStateInterface $form_state) {
public static function value($element, $input, FormStateInterface $form_state) {
if ($input) {
// Checkboxes lose their value when empty.
// If the display field is present make sure its unchecked value is saved.
@ -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;
}
}

View file

@ -17,7 +17,7 @@ class ImageField extends CckFieldPluginBase {
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
return array();
return [];
}
/**

View file

@ -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}

View file

@ -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.'),
);
];
}
/**

View file

@ -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')
@ -38,13 +38,13 @@ class UploadInstance extends DrupalSqlBase {
->fetchAllKeyed();
foreach ($node_types as $node_type) {
$name = 'upload_' . $node_type;
if (isset($values[$name])) {
$enabled = unserialize($values[$name]);
if ($enabled) {
$return[$node_type]['node_type'] = $node_type;
$return[$node_type]['max_filesize'] = $max_filesize;
$return[$node_type]['file_extensions'] = $file_extensions;
}
// By default, file attachments in D6 are enabled unless upload_<type> is
// false, so include types where the upload-variable is not set.
$enabled = !isset($values[$name]) || unserialize($values[$name]);
if ($enabled) {
$return[$node_type]['node_type'] = $node_type;
$return[$node_type]['max_filesize'] = $max_filesize;
$return[$node_type]['file_extensions'] = $file_extensions;
}
}
@ -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'),
);
];
}
/**

View file

@ -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.'),
);
];
}
/**

View file

@ -3,7 +3,6 @@
namespace Drupal\file\Plugin\views\argument;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\views\Plugin\views\argument\NumericArgument;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -24,13 +23,6 @@ class Fid extends NumericArgument implements ContainerFactoryPluginInterface {
*/
protected $entityManager;
/**
* The entity query factory service.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $entityQuery;
/**
* Constructs a Drupal\file\Plugin\views\argument\Fid object.
*
@ -42,13 +34,10 @@ class Fid extends NumericArgument implements ContainerFactoryPluginInterface {
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
* The entity query factory.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, QueryFactory $entity_query) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityManager = $entity_manager;
$this->entityQuery = $entity_query;
}
/**
@ -59,8 +48,7 @@ class Fid extends NumericArgument implements ContainerFactoryPluginInterface {
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.manager'),
$container->get('entity.query')
$container->get('entity.manager')
);
}
@ -68,12 +56,12 @@ class Fid extends NumericArgument implements ContainerFactoryPluginInterface {
* Override the behavior of titleQuery(). Get the filenames.
*/
public function titleQuery() {
$fids = $this->entityQuery->get('file')
$storage = $this->entityManager->getStorage('file');
$fids = $storage->getQuery()
->condition('fid', $this->value, 'IN')
->execute();
$controller = $this->entityManager->getStorage('file');
$files = $controller->loadMultiple($fids);
$titles = array();
$files = $storage->loadMultiple($fids);
$titles = [];
foreach ($files as $file) {
$titles[] = $file->getFilename();
}

View file

@ -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);
}

View file

@ -17,7 +17,7 @@ class DownloadTest extends FileManagedTestBase {
/**
* Test the public file transfer system.
*/
function testPublicFileTransfer() {
public function testPublicFileTransfer() {
// Test generating a URL to a created file.
$file = $this->createFile();
$url = file_create_url($file->getFileUri());
@ -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.');
@ -86,7 +86,7 @@ class DownloadTest extends FileManagedTestBase {
/**
* Test file_create_url().
*/
function testFileCreateUrl() {
public function testFileCreateUrl() {
// Tilde (~) is excluded from this test because it is encoded by
// rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
@ -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);

View file

@ -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.');

View file

@ -15,33 +15,41 @@ class FileFieldDisplayTest extends FileFieldTestBase {
/**
* Tests normal formatter display on node display.
*/
function testNodeDisplay() {
public 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) {
$edit = array(
"fields[$field_name][type]" => $formatter,
);
if ($formatter === 'hidden') {
$edit = [
"fields[$field_name][region]" => 'hidden',
];
}
else {
$edit = [
"fields[$field_name][type]" => $formatter,
"fields[$field_name][region]" => 'content',
];
}
$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');
@ -57,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);
@ -102,18 +110,18 @@ class FileFieldDisplayTest extends FileFieldTestBase {
/**
* Tests default display of File Field.
*/
function testDefaultFileFieldDisplay() {
public 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');
@ -129,36 +137,36 @@ class FileFieldDisplayTest extends FileFieldTestBase {
/**
* Tests description toggle for field instance configuration.
*/
function testDescToggle() {
public function testDescToggle() {
$type_name = 'test';
$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');

View file

@ -13,7 +13,7 @@ class FileFieldPathTest extends FileFieldTestBase {
/**
* Tests the normal formatter display on node display.
*/
function testUploadPath() {
public function testUploadPath() {
/** @var \Drupal\node\NodeStorageInterface $node_storage */
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$field_name = strtolower($this->randomMachineName());
@ -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()]));
}
/**
@ -79,7 +79,7 @@ class FileFieldPathTest extends FileFieldTestBase {
* @param string $message
* The message to display with this assertion.
*/
function assertPathMatch($expected_path, $actual_path, $message) {
public function assertPathMatch($expected_path, $actual_path, $message) {
// Strip off the extension of the expected path to allow for _0, _1, etc.
// suffixes when the file hits a duplicate name.
$pos = strrpos($expected_path, '.');

View file

@ -16,12 +16,12 @@ 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.
*/
function testFileFieldRSSContent() {
public function testFileFieldRSSContent() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
@ -30,26 +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("fields[$field_name][type]" => 'file_rss_enclosure');
$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);
@ -58,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()
);

View file

@ -21,7 +21,7 @@ class FileFieldRevisionTest extends FileFieldTestBase {
* - When the last revision that uses a file is deleted, the original file
* should be deleted also.
*/
function testRevisions() {
public function testRevisions() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
@ -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();

View file

@ -10,6 +10,9 @@ use Drupal\file\Entity\File;
/**
* Provides methods specifically for testing File module's field handling.
*
* @deprecated Scheduled for removal in Drupal 9.0.0.
* Use \Drupal\Tests\file\Functional\FileFieldTestBase instead.
*/
abstract class FileFieldTestBase extends WebTestBase {
@ -18,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.
@ -29,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']);
}
/**
@ -39,7 +42,7 @@ abstract class FileFieldTestBase extends WebTestBase {
*
* @return \Drupal\file\FileInterface
*/
function getTestFile($type_name, $size = NULL) {
public function getTestFile($type_name, $size = NULL) {
// Get a file to upload.
$file = current($this->drupalGetTestFiles($type_name, $size));
@ -53,7 +56,7 @@ abstract class FileFieldTestBase extends WebTestBase {
/**
* Retrieves the fid of the last inserted file.
*/
function getLastFileId() {
public function getLastFileId() {
return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
}
@ -73,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(
public 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 +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(
public 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()) {
public 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 +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()) {
public 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 +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(
public 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 +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.');
}
@ -234,68 +237,68 @@ 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(
public function removeNodeFile($nid, $new_revision = TRUE) {
$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'));
}
/**
* Replaces a file within a node.
*/
function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$edit = array(
public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$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'));
}
/**
* 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()));
public function assertFileExists($file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
$this->assertTrue(is_file($file->getFileUri()), $message);
}
/**
* Asserts that a file exists in the database.
*/
function assertFileEntryExists($file, $message = NULL) {
public 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);
}
/**
* 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()));
public function assertFileNotExists($file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file exists on the disk.', ['%file' => $file->getFileUri()]);
$this->assertFalse(is_file($file->getFileUri()), $message);
}
/**
* Asserts that a file does not exist in the database.
*/
function assertFileEntryNotExists($file, $message) {
public 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);
}
/**
* 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()));
public function assertFileIsPermanent(FileInterface $file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]);
$this->assertTrue($file->isPermanent(), $message);
}

View file

@ -17,26 +17,26 @@ class FileFieldValidateTest extends FileFieldTestBase {
/**
* Tests the required property on file fields.
*/
function testRequired() {
public function testRequired() {
$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.');
@ -65,56 +65,56 @@ class FileFieldValidateTest extends FileFieldTestBase {
/**
* Tests the max file size validator.
*/
function testFileMaxSize() {
public function testFileMaxSize() {
$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())]));
}
/**
* Tests file extension checking.
*/
function testFileExtension() {
public function testFileExtension() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
@ -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);

View file

@ -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.
@ -73,7 +73,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
/**
* Tests upload and remove buttons for a single-valued File field.
*/
function testSingleValuedWidget() {
public function testSingleValuedWidget() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
@ -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.');
}
@ -131,7 +131,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
/**
* Tests upload and remove buttons for multiple multi-valued File fields.
*/
function testMultiValuedWidget() {
public function testMultiValuedWidget() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$type_name = 'article';
// Use explicit names instead of random names for those fields, because of a
@ -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.');
@ -301,10 +301,10 @@ class FileFieldWidgetTest extends FileFieldTestBase {
/**
* Tests a file field with a "Private files" upload destination setting.
*/
function testPrivateFileSetting() {
public 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.');
@ -341,42 +341,42 @@ class FileFieldWidgetTest extends FileFieldTestBase {
/**
* Tests that download restrictions on private files work on comments.
*/
function testPrivateFileComment() {
$user = $this->drupalCreateUser(array('access comments'));
public function testPrivateFileComment() {
$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);
@ -413,15 +413,15 @@ class FileFieldWidgetTest extends FileFieldTestBase {
/**
* Tests validation with the Upload button.
*/
function testWidgetValidation() {
public function testWidgetValidation() {
$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 */

View file

@ -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']);
}
/**
@ -59,7 +59,7 @@ class FileListingTest extends FileFieldTestBase {
/**
* Tests file overview with different user permissions.
*/
function testFileListingPages() {
public function testFileListingPages() {
$file_usage = $this->container->get('file.usage');
// Users without sufficient permissions should not see file listing.
$this->drupalLogin($this->baseUser);
@ -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.
@ -148,14 +148,14 @@ class FileListingTest extends FileFieldTestBase {
/**
* Tests file listing usage page for entities with no canonical link template.
*/
function testFileListingUsageNoLink() {
public function testFileListingUsageNoLink() {
// Login with user with right permissions and test listing.
$this->drupalLogin($this->adminUser);
// 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.

View file

@ -13,7 +13,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
/**
* Tests the managed_file element type.
*/
function testManagedFile() {
public function testManagedFile() {
// Check that $element['#size'] is passed to the child upload element.
$this->drupalGet('file/test');
$this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
@ -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 */

View file

@ -9,6 +9,9 @@ use Drupal\simpletest\WebTestBase;
/**
* Base class for file tests that use the file_test module to test uploads and
* hooks.
*
* @deprecated Scheduled for removal in Drupal 9.0.0.
* Use \Drupal\Tests\file\Functional\FileManagedTestBase instead.
*/
abstract class FileManagedTestBase extends WebTestBase {
@ -17,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();
@ -33,7 +36,7 @@ abstract class FileManagedTestBase extends WebTestBase {
* An array of strings containing with the hook name; for example, 'load',
* 'save', 'insert', etc.
*/
function assertFileHooksCalled($expected) {
public function assertFileHooksCalled($expected) {
\Drupal::state()->resetCache();
// Determine which hooks were called.
@ -42,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.');
@ -68,18 +71,18 @@ abstract class FileManagedTestBase extends WebTestBase {
* @param string|null $message
* Optional translated string message.
*/
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
public function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
$actual_count = count(file_test_get_calls($hook));
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);
@ -93,14 +96,14 @@ abstract class FileManagedTestBase extends WebTestBase {
* @param \Drupal\file\FileInterface $after
* 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');
public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
$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');
}
/**
@ -111,9 +114,9 @@ abstract class FileManagedTestBase extends WebTestBase {
* @param \Drupal\file\FileInterface $file2
* 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');
public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
@ -124,9 +127,9 @@ abstract class FileManagedTestBase extends WebTestBase {
* @param \Drupal\file\FileInterface $file2
* 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');
public function assertSameFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
@ -145,7 +148,7 @@ abstract class FileManagedTestBase extends WebTestBase {
* @return \Drupal\file\FileInterface
* File entity.
*/
function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
public function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
// Don't count hook invocations caused by creating the file.
\Drupal::state()->set('file_test.count_hook_invocations', FALSE);
$file = File::create([
@ -177,7 +180,7 @@ abstract class FileManagedTestBase extends WebTestBase {
* @return string
* File URI.
*/
function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
public function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
if (!isset($filepath)) {
// Prefix with non-latin characters to ensure that all file-related
// tests work with international filenames.

View file

@ -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();

View file

@ -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();
@ -31,15 +31,15 @@ class FilePrivateTest extends FileFieldTestBase {
/**
* Tests file access for file uploaded to a private node.
*/
function testPrivateFile() {
public function testPrivateFile() {
$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);

View file

@ -16,7 +16,7 @@ class FileTokenReplaceTest extends FileFieldTestBase {
/**
* Creates a file, then tests the tokens generated from it.
*/
function testFileTokenReplacement() {
public function testFileTokenReplacement() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
@ -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]));
}
}

View file

@ -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.');

View file

@ -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();

View file

@ -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,24 +58,24 @@ 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();
}
/**
* Test the file_save_upload() function.
*/
function testNormal() {
public function testNormal() {
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
$this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
$file1 = File::load($max_fid_after);
@ -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!'));
@ -124,17 +124,17 @@ class SaveUploadTest extends FileManagedTestBase {
/**
* Test extension handling.
*/
function testHandleExtension() {
public function testHandleExtension() {
// The file being tested is a .gif which is in the default safe list
// of extensions to allow when the extension validator isn't used. This is
// 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,39 +162,39 @@ 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']);
}
/**
* Test dangerous file handling.
*/
function testHandleDangerousFile() {
public function testHandleDangerousFile() {
$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();
@ -228,7 +228,7 @@ class SaveUploadTest extends FileManagedTestBase {
/**
* Test file munge handling.
*/
function testHandleFileMunge() {
public function testHandleFileMunge() {
// Ensure insecure uploads are disabled for this test.
$this->config('system.file')->set('allow_insecure_uploads', 0)->save();
$this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
@ -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,100 +249,100 @@ 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(
public function testExistingRename() {
$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(
public function testExistingReplace() {
$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(
public function testExistingError() {
$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'));
public function testNoUpload() {
$this->drupalPostForm('file-test/upload', [], t('Submit'));
$this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
}
/**
* Tests for log entry on failing destination.
*/
function testDrupalMovingUploadedFileError() {
public function testDrupalMovingUploadedFileError() {
// Create a directory and make it not writable.
$test_directory = 'test_drupal_move_uploaded_file_fail';
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.');
}
}

View file

@ -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);
}

View file

@ -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)]));
}
}

View file

@ -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;
}

View file

@ -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) {

View file

@ -25,7 +25,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
return t('Dummy wrapper for simpletest (readonly).');
}
function getDirectoryPath() {
public function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
@ -34,7 +34,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
*
* Return a dummy path for testing.
*/
function getInternalUri() {
public function getInternalUri() {
return '/dummy/example.txt';
}
@ -43,7 +43,7 @@ class DummyReadOnlyStreamWrapper extends LocalReadOnlyStream {
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
public function getExternalUrl() {
return '/dummy/example.txt';
}

View file

@ -27,7 +27,7 @@ class DummyRemoteStreamWrapper extends PublicStream {
return t('Dummy wrapper for simpletest (remote).');
}
function realpath() {
public function realpath() {
return FALSE;
}

View file

@ -25,7 +25,7 @@ class DummyStreamWrapper extends LocalStream {
return t('Dummy wrapper for simpletest.');
}
function getDirectoryPath() {
public function getDirectoryPath() {
return \Drupal::service('site.path') . '/files';
}
@ -34,7 +34,7 @@ class DummyStreamWrapper extends LocalStream {
*
* Return a dummy path for testing.
*/
function getInternalUri() {
public function getInternalUri() {
return '/dummy/example.txt';
}
@ -43,7 +43,7 @@ class DummyStreamWrapper extends LocalStream {
*
* Return the HTML URI of a public file.
*/
function getExternalUrl() {
public function getExternalUrl() {
return '/dummy/example.txt';
}

View file

@ -0,0 +1,320 @@
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\file\FileInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\file\Entity\File;
/**
* Provides methods specifically for testing File module's field handling.
*/
abstract class FileFieldTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'file', 'file_module_test', 'field_ui'];
/**
* An user with administration permissions.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
$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(['type' => 'article', 'name' => 'Article']);
}
/**
* Retrieves a sample file of the specified type.
*
* @return \Drupal\file\FileInterface
*/
public function getTestFile($type_name, $size = NULL) {
// Get a file to upload.
$file = current($this->drupalGetTestFiles($type_name, $size));
// Add a filesize property to files as would be read by
// \Drupal\file\Entity\File::load().
$file->filesize = filesize($file->uri);
return File::create((array) $file);
}
/**
* Retrieves the fid of the last inserted file.
*/
public function getLastFileId() {
return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
}
/**
* Creates a new file field.
*
* @param string $name
* The name of the new field (all lowercase), exclude the "field_" prefix.
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle that this field will be added to.
* @param array $storage_settings
* A list of field storage settings that will be added to the defaults.
* @param array $field_settings
* A list of instance settings that will be added to the instance defaults.
* @param array $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
public 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);
return $field_storage;
}
/**
* Attaches a file field to an entity.
*
* @param string $name
* The name of the new field (all lowercase), exclude the "field_" prefix.
* @param string $entity_type
* The entity type this field will be added to.
* @param string $bundle
* The bundle this field will be added to.
* @param array $field_settings
* A list of field settings that will be added to the defaults.
* @param array $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
public 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, [
'type' => 'file_generic',
'settings' => $widget_settings,
])
->save();
// Assign display settings.
entity_get_display($entity_type, $bundle, 'default')
->setComponent($name, [
'label' => 'hidden',
'type' => 'file_default',
])
->save();
}
/**
* Updates an existing file field with new settings.
*/
public 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, [
'settings' => $widget_settings,
])
->save();
}
/**
* Uploads a file to a node.
*
* @param \Drupal\file\FileInterface $file
* The File to be uploaded.
* @param string $field_name
* The name of the field on which the files should be saved.
* @param $nid_or_type
* A numeric node id to upload files to an existing node, or a string
* indicating the desired bundle for a new node.
* @param bool $new_revision
* The revision number.
* @param array $extras
* Additional values when a new node is created.
*
* @return int
* The node id.
*/
public 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);
}
/**
* Uploads multiple files to a node.
*
* @param \Drupal\file\FileInterface[] $files
* The files to be uploaded.
* @param string $field_name
* The name of the field on which the files should be saved.
* @param $nid_or_type
* A numeric node id to upload files to an existing node, or a string
* indicating the desired bundle for a new node.
* @param bool $new_revision
* The revision number.
* @param array $extras
* Additional values when a new node is created.
*
* @return int
* The node id.
*/
public 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([$nid]);
$node = $node_storage->load($nid);
}
else {
// Add a new node.
$extras['type'] = $nid_or_type;
$node = $this->drupalCreateNode($extras);
$nid = $node->id();
// Save at least one revision to better simulate a real site.
$node->setNewRevision();
$node->save();
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
$this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.');
}
// Attach files to the node.
$field_storage = FieldStorageConfig::loadByName('node', $field_name);
// File input name depends on number of files already uploaded.
$field_num = count($node->{$field_name});
$name = 'files[' . $field_name . "_$field_num]";
if ($field_storage->getCardinality() != 1) {
$name .= '[]';
}
foreach ($files as $file) {
$file_path = $this->container->get('file_system')->realpath($file->getFileUri());
if (count($files) == 1) {
$edit[$name] = $file_path;
}
else {
$edit[$name][] = $file_path;
}
}
$this->drupalPostForm("node/$nid/edit", $edit, t('Save and keep published'));
return $nid;
}
/**
* Removes a file from a node.
*
* Note that if replacing a file, it must first be removed then added again.
*/
public function removeNodeFile($nid, $new_revision = TRUE) {
$edit = [
'revision' => (string) (int) $new_revision,
];
$this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
}
/**
* Replaces a file within a node.
*/
public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$edit = [
'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()),
'revision' => (string) (int) $new_revision,
];
$this->drupalPostForm('node/' . $nid . '/edit', [], t('Remove'));
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
}
/**
* Asserts that a file exists physically on disk.
*
* Overrides PHPUnit_Framework_Assert::assertFileExists() to also work with
* file entities.
*
* @param \Drupal\File\FileInterface|string $file
* Either the file entity or the file URI.
* @param string $message
* (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.', ['%file' => $file->getFileUri()]);
$filename = $file instanceof FileInterface ? $file->getFileUri() : $file;
parent::assertFileExists($filename, $message);
}
/**
* Asserts that a file exists in the database.
*/
public 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.', ['%file' => $file->getFileUri()]);
$this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message);
}
/**
* Asserts that a file does not exist on disk.
*
* Overrides PHPUnit_Framework_Assert::assertFileExists() to also work with
* file entities.
*
* @param \Drupal\File\FileInterface|string $file
* Either the file entity or the file URI.
* @param string $message
* (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.', ['%file' => $file->getFileUri()]);
$filename = $file instanceof FileInterface ? $file->getFileUri() : $file;
parent::assertFileNotExists($filename, $message);
}
/**
* Asserts that a file does not exist in the database.
*/
public 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.', ['%file' => $file->getFileUri()]);
$this->assertFalse(File::load($file->id()), $message);
}
/**
* Asserts that a file's status is set to permanent in the database.
*/
public function assertFileIsPermanent(FileInterface $file, $message = NULL) {
$message = isset($message) ? $message : format_string('File %file is permanent.', ['%file' => $file->getFileUri()]);
$this->assertTrue($file->isPermanent(), $message);
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\file\Tests;
namespace Drupal\Tests\file\Functional;
use Drupal\file\Entity\File;
@ -14,22 +14,22 @@ class FileManagedAccessTest extends FileManagedTestBase {
/**
* Tests if public file is always accessible.
*/
function testFileAccess() {
public 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');

View file

@ -0,0 +1,200 @@
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Base class for file tests that use the file_test module to test uploads and
* hooks.
*/
abstract class FileManagedTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['file_test', 'file'];
protected function setUp() {
parent::setUp();
// Clear out any hook calls.
file_test_reset();
}
/**
* Assert that all of the specified hook_file_* hooks were called once, other
* values result in failure.
*
* @param string[] $expected
* An array of strings containing with the hook name; for example, 'load',
* 'save', 'insert', etc.
*/
public function assertFileHooksCalled($expected) {
\Drupal::state()->resetCache();
// Determine which hooks were called.
$actual = array_keys(array_filter(file_test_get_all_calls()));
// 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.', ['%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled)]));
}
else {
$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.', ['%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected)]));
}
else {
$this->assertTrue(TRUE, 'No unexpected hooks were called.');
}
}
/**
* Assert that a hook_file_* hook was called a certain number of times.
*
* @param string $hook
* String with the hook name; for instance, 'load', 'save', 'insert', etc.
* @param int $expected_count
* Optional integer count.
* @param string|null $message
* Optional translated string message.
*/
public function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
$actual_count = count(file_test_get_calls($hook));
if (!isset($message)) {
if ($actual_count == $expected_count) {
$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.', ['@name' => $hook, '@count' => $actual_count]);
}
else {
$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);
}
/**
* Asserts that two files have the same values (except timestamp).
*
* @param \Drupal\file\FileInterface $before
* File object to compare.
* @param \Drupal\file\FileInterface $after
* File object to compare.
*/
public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
$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');
}
/**
* Asserts that two files are not the same by comparing the fid and filepath.
*
* @param \Drupal\file\FileInterface $file1
* File object to compare.
* @param \Drupal\file\FileInterface $file2
* File object to compare.
*/
public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
* Asserts that two files are the same by comparing the fid and filepath.
*
* @param \Drupal\file\FileInterface $file1
* File object to compare.
* @param \Drupal\file\FileInterface $file2
* File object to compare.
*/
public function assertSameFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
* Create a file and save it to the files table and assert that it occurs
* correctly.
*
* @param string $filepath
* Optional string specifying the file path. If none is provided then a
* randomly named file will be created in the site's files directory.
* @param string $contents
* Optional contents to save into the file. If a NULL value is provided an
* arbitrary string will be used.
* @param string $scheme
* Optional string indicating the stream scheme to use. Drupal core includes
* public, private, and temporary. The public wrapper is the default.
* @return \Drupal\file\FileInterface
* File entity.
*/
public function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
// Don't count hook invocations caused by creating the file.
\Drupal::state()->set('file_test.count_hook_invocations', FALSE);
$file = File::create([
'uri' => $this->createUri($filepath, $contents, $scheme),
'uid' => 1,
]);
$file->save();
// Write the record directly rather than using the API so we don't invoke
// the hooks.
$this->assertTrue($file->id() > 0, 'The file was added to the database.', 'Create test file');
\Drupal::state()->set('file_test.count_hook_invocations', TRUE);
return $file;
}
/**
* Creates a file and returns its URI.
*
* @param string $filepath
* Optional string specifying the file path. If none is provided then a
* randomly named file will be created in the site's files directory.
* @param string $contents
* Optional contents to save into the file. If a NULL value is provided an
* arbitrary string will be used.
* @param string $scheme
* Optional string indicating the stream scheme to use. Drupal core includes
* public, private, and temporary. The public wrapper is the default.
*
* @return string
* File URI.
*/
public function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
if (!isset($filepath)) {
// Prefix with non-latin characters to ensure that all file-related
// tests work with international filenames.
$filepath = 'Файл для тестирования ' . $this->randomMachineName();
}
if (!isset($scheme)) {
$scheme = file_default_scheme();
}
$filepath = $scheme . '://' . $filepath;
if (!isset($contents)) {
$contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
}
file_put_contents($filepath, $contents);
$this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
return $filepath;
}
}

View file

@ -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',
));
]);
}
/**

View file

@ -13,7 +13,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test file copying in the normal, base case.
*/
function testNormal() {
public function testNormal() {
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
$desired_uri = 'public://' . $this->randomMachineName();
@ -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.');
@ -42,7 +42,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test renaming when copying over a file that already exists.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -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.
@ -82,7 +82,7 @@ class CopyTest extends FileManagedUnitTestBase {
/**
* Test replacement when copying over a file that already exists.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -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.
@ -121,7 +121,7 @@ class CopyTest extends FileManagedUnitTestBase {
* Test that copying over an existing file fails when FILE_EXISTS_ERROR is
* specified.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(10);
$source = $this->createFile();
$target = $this->createFile(NULL, $contents);
@ -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()));

View file

@ -13,13 +13,13 @@ class DeleteTest extends FileManagedUnitTestBase {
/**
* Tries deleting a normal file (as opposed to a directory, symlink, etc).
*/
function testUnused() {
public function testUnused() {
$file = $this->createFile();
// 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.');
}
@ -27,7 +27,7 @@ class DeleteTest extends FileManagedUnitTestBase {
/**
* Tries deleting a file that is in use.
*/
function testInUse() {
public function testInUse() {
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'test', 1);
@ -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.');
}

View file

@ -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);

View file

@ -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.
@ -46,7 +46,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* Array with string containing with the hook name, e.g. 'load', 'save',
* 'insert', etc.
*/
function assertFileHooksCalled($expected) {
public function assertFileHooksCalled($expected) {
\Drupal::state()->resetCache();
// Determine which hooks were called.
@ -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.');
@ -81,18 +81,18 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @param string $message
* Optional translated string message.
*/
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
public function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
$actual_count = count(file_test_get_calls($hook));
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);
@ -106,14 +106,14 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @param \Drupal\file\FileInterface $after
* 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');
public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
$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');
}
/**
@ -124,9 +124,9 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @param \Drupal\file\FileInterface $file2
* 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');
public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
@ -137,9 +137,9 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @param \Drupal\file\FileInterface $file2
* 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');
public function assertSameFile(FileInterface $file1, FileInterface $file2) {
$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');
}
/**
@ -158,7 +158,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @return \Drupal\file\FileInterface
* File entity.
*/
function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
public function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
// Don't count hook invocations caused by creating the file.
\Drupal::state()->set('file_test.count_hook_invocations', FALSE);
$file = File::create([
@ -190,7 +190,7 @@ abstract class FileManagedUnitTestBase extends KernelTestBase {
* @return string
* File URI.
*/
function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
public function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
if (!isset($filepath)) {
// Prefix with non-latin characters to ensure that all file-related
// tests work with international filenames.

View file

@ -13,33 +13,33 @@ class LoadTest extends FileManagedUnitTestBase {
/**
* Try to load a non-existent file by fid.
*/
function testLoadMissingFid() {
public 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'));
public function testLoadMissingFilepath() {
$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));
public function testLoadInvalidStatus() {
$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([]);
}
/**
* Load a single file and ensure that the correct values are returned.
*/
function testSingleValues() {
public function testSingleValues() {
// Create a new file entity from scratch so we know the values.
$file = $this->createFile('druplicon.txt', NULL, 'public');
$by_fid_file = File::load($file->id());
@ -56,13 +56,13 @@ class LoadTest extends FileManagedUnitTestBase {
/**
* This will test loading file data from the database.
*/
function testMultiple() {
public function testMultiple() {
// Create a new file entity.
$file = $this->createFile('druplicon.txt', NULL, 'public');
// 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.');

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\file\Kernel\Migrate\d6;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**

View file

@ -69,33 +69,77 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
$this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
$this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
$this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
$this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
$this->assertEntity(4, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
$map_table = $this->getMigration('d6_file')->getIdMap()->mapTableName();
$map = \Drupal::database()
->select($map_table, 'm')
->fields('m', ['sourceid1', 'destid1'])
->execute()
->fetchAllKeyed();
$map_expected = [
// The 4 files from the fixture.
1 => '1',
2 => '2',
3 => '3',
5 => '4',
// The file updated in migrateDumpAlter().
6 => NULL,
// The file created in migrateDumpAlter().
7 => '4',
];
$this->assertEquals($map_expected, $map);
// Test that we can re-import and also test with file_directory_path set.
\Drupal::database()
->truncate($this->getMigration('d6_file')->getIdMap()->mapTableName())
->truncate($map_table)
->execute();
// 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();
$this->executeMigration('d6_file');
$file = File::load(2);
// File 2, when migrated for the second time, is treated as a different file
// (due to having a different uri this time) and is given fid 6.
$file = File::load(6);
$this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
// File 7, created in static::migrateDumpAlter(), shares a path with
// file 5, which means it should be skipped entirely.
$this->assertNull(File::load(7));
$map_table = $this->getMigration('d6_file')->getIdMap()->mapTableName();
$map = \Drupal::database()
->select($map_table, 'm')
->fields('m', ['sourceid1', 'destid1'])
->execute()
->fetchAllKeyed();
$map_expected = [
// The 4 files from the fixture.
1 => '5',
2 => '6',
3 => '7',
5 => '8',
// The file updated in migrateDumpAlter().
6 => NULL,
// The files created in migrateDumpAlter().
7 => '8',
8 => '8',
];
$this->assertEquals($map_expected, $map);
// File 6, created in static::migrateDumpAlter(), shares a path with
// file 4, which means it should be skipped entirely. If it was migrated
// then it would have an fid of 9.
$this->assertNull(File::load(9));
$this->assertEquals(8, count(File::loadMultiple()));
}
/**
@ -122,10 +166,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')

View file

@ -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']));
}
}

View file

@ -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']));
}
}

View file

@ -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(['']));
}
}

View file

@ -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']));
}
}

View file

@ -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);
@ -57,7 +57,7 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
/**
* Test upload migration from Drupal 6 to Drupal 8.
*/
function testUpload() {
public function testUpload() {
$this->container->get('entity.manager')
->getStorage('node')
->resetCache([1, 2]);

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\file\Kernel\Migrate\d7;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**

View file

@ -13,7 +13,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Move a normal file.
*/
function testNormal() {
public function testNormal() {
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
$desired_filepath = 'public://' . $this->randomMachineName();
@ -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.
@ -43,7 +43,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test renaming when moving onto a file that already exists.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -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()));
@ -78,7 +78,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test replacement when moving onto a file that already exists.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -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.
@ -110,7 +110,7 @@ class MoveTest extends FileManagedUnitTestBase {
/**
* Test replacement when moving onto itself.
*/
function testExistingReplaceSelf() {
public function testExistingReplaceSelf() {
// Setup a file to overwrite.
$contents = $this->randomMachineName(10);
$source = $this->createFile(NULL, $contents);
@ -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.
@ -133,7 +133,7 @@ class MoveTest extends FileManagedUnitTestBase {
* Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
* specified.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(10);
$source = $this->createFile();
$target = $this->createFile(NULL, $contents);
@ -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.

View file

@ -13,7 +13,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test the file_save_data() function when no filename is provided.
*/
function testWithoutFilename() {
public function testWithoutFilename() {
$contents = $this->randomMachineName(8);
$result = file_save_data($contents);
@ -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()));
@ -35,7 +35,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test the file_save_data() function when a filename is provided.
*/
function testWithFilename() {
public function testWithFilename() {
$contents = $this->randomMachineName(8);
// Using filename with non-latin characters.
@ -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()));
@ -60,7 +60,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test file_save_data() when renaming around an existing file.
*/
function testExistingRename() {
public function testExistingRename() {
// Setup a file to overwrite.
$existing = $this->createFile();
$contents = $this->randomMachineName(8);
@ -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);
@ -88,7 +88,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test file_save_data() when replacing an existing file.
*/
function testExistingReplace() {
public function testExistingReplace() {
// Setup a file to overwrite.
$existing = $this->createFile();
$contents = $this->randomMachineName(8);
@ -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);
@ -115,7 +115,7 @@ class SaveDataTest extends FileManagedUnitTestBase {
/**
* Test that file_save_data() fails overwriting an existing file.
*/
function testExistingError() {
public function testExistingError() {
$contents = $this->randomMachineName(8);
$existing = $this->createFile(NULL, $contents);
@ -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()));

View file

@ -10,22 +10,22 @@ use Drupal\file\Entity\File;
* @group file
*/
class SaveTest extends FileManagedUnitTestBase {
function testFileSave() {
public 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);
}

View file

@ -52,7 +52,7 @@ class SpaceUsedTest extends FileManagedUnitTestBase {
/**
* Test different users with the default status.
*/
function testFileSpaceUsed() {
public function testFileSpaceUsed() {
$file = $this->container->get('entity.manager')->getStorage('file');
// Test different users with default status.
$this->assertEqual($file->spaceUsed(2), 70);

View file

@ -18,25 +18,25 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::listUsage().
*/
function testGetUsage() {
public 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);
@ -51,7 +51,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::add().
*/
function testAddUsage() {
public function testAddUsage() {
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'foo', 1);
@ -77,23 +77,23 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::delete().
*/
function testRemoveUsage() {
public function testRemoveUsage() {
$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();
@ -124,14 +124,14 @@ class UsageTest extends FileManagedUnitTestBase {
* We are using UPDATE statements because using the API would set the
* timestamp.
*/
function createTempFiles() {
public function createTempFiles() {
// 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,13 +155,13 @@ 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];
}
/**
* Ensure that temporary files are removed by default.
*/
function testTempFileCleanupDefault() {
public function testTempFileCleanupDefault() {
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
// Run cron and then ensure that only the old, temp file was deleted.
@ -175,7 +175,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Ensure that temporary files are kept as configured.
*/
function testTempFileNoCleanup() {
public function testTempFileNoCleanup() {
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
// Set the max age to 0, meaning no temporary files will be deleted.
@ -194,7 +194,7 @@ class UsageTest extends FileManagedUnitTestBase {
/**
* Ensure that temporary files are kept as configured.
*/
function testTempFileCustomCleanup() {
public function testTempFileCustomCleanup() {
list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
// Set the max age to older than default.

View file

@ -12,27 +12,27 @@ class ValidateTest extends FileManagedUnitTestBase {
/**
* Test that the validators passed into are checked.
*/
function testCallerValidation() {
public function testCallerValidation() {
$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']);
}
}

View file

@ -40,7 +40,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* Test the file_validate_extensions() function.
*/
function testFileValidateExtensions() {
public function testFileValidateExtensions() {
$file = File::create(['filename' => 'asdf.txt']);
$errors = file_validate_extensions($file, 'asdf txt pork');
$this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
@ -53,7 +53,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* This ensures a specific file is actually an image.
*/
function testFileValidateIsImage() {
public function testFileValidateIsImage() {
$this->assertTrue(file_exists($this->image->getFileUri()), 'The image being tested exists.', 'File');
$errors = file_validate_is_image($this->image);
$this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
@ -68,7 +68,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
*
* The image will be resized if it's too large.
*/
function testFileValidateImageResolution() {
public function testFileValidateImageResolution() {
// Non-images.
$errors = file_validate_image_resolution($this->nonImage);
$this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
@ -116,7 +116,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* This will ensure the filename length is valid.
*/
function testFileValidateNameLength() {
public function testFileValidateNameLength() {
// Create a new file entity.
$file = File::create();
@ -141,7 +141,7 @@ class ValidatorTest extends FileManagedUnitTestBase {
/**
* Test file_validate_size().
*/
function testFileValidateSize() {
public function testFileValidateSize() {
// Create a file with a size of 1000 bytes, and quotas of only 1 byte.
$file = File::create(['filesize' => 1000]);
$errors = file_validate_size($file, 0, 0);

View file

@ -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');

View file

@ -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);
}