getFileUri example

    $form_state->cleanValues();
    $form_state->unsetValue('var');
    $form_state->unsetValue('config_key');

    $values = $form_state->getValues();

    // If the user uploaded a new logo or favicon, save it to a permanent location     // and use it in place of the default theme-provided file.     $default_scheme = $this->config('system.file')->get('default_scheme');
    try {
      if (!empty($values['logo_upload'])) {
        $filename = $this->fileSystem->copy($values['logo_upload']->getFileUri()$default_scheme . '://');
        $values['default_logo'] = 0;
        $values['logo_path'] = $filename;
      }
    }
    catch (FileException $e) {
      // Ignore.     }
    try {
      if (!empty($values['favicon_upload'])) {
        $filename = $this->fileSystem->copy($values['favicon_upload']->getFileUri()$default_scheme . '://');
        $values['default_favicon'] = 0;
        
$image_style_setting = $this->getSetting('image_style');

    // Collect cache tags to be added for each item in the field.     $base_cache_tags = [];
    if (!empty($image_style_setting)) {
      $image_style = $this->imageStyleStorage->load($image_style_setting);
      $base_cache_tags = $image_style->getCacheTags();
    }

    foreach ($files as $delta => $file) {
      if (isset($link_file)) {
        $image_uri = $file->getFileUri();
        $url = $this->fileUrlGenerator->generate($image_uri);
      }
      $cache_tags = Cache::mergeTags($base_cache_tags$file->getCacheTags());

      // Extract field item attributes for the theme function, and unset them       // from the $item so that the field template does not re-render them.       $item = $file->_referringItem;
      $item_attributes = $item->_attributes;
      unset($item->_attributes);

      $image_loading_settings = $this->getSetting('image_loading');
      

  public function testViewsHandlerRelationshipFileToNode(): void {
    $file1 = File::create([
      'filename' => 'image-test.jpg',
      'uri' => "public://image-test.jpg",
      'filemime' => 'image/jpeg',
      'created' => 1,
      'changed' => 1,
      'status' => FileInterface::STATUS_PERMANENT,
    ]);
    $file1->enforceIsNew();
    file_put_contents($file1->getFileUri()file_get_contents('core/tests/fixtures/files/image-1.png'));
    $file1->save();

    $file2 = File::create([
      'filename' => 'image-test-2.jpg',
      'uri' => "public://image-test-2.jpg",
      'filemime' => 'image/jpeg',
      'created' => 1,
      'changed' => 1,
      'status' => FileInterface::STATUS_PERMANENT,
    ]);
    $file2->enforceIsNew();
    
'settings' => ['image_style' => $style_name],
      ])
      ->save();

    // Create a new node with an image attached.     $test_image = current($this->drupalGetTestFiles('image'));
    $nid = $this->uploadNodeImage($test_image$field_name, 'article', $this->randomMachineName());
    $node = Node::load($nid);

    // Get node field original image URI.     $fid = $node->get($field_name)->target_id;
    $original_uri = File::load($fid)->getFileUri();

    // Test that image is displayed using newly created style.     /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');

    $this->drupalGet('node/' . $nid);
    $this->assertSession()->responseContains($file_url_generator->transformRelative($style->buildUrl($original_uri)));

    // Rename the style and make sure the image field is updated.     $new_style_name = strtolower($this->randomMachineName(10));
    $new_style_label = $this->randomString();
    
$file = File::create([
        'fid' => $i,
        'uid' => 1,
        'filename' => 'druplicon.txt',
        'uri' => "public://druplicon-$i.txt",
        'filemime' => 'text/plain',
        'created' => 1,
        'changed' => 1,
      ]);
      $file->setPermanent();
      $file->enforceIsNew();
      file_put_contents($file->getFileUri(), 'hello world');

      // Save it, inserting a new record.       $file->save();
      $id_mappings['d6_file'][] = [[$i][$i]];
    }
    $this->prepareMigrations($id_mappings);

    $this->migrateContent(['translations']);
    // Since we are only testing a subset of the file migration, do not check     // that the full file migration has been run.     $migration = $this->getMigration('d6_upload');
    
return $file;
  }

  /** * {@inheritdoc} */
  public function copy(FileInterface $source, string $destination, int $replace = FileSystemInterface::EXISTS_RENAME): FileInterface {
    if (!$this->streamWrapperManager->isValidUri($destination)) {
      throw new InvalidStreamWrapperException("Invalid stream wrapper: {$destination}");
    }
    $uri = $this->fileSystem->copy($source->getFileUri()$destination$replace);

    // If we are replacing an existing file, load it.     if ($replace === FileSystemInterface::EXISTS_REPLACE && $existing = $this->loadByUri($uri)) {
      $file = $existing;
    }
    else {
      $file = $source->createDuplicate();
      $file->setFileUri($uri);

      // If we are renaming around an existing file (rather than a directory),       // use its basename for the filename.
// Assert that the default name was mapped into the name field for both     // media items.     $this->assertFalse($a->get('name')->isEmpty());
    $this->assertFalse($b->get('name')->isEmpty());

    // Assert that arbitrary metadata was mapped correctly.     $this->assertFalse($a->get('field_to_map_to')->isEmpty());
    $this->assertFalse($b->get('field_to_map_to')->isEmpty());

    // Assert that the thumbnail was mapped correctly from the source.     $this->assertSame('public://TheSisko.png', $a->thumbnail->entity->getFileUri());
    $this->assertSame('public://TheSisko.png', $b->thumbnail->entity->getFileUri());
  }

  /** * Tests default media name functionality. */
  public function testDefaultName() {
    // Make sure that the default name is set if not provided by the user.     /** @var \Drupal\media\MediaInterface $media */
    $media = Media::create(['bundle' => $this->testMediaType->id()]);
    $media_source = $media->getSource();
    
public static function process($element, FormStateInterface $form_state$form) {
    $item = $element['#value'];
    $item['fids'] = $element['fids']['#value'];

    $element['#theme'] = 'image_widget';

    // Add the image preview.     if (!empty($element['#files']) && $element['#preview_image_style']) {
      $file = reset($element['#files']);
      $variables = [
        'style_name' => $element['#preview_image_style'],
        'uri' => $file->getFileUri(),
      ];

      $dimension_key = $variables['uri'] . '.image_preview_dimensions';
      // Determine image dimensions.       if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
        $variables['width'] = $element['#value']['width'];
        $variables['height'] = $element['#value']['height'];
      }
      elseif ($form_state->has($dimension_key)) {
        $variables += $form_state->get($dimension_key);
      }
      

  public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
    $this->assertEquals($before->id()$after->id(), 'File id is the same');
    $this->assertEquals($before->getOwner()->id()$after->getOwner()->id(), 'File owner is the same');
    $this->assertEquals($before->getFilename()$after->getFilename(), 'File name is the same');
    $this->assertEquals($before->getFileUri()$after->getFileUri(), 'File path is the same');
    $this->assertEquals($before->getMimeType()$after->getMimeType(), 'File MIME type is the same');
    $this->assertEquals($before->getSize()$after->getSize(), 'File size is the same');
    $this->assertEquals($before->isPermanent()$after->isPermanent(), 'File status is the same');
  }

  /** * Asserts that two files are not the same by comparing the fid and filepath. * * @param \Drupal\file\FileInterface $file1 * File object to compare. * @param \Drupal\file\FileInterface $file2 * File object to compare. */
// Check if the correct source field values were saved/loaded.     foreach ($field_translations as $langcode => $items) {
      /** @var \Drupal\media\MediaInterface $media_translation */
      $media_translation = $media->getTranslation($langcode);
      $result = TRUE;
      foreach ($items as $delta => $item) {
        $result = $result && $item['value'] == $media_translation->{$source_field_definition->getName()}[$delta]->value;
      }
      $this->assertTrue($resultnew FormattableMarkup('%language translation field value not correct.', ['%language' => $langcode]));
      $this->assertSame('public://' . $langcode . '.png', $media_translation->getSource()->getMetadata($media_translation, 'thumbnail_uri')new FormattableMarkup('%language translation thumbnail metadata attribute is not correct.', ['%language' => $langcode]));
      $this->assertSame('public://' . $langcode . '.png', $media_translation->get('thumbnail')->entity->getFileUri()new FormattableMarkup('%language translation thumbnail value is not correct.', ['%language' => $langcode]));
      $this->assertEquals('Test Thumbnail ' . $langcode$media_translation->getSource()->getMetadata($media_translation, 'test_thumbnail_alt')new FormattableMarkup('%language translation thumbnail alt metadata attribute is not correct.', ['%language' => $langcode]));
      $this->assertSame('Test Thumbnail ' . $langcode$media_translation->get('thumbnail')->alt, new FormattableMarkup('%language translation thumbnail alt value is not correct.', ['%language' => $langcode]));
    }
  }

}

  public function preSave() {
    parent::preSave();

    $width = $this->width;
    $height = $this->height;

    // Determine the dimensions if necessary.     if ($this->entity && $this->entity instanceof EntityInterface) {
      if (empty($width) || empty($height)) {
        $image = \Drupal::service('image.factory')->get($this->entity->getFileUri());
        if ($image->isValid()) {
          $this->width = $image->getWidth();
          $this->height = $image->getHeight();
        }
      }
    }
    else {
      trigger_error(sprintf("Missing file with ID %s.", $this->target_id), E_USER_WARNING);
    }
  }

  

  public function testCreateDeletePicture() {
    $this->drupalLogin($this->webUser);

    // Save a new picture.     $image = current($this->drupalGetTestFiles('image'));
    $file = $this->saveUserPicture($image);

    // Verify that the image is displayed on the user account page.     $this->drupalGet('user');
    $this->assertSession()->responseContains(StreamWrapperManager::getTarget($file->getFileUri()));

    // Delete the picture.     $edit = [];
    $this->drupalGet('user/' . $this->webUser->id() . '/edit');
    $this->submitForm($edit, 'Remove');
    $this->submitForm([], 'Save');

    // Call file_cron() to clean up the file. Make sure the timestamp     // of the file is older than the system.file.temporary_maximum_age     // configuration value. We use an UPDATE statement because using the API     // would set the timestamp.
          $this->drupalGet($path);
          $this->submitForm([], 'Save');
          $this->assertSession()->pageTextContains("The file ids are .");

          // Submit with a file, but with an invalid form token. Ensure the file           // was not saved.           $last_fid_prior = $this->getLastFileId();
          $this->drupalGet($path);
          $form_token_field = $this->assertSession()->hiddenFieldExists('form_token');
          $form_token_field->setValue('invalid token');
          $edit = [
            $file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri()),
          ];
          $this->submitForm($edit, 'Save');
          $this->assertSession()->pageTextContains('The form has become outdated.');
          $last_fid = $this->getLastFileId();
          $this->assertEquals($last_fid_prior$last_fid, 'File was not saved when uploaded with an invalid form token.');

          // Submit a new file, without using the Upload button.           $last_fid_prior = $this->getLastFileId();
          $edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
          $this->drupalGet($path);
          $this->submitForm($edit, 'Save');
          


    $form['file_test_upload']['#upload_validators'] = $validators;
    $form['file_test_upload']['#upload_location'] = $destination;

    $this->messenger->addStatus($this->t('Number of error messages before _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));
    $file = _file_save_upload_from_form($form['file_test_upload']$form_state, 0, $form_state->getValue('file_test_replace'));
    $this->messenger->addStatus($this->t('Number of error messages after _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));

    if ($file) {
      $form_state->setValue('file_test_upload', $file);
      $this->messenger->addStatus($this->t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
      $this->messenger->addStatus($this->t('File name is @filename.', ['@filename' => $file->getFilename()]));
      $this->messenger->addStatus($this->t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
      $this->messenger->addStatus($this->t('You WIN!'));
    }
    elseif ($file === FALSE) {
      $this->messenger->addError($this->t('Epic upload FAIL!'));
    }
  }

  /** * {@inheritdoc} */


  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    $url = NULL;
    // Add support to link to the entity itself.     if ($this->getSetting('link_to_file')) {
      $url = $this->fileUrlGenerator->generate($items->getEntity()->getFileUri());
    }

    foreach ($items as $delta => $item) {
      $view_value = $this->viewValue($item);

      if ($url) {
        $elements[$delta] = [
          '#type' => 'link',
          '#title' => $view_value,
          '#url' => $url,
        ];
      }
Home | Imprint | This part of the site doesn't use cookies.