本文整理汇总了PHP中Drupal\file\Entity\File类的典型用法代码示例。如果您正苦于以下问题:PHP File类的具体用法?PHP File怎么用?PHP File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testFileValidateIsImage
/**
* This ensures a specific file is actually an image.
*/
function testFileValidateIsImage()
{
$this->assertTrue(file_exists($this->image->getFileUri()), 'The image being tested exists.', 'File');
$errors = file_validate_is_image($this->image);
$this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
$this->assertTrue(file_exists($this->nonImage->getFileUri()), 'The non-image being tested exists.', 'File');
$errors = file_validate_is_image($this->nonImage);
$this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
}
示例2: testImageItem
/**
* Tests using entity fields of the image field type.
*/
public function testImageItem()
{
// Create a test entity with the image field set.
$entity = EntityTest::create();
$entity->image_test->target_id = $this->image->id();
$entity->image_test->alt = $alt = $this->randomMachineName();
$entity->image_test->title = $title = $this->randomMachineName();
$entity->name->value = $this->randomMachineName();
$entity->save();
$entity = entity_load('entity_test', $entity->id());
$this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEqual($entity->image_test->target_id, $this->image->id());
$this->assertEqual($entity->image_test->alt, $alt);
$this->assertEqual($entity->image_test->title, $title);
$image = $this->imageFactory->get('public://example.jpg');
$this->assertEqual($entity->image_test->width, $image->getWidth());
$this->assertEqual($entity->image_test->height, $image->getHeight());
$this->assertEqual($entity->image_test->entity->id(), $this->image->id());
$this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid());
// Make sure the computed entity reflects updates to the referenced file.
file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example-2.jpg');
$image2 = File::create(['uri' => 'public://example-2.jpg']);
$image2->save();
$entity->image_test->target_id = $image2->id();
$entity->image_test->alt = $new_alt = $this->randomMachineName();
// The width and height is only updated when width is not set.
$entity->image_test->width = NULL;
$entity->save();
$this->assertEqual($entity->image_test->entity->id(), $image2->id());
$this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri());
$image = $this->imageFactory->get('public://example-2.jpg');
$this->assertEqual($entity->image_test->width, $image->getWidth());
$this->assertEqual($entity->image_test->height, $image->getHeight());
$this->assertEqual($entity->image_test->alt, $new_alt);
// Check that the image item can be set to the referenced file directly.
$entity->image_test = $this->image;
$this->assertEqual($entity->image_test->target_id, $this->image->id());
// Delete the image and try to save the entity again.
$this->image->delete();
$entity = EntityTest::create(array('mame' => $this->randomMachineName()));
$entity->save();
// Test image item properties.
$expected = array('target_id', 'entity', 'alt', 'title', 'width', 'height');
$properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
$this->assertEqual(array_keys($properties), $expected);
// Test the generateSampleValue() method.
$entity = EntityTest::create();
$entity->image_test->generateSampleItems();
$this->entityValidateAndSave($entity);
$this->assertEqual($entity->image_test->entity->get('filemime')->value, 'image/jpeg');
}
示例3: testEmbedButtonIconUsage
/**
* Tests the embed_button and file usage integration.
*/
public function testEmbedButtonIconUsage()
{
$this->enableModules(['system', 'user', 'file']);
$this->installSchema('file', ['file_usage']);
$this->installConfig(['system']);
$this->installEntitySchema('user');
$this->installEntitySchema('file');
$this->installEntitySchema('embed_button');
$file1 = file_save_data(file_get_contents('core/misc/druplicon.png'));
$file1->setTemporary();
$file1->save();
$file2 = file_save_data(file_get_contents('core/misc/druplicon.png'));
$file2->setTemporary();
$file2->save();
$button = array('id' => 'test_button', 'label' => 'Testing embed button instance', 'type_id' => 'embed_test_default', 'icon_uuid' => $file1->uuid());
$entity = EmbedButton::create($button);
$entity->save();
$this->assertTrue(File::load($file1->id())->isPermanent());
// Delete the icon from the button.
$entity->icon_uuid = NULL;
$entity->save();
$this->assertTrue(File::load($file1->id())->isTemporary());
$entity->icon_uuid = $file1->uuid();
$entity->save();
$this->assertTrue(File::load($file1->id())->isPermanent());
$entity->icon_uuid = $file2->uuid();
$entity->save();
$this->assertTrue(File::load($file1->id())->isTemporary());
$this->assertTrue(File::load($file2->id())->isPermanent());
$entity->delete();
$this->assertTrue(File::load($file2->id())->isTemporary());
}
示例4: testFileDenormalize
/**
* Tests file entity denormalization.
*/
public function testFileDenormalize()
{
$file_params = array('filename' => 'test_1.txt', 'uri' => 'public://test_1.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
// Create a new file entity.
$file = File::create($file_params);
file_put_contents($file->getFileUri(), 'hello world');
$file->save();
$serializer = \Drupal::service('serializer');
$normalized_data = $serializer->normalize($file, 'hal_json');
$denormalized = $serializer->denormalize($normalized_data, 'Drupal\\file\\Entity\\File', 'hal_json');
$this->assertTrue($denormalized instanceof File, 'A File instance was created.');
$this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.');
$this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
$this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found');
$this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.');
$this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.');
$this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.');
// Try to denormalize with the file uri only.
$file_name = 'test_2.txt';
$file_path = 'public://' . $file_name;
file_put_contents($file_path, 'hello world');
$file_uri = file_create_url($file_path);
$data = array('uri' => array(array('value' => $file_uri)));
$denormalized = $serializer->denormalize($data, 'Drupal\\file\\Entity\\File', 'hal_json');
$this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.');
$this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
$this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.');
$this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.');
$this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.');
}
示例5: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
drupal_set_message('Settings saved');
// Fetch the file id previously saved.
$config = $this->config('cfia_base.settings');
$old_fid = $config->get('cfia_frontpage.frontpage_image', '');
// Load the file set in the form.
$value = $form_state->getValue('frontpage_image');
$form_fid = count($value) > 0 ? $value[0] : 0;
$file = $form_fid ? File::load($form_fid) : FALSE;
// If a file is set.
if ($file) {
$fid = $file->id();
// Check if the file has changed.
if ($fid != $old_fid) {
// Remove old file.
if ($old_fid) {
removeFile($old_fid);
}
// Add file to file_usage table.
\Drupal::service('file.usage')->add($file, 'cfia_base', 'user', '1');
}
} else {
// If old file exists but no file set in form, remove old file.
if ($old_fid) {
removeFile($old_fid);
}
}
$this->configFactory()->getEditable('cfia_base.settings')->set('cfia_frontpage.frontpage_title', $form_state->getValue('frontpage_title'))->set('cfia_frontpage.frontpage_lead', $form_state->getValue('frontpage_lead'))->set('cfia_frontpage.frontpage_sub', $form_state->getValue('frontpage_sub'))->set('cfia_frontpage.frontpage_button', $form_state->getValue('frontpage_button'))->set('cfia_frontpage.frontpage_link', $form_state->getValue('frontpage_link'))->set('cfia_footer.footer_text', $form_state->getValue('footer_text')['value'])->set('cfia_footer.footer_twitter', $form_state->getValue('footer_twitter'))->set('cfia_footer.footer_instagram', $form_state->getValue('footer_instagram'))->set('cfia_footer.footer_linkedin', $form_state->getValue('footer_linkedin'))->set('cfia_frontpage.frontpage_image', $file ? $file->id() : NULL)->save();
}
示例6: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
// Pass the file to the parser.
$fid = $form_state->getValue('mtg_import_json_file');
$fid = reset($fid);
if ($fid == 0) {
return FALSE;
}
$file = File::load($fid);
if (!$file) {
drupal_set_message('Unable to load file.');
\Drupal::logger('mtg_import')->error(t('Unable to load the file.'));
return FALSE;
}
$uri = $file->uri->value;
$file_contents_raw = file_get_contents($uri);
$file_contents = json_decode($file_contents_raw);
if (!empty($file_contents->cards)) {
$operations = [['mtg_import_parse_set_data', [$file_contents]]];
$chunks = array_chunk($file_contents->cards, 20);
foreach ($chunks as $chunk) {
$operations[] = ['mtg_import_parse_card_data', [$chunk]];
}
$batch = ['title' => t('Importing'), 'operations' => $operations, 'finished' => 'mtg_import_completed', 'progress_message' => t('Completed part @current of @total.')];
batch_set($batch);
} else {
drupal_set_message(t('There are no cards in the file, so no import will take place.'), 'warning');
}
}
示例7: testFileAccess
/**
* 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');
}
示例8: testPrivateFile
/**
* Tests file access for file uploaded to a private node.
*/
function testPrivateFile()
{
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
$this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private'));
// 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'));
$test_file = $this->getTestFile('text');
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
$node = node_load($nid, TRUE);
$node_file = file_load($node->{$field_name}->target_id);
// Ensure the file can be downloaded.
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
$this->drupalLogOut();
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
// Test with the field that should deny access through field access.
$this->drupalLogin($this->admin_user);
$nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
\Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
$node = Node::load($nid);
$node_file = File::load($node->{$no_access_field_name}->target_id);
// Ensure the file cannot be downloaded.
$user = $this->drupalCreateUser(array('access content'));
$this->drupalLogin($user);
$this->drupalGet(file_create_url($node_file->getFileUri()));
$this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
}
示例9: testInUse
/**
* Tries deleting a file that is in use.
*/
function testInUse()
{
$file = $this->createFile();
$file_usage = $this->container->get('file.usage');
$file_usage->add($file, 'testing', 'test', 1);
$file_usage->add($file, 'testing', 'test', 1);
$file_usage->delete($file, 'testing', 'test', 1);
$usage = $file_usage->listUsage($file);
$this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
$this->assertTrue(File::load($file->id()), 'File still exists in the database.');
// Clear out the call to hook_file_load().
file_test_reset();
$file_usage->delete($file, 'testing', 'test', 1);
$usage = $file_usage->listUsage($file);
$this->assertFileHooksCalled(array('load', 'update'));
$this->assertTrue(empty($usage), 'File usage data was removed.');
$this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.');
$file = File::load($file->id());
$this->assertTrue($file, 'File still exists in the database.');
$this->assertTrue($file->isTemporary(), 'File is temporary.');
file_test_reset();
// 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('changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1)))->condition('fid', $file->id())->execute();
\Drupal::service('cron')->run();
// file_cron() loads
$this->assertFileHooksCalled(array('delete'));
$this->assertFalse(file_exists($file->getFileUri()), 'File has been deleted after its last usage was removed.');
$this->assertFalse(File::load($file->id()), 'File was removed from the database.');
}
示例10: content
public function content($nid) {
$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$fields = $node->getFieldDefinitions();
$fcArray = [];
foreach ($fields as $field){
$type = $field->getType();
if ($type == 'field_collection') {
$field_collection = $field->get('field_name');
foreach ($node->$field_collection as $key => $item){
$item = $item->value;
// $fcArray[$key];
$fc = FieldCollectionItem::load($item);
foreach ($fc as $fckey => $field){
$fcArray[$key][$fckey] = $field->value;
if (is_object($field[0]) && $field[0]->height){
$image = File::load($field[0]->target_id);
$fcArray[$key][$fckey] = str_replace('public://', '/drupal/sites/default/files/', $image->uri->value);
$fcArray[$key]['field_mosaic_image_alt'] = $field[0]->alt;
}
if (is_object($field[0]) && $field[0]->uri){
$fcArray[$key][$fckey] = str_replace('internal:', '', $field[0]->uri);
}
}
}
}
}
return new JsonResponse($fcArray);
}
示例11: testSubRequestDependent
/**
* Test a gallery embedded in a view row that is dependent on the Juicebox
* cache.
*/
public function testSubRequestDependent()
{
$node = $this->node;
$xml_path = 'juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/_custom';
$xml_url = \Drupal::url('juicebox.xml_field', array('entityType' => 'node', 'entityId' => $node->id(), 'fieldName' => $this->instFieldName, 'displayName' => '_custom'));
// Get the urls to the test image and thumb derivative used by default.
$uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri();
$test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri);
$test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri);
// Check for correct embed markup. This will also prime the cache.
$content = $this->drupalGet('juicebox_test_row_formatter');
$this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.');
$this->assertRaw('id="node--' . $node->id() . '--' . str_replace('_', '-', $this->instFieldName) . '---custom"', 'Embed code wrapper found.');
$this->assertRaw(Html::escape($test_image_url), 'Test image found in embed code');
// Extract the xml-source values from the XML.
$matches = array();
// In the pattern below we have to use four (yeah, FOUR) backslashes to
// match a SINGLE literal backslash. Our source will contain an encoded
// (JSON) "&" character as "\u0026", but we don't want the regex to confuse
// that with an actaul "&" char in the pattern itself.
preg_match('|xml-source-path=([a-z1-9_-]+)\\\\u0026xml-source-id=([a-z1-9-]+)|', $content, $matches);
$this->assertNotNull($matches[1], 'xml-source-path value found in Drupal.settings.');
$this->assertNotNull($matches[2], 'xml-source-id value found in Drupal.settings.');
// Check for correct XML. This example is dependent on a sub-request XML
// lookup, so everything below would fail without that feature.
$this->drupalGet($xml_path, array('query' => array('xml-source-path' => $matches[1], 'xml-source-id' => $matches[2])));
$this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.');
$this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.' . $test_image_url);
$this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.' . $test_thumb_url);
$this->assertRaw('backgroundcolor="green"', 'Custom background setting from pseudo field instance config found in XML.');
}
示例12: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $grouping = NULL)
{
// Load logo image.
$rendered_image = NULL;
if (!empty($grouping->logo_fid)) {
$file = File::load($grouping->logo_fid);
if ($file) {
$logo_url = ImageStyle::load('ea_groupings_200x200')->buildUrl($file->getFileUri());
$image_array = array('#theme' => 'image', '#uri' => $logo_url, '#alt' => $this->t('Logo for @grouping', array('@grouping' => $grouping->title)), '#title' => $this->t('@grouping', array('@grouping' => $grouping->title)));
$rendered_image = \Drupal::service('renderer')->render($image_array);
}
}
// Construct form.
$form = array();
$form['gid'] = array('#type' => 'value', '#value' => $grouping->gid);
$form['add'] = array('#type' => 'fieldset', '#description' => $this->t('Update grouping'), '#title' => $this->t('Edit grouping'));
$form['add']['title'] = array('#type' => 'textfield', '#title' => $this->t('Title'), '#description' => $this->t('Title of grouping'), '#size' => 20, '#maxlength' => 20, '#required' => FALSE, '#default_value' => $grouping->title);
$form['add']['description'] = array('#type' => 'textarea', '#title' => $this->t('Description'), '#description' => $this->t('A short description of the grouping'), '#required' => FALSE, '#default_value' => $grouping->description);
$form['add']['logo'] = array('#type' => 'markup', '#markup' => $rendered_image);
$form['add']['logo_fid'] = array('#title' => $this->t('Update logo'), '#type' => 'managed_file', '#description' => $this->t('Upload a logo for the grouping'), '#default_value' => NULL, '#upload_location' => 'public://logos/');
$form['add']['time_zone'] = array('#title' => $this->t('Timezone'), '#type' => 'select', '#description' => $this->t('Select a time zone for the grouping'), '#options' => _ea_groupings_get_time_zones(), '#default_value' => $grouping->time_zone);
$form['add']['parent_gid'] = array('#type' => 'select', '#description' => $this->t('Select a parent grouping'), '#options' => _ea_groupings_get_groupings_list(FALSE, $grouping->gid), '#disabled' => _ea_groupings_is_parent($grouping->gid), '#default_value' => $grouping->parent_gid);
$form['add']['submit'] = array('#type' => 'submit', '#name' => 'add_group', '#value' => $this->t('Update grouping'), '#weight' => 100);
$form['add']['old_title'] = array('#type' => 'value', '#value' => $grouping->title);
$form['add']['old_logo_fid'] = array('#type' => 'value', '#value' => $grouping->logo_fid);
$form['add']['old_parent_gid'] = array('#type' => 'value', '#value' => $grouping->parent_gid);
return $form;
}
示例13: testFileFieldRSSContent
/**
* Tests RSS enclosure formatter display for RSS feeds.
*/
function testFileFieldRSSContent()
{
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
$this->createFileField($field_name, 'node', $type_name);
// RSS display must be added manually.
$this->drupalGet("admin/structure/types/manage/{$type_name}/display");
$edit = array("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');
$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));
$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 = $node_storage->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
// Check that the RSS enclosure appears in the RSS feed.
$this->drupalGet('rss.xml');
$uploaded_filename = str_replace('public://', '', $node_file->getFileUri());
$test_element = sprintf('<enclosure url="%s" length="%s" type="%s" />', file_create_url("public://{$uploaded_filename}", array('absolute' => TRUE)), $node_file->getSize(), $node_file->getMimeType());
$this->assertRaw($test_element, 'File field RSS enclosure is displayed when viewing the RSS feed.');
}
示例14: testTaxonomyImageAccess
public function testTaxonomyImageAccess()
{
$user = $this->drupalCreateUser(array('administer site configuration', 'administer taxonomy', 'access user profiles'));
$this->drupalLogin($user);
// Create a term and upload the image.
$files = $this->drupalGetTestFiles('image');
$image = array_pop($files);
$edit['name[0][value]'] = $this->randomMachineName();
$edit['files[field_test_0]'] = drupal_realpath($image->uri);
$this->drupalPostForm('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add', $edit, t('Save'));
$this->drupalPostForm(NULL, ['field_test[0][alt]' => $this->randomMachineName()], t('Save'));
$terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $edit['name[0][value]']));
$term = reset($terms);
$this->assertText(t('Created new term @name.', array('@name' => $term->getName())));
// Create a user that should have access to the file and one that doesn't.
$access_user = $this->drupalCreateUser(array('access content'));
$no_access_user = $this->drupalCreateUser();
$image = File::load($term->field_test->target_id);
$this->drupalLogin($access_user);
$this->drupalGet(file_create_url($image->getFileUri()));
$this->assertResponse(200, 'Private image on term is accessible with right permission');
$this->drupalLogin($no_access_user);
$this->drupalGet(file_create_url($image->getFileUri()));
$this->assertResponse(403, 'Private image on term not accessible without right permission');
}
示例15: testFiles
/**
* 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;
}
// Test that we can re-import and also test with file_directory_path set.
db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
// Update the file_directory_path.
Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize($this->getTempFilesDirectory())))->condition('name', 'file_directory_temp')->execute();
$migration = entity_load_unchanged('migration', 'd6_file');
$this->executeMigration($migration);
$file = File::load(2);
$this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
// Ensure that a temporary file has been migrated.
$file = File::load(6);
$this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
}