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

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

@ -1,69 +0,0 @@
<?php
namespace Drupal\file\Tests;
use Drupal\file\Entity\File;
/**
* Tests access to managed files.
*
* @group file
*/
class FileManagedAccessTest extends FileManagedTestBase {
/**
* Tests if public file is always accessible.
*/
function testFileAccess() {
// Create a new file entity.
$file = File::create(array(
'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'));
$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');
// Create anonymous user to check file access.
$account = $this->createUser()->getAnonymousUser();
$this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
// Create a new file entity.
$file = File::create(array(
'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'));
$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');
// Create anonymous user to check file access.
$account = $this->createUser()->getAnonymousUser();
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');
}
}

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