Update to drupal 8.0.0-rc1. For more information, see https://www.drupal.org/node/2582663

This commit is contained in:
Greg Anderson 2015-10-08 11:40:12 -07:00
parent eb34d130a8
commit f32e58e4b1
8476 changed files with 211648 additions and 170042 deletions

View file

@ -372,19 +372,25 @@ class ManagedFile extends FormElement {
if ($file->isPermanent()) {
$references = static::fileUsage()->listUsage($file);
if (empty($references)) {
$form_state->setError($element, t('The file used in the !name field may not be referenced.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
}
}
}
else {
$form_state->setError($element, t('The file referenced by the !name field does not exist.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('The file referenced by the @name field does not exist.', ['@name' => $element['#title']]));
}
}
}
// Check required property based on the FID.
if ($element['#required'] && empty($element['fids']['#value']) && !in_array($clicked_button, ['upload_button', 'remove_button'])) {
$form_state->setError($element, t('!name is required.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('@name field is required.', ['@name' => $element['#title']]));
}
// Consolidate the array value of this field to array of FIDs.

View file

@ -110,13 +110,6 @@ class File extends ContentEntityBase implements FileInterface {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function getChangedTime() {
return $this->get('changed')->value;
}
/**
* {@inheritdoc}
*/

View file

@ -21,7 +21,7 @@ class FileAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\file\FileInterface $entity */
if ($operation == 'download' || $operation == 'view') {
if (\Drupal::service('file_system')->uriScheme($entity->getFileUri()) === 'public') {

View file

@ -7,7 +7,7 @@
namespace Drupal\file\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
/**
* Provides specific access control for the file entity type.
@ -20,7 +20,7 @@ use Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase;
* weight = 1
* )
*/
class FileSelection extends SelectionBase {
class FileSelection extends DefaultSelection {
/**
* {@inheritdoc}

View file

@ -46,7 +46,7 @@ abstract class BaseFieldFileFormatterBase extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$url = NULL;

View file

@ -34,7 +34,7 @@ class FileSize extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {

View file

@ -25,10 +25,10 @@ class GenericFileFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$item = $file->_referringItem;
$elements[$delta] = array(
'#theme' => 'file_link',
@ -47,11 +47,6 @@ class GenericFileFormatter extends FileFormatterBase {
unset($item->_attributes);
}
}
if (!empty($elements)) {
$elements['#attached'] = array(
'library' => array('file/drupal.file.formatter.generic'),
);
}
return $elements;
}

View file

@ -25,11 +25,11 @@ class RSSEnclosureFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$entity = $items->getEntity();
// Add the first file as an enclosure to the RSS item. RSS allows only one
// enclosure per item. See: http://en.wikipedia.org/wiki/RSS_enclosure
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$entity->rss_elements[] = array(
'key' => 'enclosure',
'attributes' => array(

View file

@ -25,10 +25,10 @@ class TableFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
if ($files = $this->getEntitiesToView($items)) {
if ($files = $this->getEntitiesToView($items, $langcode)) {
$header = array(t('Attachment'), t('Size'));
$rows = array();
foreach ($files as $delta => $file) {

View file

@ -25,10 +25,10 @@ class UrlPlainFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$elements[$delta] = array(
'#markup' => file_create_url($file->getFileUri()),
'#cache' => array(

View file

@ -54,7 +54,9 @@ class FileFieldItemList extends EntityReferenceFieldItemList {
// Get the file IDs attached to the field before this update.
$field_name = $this->getFieldDefinition()->getName();
$original_ids = array();
$original_items = $entity->original->getTranslation($this->getLangcode())->$field_name;
$langcode = $this->getLangcode();
$original = $entity->original;
$original_items = $original->hasTranslation($langcode) ? $original->getTranslation($langcode)->{$field_name} : $original->{$field_name};
foreach ($original_items as $item) {
$original_ids[] = $item->target_id;
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Plugin\Field\FieldType;
use Drupal\Component\Utility\Bytes;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
@ -249,7 +250,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' => t($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).', array('@name' => $element['title'])));
}
}
@ -260,7 +261,8 @@ class FileItem extends EntityReferenceItem {
* An array of token objects to pass to token_replace().
*
* @return string
* A file directory URI with tokens replaced.
* 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()
*/
@ -268,9 +270,9 @@ class FileItem extends EntityReferenceItem {
$settings = $this->getSettings();
$destination = trim($settings['file_directory'], '/');
// Replace tokens.
$destination = \Drupal::token()->replace($destination, $data);
// Replace tokens. As the tokens might contain HTML we convert it to plain
// text.
$destination = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($destination, $data));
return $settings['uri_scheme'] . '://' . $destination;
}
@ -309,8 +311,12 @@ class FileItem extends EntityReferenceItem {
$random = new Random();
$settings = $field_definition->getSettings();
// Prepare destination.
$dirname = $settings['uri_scheme'] . '://' . $settings['file_directory'];
file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
// Generate a file entity.
$destination = $settings['uri_scheme'] . '://' . $settings['file_directory'] . $random->name(10, TRUE) . '.txt';
$destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
$data = $random->paragraphs(3);
$file = file_save_data($data, $destination, FILE_EXISTS_ERROR);
$values = array(
@ -334,4 +340,11 @@ class FileItem extends EntityReferenceItem {
return TRUE;
}
/**
* {@inheritdoc}
*/
public static function getPreconfiguredOptions() {
return [];
}
}

View file

@ -9,7 +9,7 @@ namespace Drupal\file\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldFilteredString;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
@ -119,7 +119,7 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface {
}
$title = $this->fieldDefinition->getLabel();
$description = FieldFilteredString::create($this->fieldDefinition->getDescription());
$description = FieldFilteredMarkup::create($this->fieldDefinition->getDescription());
$elements = array();
@ -370,7 +370,10 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface {
$item = $element['#value'];
$item['fids'] = $element['fids']['#value'];
$element['#theme'] = 'file_widget';
// Prevent the file widget from overriding the image widget.
if (!isset($element['#theme'])) {
$element['#theme'] = 'file_widget';
}
// Add the display field if enabled.
if ($element['#display_field']) {

View file

@ -73,6 +73,20 @@ class EntityFile extends EntityContentBase {
);
}
/**
* {@inheritdoc}
*/
protected function getEntity(Row $row, array $old_destination_id_values) {
$destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
$entity = $this->storage->loadByProperties(['uri' => $destination]);
if ($entity) {
return reset($entity);
}
else {
return parent::getEntity($row, $old_destination_id_values);
}
}
/**
* {@inheritdoc}
*/

View file

@ -24,20 +24,19 @@ class FileUri extends ProcessPluginBase {
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($filepath, $file_directory_path, $temp_directory_path, $is_public) = $value;
// Specific handling using $temp_directory_path for temporary files.
if (substr($filepath, 0, strlen($temp_directory_path)) === $temp_directory_path) {
$uri = preg_replace('/^' . preg_quote($temp_directory_path, '/') . '/', '', $filepath);
return "temporary://$uri";
return 'temporary://' . ltrim($uri, '/');
}
// Strip the files path from the uri instead of using basename
// so any additional folders in the path are preserved.
$uri = preg_replace('/^' . preg_quote($file_directory_path, '/') . '/', '', $filepath);
return $is_public ? "public://$uri" : "private://$uri";
return ($is_public ? 'public' : 'private') . '://' . ltrim($uri, '/');
}
}

View file

@ -44,18 +44,13 @@ class File extends DrupalSqlBase {
* {@inheritdoc}
*/
public function query() {
$query = $this->select('files', 'f')->fields('f', array(
'fid',
'uid',
'filename',
'filepath',
'filemime',
'filesize',
'status',
'timestamp',
));
$query->orderBy('timestamp');
return $query;
return $this->select('files', 'f')
->fields('f')
->orderBy('timestamp')
// If two or more files have the same timestamp, they'll end up in a
// non-deterministic order. Ordering by fid (or any other unique field)
// will prevent this.
->orderBy('fid');
}
/**

View file

@ -26,19 +26,23 @@ class UploadInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
protected function initializeIterator() {
$prefix = 'upload';
$node_types = $this->getDatabase()->query('SELECT type FROM {node_type}')->fetchCol();
foreach ($node_types as $node_type) {
$variables[] = $prefix . '_' . $node_type;
}
$node_types = $this->select('node_type', 'nt')
->fields('nt', ['type'])
->execute()
->fetchCol();
$variables = array_map(function($type) { return 'upload_' . $type; }, $node_types);
$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();
$values = $this->getDatabase()->query('SELECT name, value FROM {variable} WHERE name IN ( :name[] )', array(':name[]' => $variables))->fetchAllKeyed();
$values = $this->select('variable', 'v')
->fields('v', ['name', 'value'])
->condition('name', $variables, 'IN')
->execute()
->fetchAllKeyed();
foreach ($node_types as $node_type) {
$name = $prefix . '_' . $node_type;
$name = 'upload_' . $node_type;
if (isset($values[$name])) {
$enabled = unserialize($values[$name]);
if ($enabled) {

View file

@ -7,6 +7,7 @@
namespace Drupal\file\Plugin\migrate\source\d7;
use Drupal\Core\Database\Query\Condition;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
@ -44,9 +45,28 @@ class File extends DrupalSqlBase {
* {@inheritdoc}
*/
public function query() {
return $this->select('file_managed', 'f')
$query = $this->select('file_managed', 'f')
->fields('f')
->orderBy('timestamp');
// Filter by scheme(s), if configured.
if (isset($this->configuration['scheme'])) {
$schemes = array();
// Accept either a single scheme, or a list.
foreach ((array) $this->configuration['scheme'] as $scheme) {
$schemes[] = rtrim($scheme) . '://';
}
$schemes = array_map([$this->getDatabase(), 'escapeLike'], $schemes);
// uri LIKE 'public://%' OR uri LIKE 'private://%'
$conditions = new Condition('OR');
foreach ($schemes as $scheme) {
$conditions->condition('uri', $scheme . '%', 'LIKE');
}
$query->condition($conditions);
}
return $query;
}
/**
@ -69,7 +89,9 @@ class File extends DrupalSqlBase {
// At this point, $path could be an absolute path or a relative path,
// depending on how the scheme's variable was set. So we need to shear out
// the source_base_path in order to make them all relative.
$path = str_replace($this->migration->get('destination.source_base_path'), NULL, $path);
// @todo Don't depend on destination configuration.
// @see https://www.drupal.org/node/2577871
$path = str_replace($this->migration->get('destination')['source_base_path'], NULL, $path);
$row->setSourceProperty('filepath', $path);
return parent::prepareRow($row);
}

View file

@ -113,14 +113,25 @@ class DownloadTest extends FileManagedTestBase {
'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';
$request = $this->prepareRequestForGenerator($clean_urls);
$base_path = $request->getSchemeAndHttpHost() . $request->getBasePath();
$this->checkUrl('public', '', $basename, $base_path . '/' . \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath() . '/' . $basename_encoded);
$this->checkUrl('public', '', $basename, $base_path . '/' . $public_directory_path . '/' . $basename_encoded);
$this->checkUrl('private', '', $basename, $base_path . '/' . $script_path . 'system/files/' . $basename_encoded);
}
$this->assertEqual(file_create_url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', t('Generated URL matches expected URL.'));
// Test public files with a different host name from settings.
$test_base_url = 'http://www.example.com/cdn';
$this->settingsSet('file_public_base_url', $test_base_url);
$filepath = file_create_filename('test.txt', '');
$directory_uri = 'public://' . dirname($filepath);
file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
$file = $this->createFile($filepath, NULL, 'public');
$url = file_create_url($file->getFileUri());
$expected_url = $test_base_url . '/' . basename($filepath);
$this->assertEqual($url, $expected_url);
}
/**

View file

@ -35,8 +35,7 @@ class FileFieldValidateTest extends FileFieldTestBase {
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
$this->assertText('1 error has been found: ' . $field->label(), 'Node save failed when required file field was empty.');
$this->assertIdentical(1, count($this->xpath('//div[contains(concat(" ", normalize-space(@class), " "), :class)]//a', [':class' => ' messages--error '])), 'There is one link in the error message.');
$this->assertRaw(t('@title field is required.', array('@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);
@ -57,8 +56,7 @@ class FileFieldValidateTest extends FileFieldTestBase {
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
$this->assertText('1 error has been found: ' . $field->label(), 'Node save failed when required multiple value file field was empty.');
$this->assertIdentical(1, count($this->xpath('//div[contains(concat(" ", normalize-space(@class), " "), :class)]//a', [':class' => ' messages--error '])), 'There is one link in the error message.');
$this->assertRaw(t('@title field is required.', array('@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);

View file

@ -10,6 +10,7 @@ namespace Drupal\file\Tests;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Tests\FieldUnitTestBase;
/**
@ -33,6 +34,13 @@ class FileItemTest extends FieldUnitTestBase {
*/
protected $file;
/**
* Directory where the sample files are stored.
*
* @var string
*/
protected $directory;
protected function setUp() {
parent::setUp();
@ -45,10 +53,12 @@ class FileItemTest extends FieldUnitTestBase {
'type' => 'file',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
))->save();
$this->directory = $this->getRandomGenerator()->name(8);
entity_create('field_config', array(
'entity_type' => 'entity_test',
'field_name' => 'file_test',
'bundle' => 'entity_test',
'settings' => array('file_directory' => $this->directory),
))->save();
file_put_contents('public://example.txt', $this->randomMachineName());
$this->file = entity_create('file', array(
@ -61,6 +71,12 @@ class FileItemTest extends FieldUnitTestBase {
* Tests using entity fields of the file field type.
*/
public function testFileItem() {
// Check that the selection handler was automatically assigned to
// 'default:file'.
$field_definition = FieldConfig::load('entity_test.entity_test.file_test');
$handler_id = $field_definition->getSetting('handler');
$this->assertEqual($handler_id, 'default:file');
// Create a test entity with the
$entity = entity_create('entity_test');
$entity->file_test->target_id = $this->file->id();
@ -100,6 +116,9 @@ class FileItemTest extends FieldUnitTestBase {
$entity = entity_create('entity_test');
$entity->file_test->generateSampleItems();
$this->entityValidateAndSave($entity);
// Verify that the sample file was stored in the correct directory.
$uri = $entity->file_test->entity->getFileUri();
$this->assertEqual($this->directory, dirname(file_uri_target($uri)));
// Make sure the computed files reflects updates to the file.
file_put_contents('public://example-3.txt', $this->randomMachineName());

View file

@ -154,4 +154,26 @@ class FileManagedFileElementTest extends FileFieldTestBase {
$this->assertNoFieldByXpath('//input[@name="nested[file][file_' . $fid_list[0] . '][selected]"]', NULL, 'An individual file can be deleted from a multiple file element.');
$this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[1] . '][selected]"]', NULL, 'Second individual file not deleted when the first file is deleted from a multiple file element.');
}
/**
* Ensure that warning is shown if file on the field has been removed.
*/
public function testManagedFileRemoved() {
$this->drupalGet('file/test/1/0/1');
$test_file = $this->getTestFile('text');
$file_field_name = 'files[nested_file][]';
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$this->drupalPostForm(NULL, $edit, t('Upload'));
$fid = $this->getLastFileId();
$file = \Drupal::entityManager()->getStorage('file')->load($fid);
$file->delete();
$this->drupalPostForm(NULL, $edit, t('Upload'));
// We expect the title 'Managed <em>file & butter</em>' which got escaped
// via a t() call before.
$this->assertRaw('The file referenced by the Managed <em>file &amp; butter</em> field does not exist.');
}
}

View file

@ -56,7 +56,7 @@ class FileTokenReplaceTest extends FileFieldTestBase {
$tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:owner]'] = Html::escape(user_format_name($this->adminUser));
$tests['[file:owner]'] = Html::escape($this->adminUser->getDisplayName());
$tests['[file:owner:uid]'] = $file->getOwnerId();
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($file);

View file

@ -19,13 +19,6 @@ class MigrateFileConfigsTest extends MigrateDrupal6TestBase {
use SchemaCheckTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('file');
/**
* {@inheritdoc}
*/

View file

@ -8,11 +8,13 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Component\Utility\Random;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate\Tests\MigrateDumpAlterInterface;
use Drupal\Core\Database\Database;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
use Drupal\simpletest\TestBase;
use Drupal\file\Entity\File;
/**
* file migration.
@ -28,13 +30,6 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
*/
protected static $tempFilename;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('file');
/**
* {@inheritdoc}
*/
@ -45,33 +40,53 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
$this->installConfig(['file']);
/** @var \Drupal\migrate\Entity\MigrationInterface $migration */
$migration = entity_load('migration', 'd6_file');
$migration = Migration::load('d6_file');
$source = $migration->get('source');
$source['site_path'] = 'core/modules/simpletest';
$migration->set('source', $source);
$this->executeMigration($migration);
$this->standalone = TRUE;
}
/**
* Asserts a file entity.
*
* @param integer $fid
* The file ID.
* @param string $name
* The expected file name.
* @param integer $size
* The expected file size.
* @param string $uri
* The expected file URI.
* @param string $type
* The expected MIME type.
* @param integer $uid
* The expected file owner ID.
*/
protected function assertEntity($fid, $name, $size, $uri, $type, $uid) {
/** @var \Drupal\file\FileInterface $file */
$file = File::load($fid);
$this->assertTrue($file instanceof FileInterface);
$this->assertIdentical($name, $file->getFilename());
$this->assertIdentical($size, $file->getSize());
$this->assertIdentical($uri, $file->getFileUri());
$this->assertIdentical($type, $file->getMimeType());
$this->assertIdentical($uid, $file->getOwnerId());
}
/**
* Tests the Drupal 6 files to Drupal 8 migration.
*/
public function testFiles() {
/** @var \Drupal\file\FileInterface $file */
$file = File::load(1);
$this->assertIdentical('Image1.png', $file->getFilename());
$this->assertIdentical('39325', $file->getSize());
$this->assertIdentical('public://image-1.png', $file->getFileUri());
$this->assertIdentical('image/png', $file->getMimeType());
$this->assertIdentical("1", $file->getOwnerId());
// It is pointless to run the second half from MigrateDrupal6Test.
if (empty($this->standalone)) {
return;
}
$this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
$this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
$this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
$this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
// Test that we can re-import and also test with file_directory_path set.
db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
\Drupal::database()
->truncate(Migration::load('d6_file')->getIdMap()->mapTableName())
->execute();
// Update the file_directory_path.
Database::getConnection('default', 'migrate')
@ -85,7 +100,7 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
->condition('name', 'file_directory_temp')
->execute();
$migration = entity_load_unchanged('migration', 'd6_file');
$migration = \Drupal::entityManager()->getStorage('migration')->loadUnchanged('d6_file');
$this->executeMigration($migration);
$file = File::load(2);
@ -94,6 +109,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
// Ensure that a temporary file has been migrated.
$file = File::load(6);
$this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
// File 7, created in static::migrateDumpAlter(), shares a path with
// file 5, which means it should be skipped entirely.
$this->assertNull(File::load(7));
}
/**
@ -115,8 +134,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
static::$tempFilename = $test->getDatabasePrefix() . $random->name() . '.jpg';
$file_path = $temp_directory . '/' . static::$tempFilename;
file_put_contents($file_path, '');
Database::getConnection('default', 'migrate')
->update('files')
$db = Database::getConnection('default', 'migrate');
$db->update('files')
->condition('fid', 6)
->fields(array(
'filename' => static::$tempFilename,
@ -124,6 +145,14 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
))
->execute();
$file = (array) $db->select('files')
->fields('files')
->condition('fid', 5)
->execute()
->fetchObject();
unset($file['fid']);
$db->insert('files')->fields($file)->execute();
return static::$tempFilename;
}

View file

@ -1,100 +0,0 @@
<?php
/**
* @file
* Contains \Drupal\file\Tests\Migrate\d6\MigrateUploadBase.
*/
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
* Base class for file/upload migration tests.
*/
abstract class MigrateUploadBase extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('file');
$this->installEntitySchema('node');
$this->installSchema('file', ['file_usage']);
$this->installSchema('node', ['node_access']);
// Create new file entities.
for ($i = 1; $i <= 3; $i++) {
$file = entity_create('file', array(
'fid' => $i,
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => "public://druplicon-$i.txt",
'filemime' => 'text/plain',
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
$file->enforceIsNew();
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
$id_mappings['d6_file'][] = array(array($i), array($i));
}
// Add a node type.
$node_type = entity_create('node_type', array('type' => 'story'));
$node_type->save();
// Add a file field.
entity_create('field_storage_config', array(
'field_name' => 'upload',
'entity_type' => 'node',
'type' => 'file',
'cardinality' => -1,
'settings' => array(
'display_field' => TRUE,
),
))->save();
entity_create('field_config', array(
'field_name' => 'upload',
'entity_type' => 'node',
'bundle' => 'story',
))->save();
$id_mappings['d6_node'] = array(
array(array(1), array(1)),
array(array(2), array(2)),
);
$id_mappings['d6_upload_field_instance'] = [
[['story'], ['node', 'story', 'upload']],
];
$this->prepareMigrations($id_mappings);
$vids = array(1, 2, 3);
for ($i = 1; $i <= 2; $i++) {
$node = entity_create('node', array(
'type' => 'story',
'nid' => $i,
'vid' => array_shift($vids),
'title' => $this->randomString(),
));
$node->enforceIsNew();
$node->save();
if ($i == 1) {
$node->vid->value = array_shift($vids);
$node->enforceIsNew(FALSE);
$node->isDefaultRevision(FALSE);
$node->save();
}
}
}
}

View file

@ -7,6 +7,8 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -16,29 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('node', 'file');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'article'))->save();
entity_create('node_type', array('type' => 'story'))->save();
entity_create('node_type', array('type' => 'page'))->save();
$id_mappings = array(
'd6_upload_field_instance' => array(
array(array(1), array('node', 'page', 'upload')),
),
);
$this->prepareMigrations($id_mappings);
$this->migrateFields();
$this->executeMigration('d6_upload_entity_display');
}
@ -46,20 +31,20 @@ class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
* Tests the Drupal 6 upload settings to Drupal 8 entity display migration.
*/
public function testUploadEntityDisplay() {
$display = entity_get_display('node', 'page', 'default');
$display = EntityViewDisplay::load('node.page.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_default', $component['type']);
$display = entity_get_display('node', 'story', 'default');
$display = EntityViewDisplay::load('node.story.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_default', $component['type']);
// Assure this doesn't exist.
$display = entity_get_display('node', 'article', 'default');
$display = EntityViewDisplay::load('node.article.default');
$component = $display->getComponent('upload');
$this->assertTrue(is_null($component));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), entity_load('migration', 'd6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), Migration::load('d6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -7,6 +7,8 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -16,29 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'article'))->save();
entity_create('node_type', array('type' => 'story'))->save();
entity_create('node_type', array('type' => 'page'))->save();
$id_mappings = array(
'd6_upload_field_instance' => array(
array(array(1), array('node', 'page', 'upload')),
),
);
$this->prepareMigrations($id_mappings);
$this->migrateFields();
$this->executeMigration('d6_upload_entity_form_display');
}
@ -46,20 +31,20 @@ class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
* Tests the Drupal 6 upload settings to Drupal 8 entity form display migration.
*/
public function testUploadEntityFormDisplay() {
$display = entity_get_form_display('node', 'page', 'default');
$display = EntityFormDisplay::load('node.page.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_generic', $component['type']);
$display = entity_get_form_display('node', 'story', 'default');
$display = EntityFormDisplay::load('node.story.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_generic', $component['type']);
// Assure this doesn't exist.
$display = entity_get_form_display('node', 'article', 'default');
$display = EntityFormDisplay::load('node.article.default');
$component = $display->getComponent('upload');
$this->assertTrue(is_null($component));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), entity_load('migration', 'd6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), Migration::load('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -17,19 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('d6_upload_field');
$this->migrateFields();
}
/**
@ -38,7 +32,7 @@ class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
public function testUpload() {
$field_storage = FieldStorageConfig::load('node.upload');
$this->assertIdentical('node.upload', $field_storage->id());
$this->assertIdentical(array('node', 'upload'), entity_load('migration', 'd6_upload_field')->getIdMap()->lookupDestinationID(array('')));
$this->assertIdentical(array('node', 'upload'), Migration::load('d6_upload_field')->getIdMap()->lookupDestinationID(array('')));
}
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\field\Entity\FieldConfig;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -17,41 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Add some node mappings to get past checkRequirements().
$id_mappings = array(
'd6_upload_field' => array(
array(array(1), array('node', 'upload')),
),
'd6_node_type' => array(
array(array('page'), array('page')),
array(array('story'), array('story')),
),
);
$this->prepareMigrations($id_mappings);
foreach (array('page', 'story') as $type) {
entity_create('node_type', array('type' => $type))->save();
}
entity_create('field_storage_config', array(
'entity_type' => 'node',
'field_name' => 'upload',
'type' => 'file',
'translatable' => '0',
))->save();
$this->executeMigration('d6_upload_field_instance');
$this->migrateFields();
}
/**
@ -72,7 +44,7 @@ class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
$field = FieldConfig::load('node.article.upload');
$this->assertTrue(is_null($field));
$this->assertIdentical(array('node', 'page', 'upload'), entity_load('migration', 'd6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'upload'), Migration::load('d6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -7,6 +7,9 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\file\Entity\File;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
use Drupal\node\Entity\Node;
/**
@ -14,32 +17,58 @@ use Drupal\node\Entity\Node;
*
* @group migrate_drupal_6
*/
class MigrateUploadTest extends MigrateUploadBase {
class MigrateUploadTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$id_mappings = array(
'd6_node:*' => array(
array(
array(0),
array(0),
),
),
);
$this->installEntitySchema('file');
$this->installEntitySchema('node');
$this->installSchema('file', ['file_usage']);
$this->installSchema('node', ['node_access']);
$id_mappings = array('d6_file' => array());
// Create new file entities.
for ($i = 1; $i <= 3; $i++) {
$file = File::create(array(
'fid' => $i,
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => "public://druplicon-$i.txt",
'filemime' => 'text/plain',
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
$file->enforceIsNew();
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
$id_mappings['d6_file'][] = array(array($i), array($i));
}
$this->prepareMigrations($id_mappings);
$this->executeMigration('d6_upload');
$this->migrateContent();
// Since we are only testing a subset of the file migration, do not check
// that the full file migration has been run.
$migration = Migration::load('d6_upload');
$migration->set('requirements', []);
$this->executeMigration($migration);
}
/**
* Test upload migration from Drupal 6 to Drupal 8.
*/
function testUpload() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$node_storage->resetCache(array(1, 2));
$nodes = Node::loadMultiple(array(1, 2));
$this->container->get('entity.manager')
->getStorage('node')
->resetCache([1, 2]);
$nodes = Node::loadMultiple([1, 2]);
$node = $nodes[1];
$this->assertIdentical(1, count($node->upload));
$this->assertIdentical('1', $node->upload[0]->target_id);

View file

@ -220,7 +220,7 @@ 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', array('@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.
@ -254,7 +254,7 @@ 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', array('@filename' => $munged_filename)), 'File was successfully munged.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
@ -272,7 +272,7 @@ 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->image->getFilename())), 'File was not munged when allowing any extension.');
$this->assertRaw(t('File name is @filename', array('@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.

View file

@ -84,7 +84,7 @@ class RelationshipUserFileDataTest extends ViewTestBase {
'user',
],
];
$this->assertIdentical($expected, $view->calculateDependencies());
$this->assertIdentical($expected, $view->getDependencies());
$this->executeView($view);
$expected_result = array(
array(