setPermanent example

// Create new file entities.     for ($i = 1; $i <= 3; $i++) {
      $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
FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
    );
    // Add the media field to the form display.     \Drupal::service('entity_display.repository')->getFormDisplay('node', 'article')
      ->setComponent('field_media', ['type' => 'media_library_widget'])
      ->save();

    // Create a file to user for our images.     $image = File::create([
      'uri' => $this->getTestFiles('image')[0]->uri,
    ]);
    $image->setPermanent();
    $image->save();

    // Create a translated and untranslated media item in each language.     // cSpell:disable     $media_items = [
      ['nl' => 'Eekhoorn', 'es' => 'Ardilla'],
      ['es' => 'Zorro', 'nl' => 'Vos'],
      ['nl' => 'Hert'],
      ['es' => 'Tejón'],
    ];
    // cSpell:enable


  $form['#submit'][] = 'test_theme_settings_form_system_theme_settings_submit';
}

/** * Test theme form settings submission handler. */
function test_theme_settings_form_system_theme_settings_submit(&$form, FormStateInterface $form_state) {
  if ($file_id = $form_state->getValue(['custom_logo', '0'])) {
    $file = File::load($file_id);
    $file->setPermanent();
    $file->save();
  }
}

  protected function createPrivateFile($file_name) {
    // Create a new file entity.     $file = File::create([
      'uid' => 1,
      'filename' => $file_name,
      'uri' => "private://$file_name",
      'filemime' => 'text/plain',
    ]);
    $file->setPermanent();
    file_put_contents($file->getFileUri()$this->getFileSecret($file));
    $file->save();
    return $file;
  }

  /** * Returns the href of a file, asserting it is accessible on the page. * * @param \Drupal\file\FileInterface $file * The file entity. * * @return string * The file href. */
$tags[] = mt_rand(1, $num_tags);
          $tags = array_unique($tags);
        }
        $values['field_tags'] = array_map(function D$tag) {
          return ['target_id' => $tag];
        }$tags);
      }
      if ($article_has_image) {
        $file = File::create([
          'uri' => 'public://' . $random->name() . '.png',
        ]);
        $file->setPermanent();
        $file->save();
        $this->files[] = $file;
        $values['field_image'] = ['target_id' => $file->id(), 'alt' => 'alt text'];
      }
      if ($article_has_link) {
        $values['field_link'] = [
          'title' => $this->getRandomGenerator()->name(),
          'uri' => sprintf(
            '%s://%s.%s',
            'http' . (mt_rand(0, 2) > 1 ? '' : 's'),
            $this->getRandomGenerator()->name(),
            


  /** * {@inheritdoc} */
  public function createNewEntity($entity_type_id$bundle$label$uid) {
    $file = parent::createNewEntity($entity_type_id$bundle$label$uid);

    // In order to create a referenceable file, it needs to have a "permanent"     // status.     /** @var \Drupal\file\FileInterface $file */
    $file->setPermanent();

    return $file;
  }

  /** * {@inheritdoc} */
  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);
    $entities = array_filter($entitiesfunction D$file) {
      /** @var \Drupal\file\FileInterface $file */
      
->set('make_unused_managed_files_temporary', FALSE)
      ->save();
    $file = $this->doTestRemoveUsage();
    $this->assertFalse($file->isTemporary());
  }

  /** * Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::delete(). */
  public function doTestRemoveUsage() {
    $file = $this->createFile();
    $file->setPermanent();
    $file_usage = $this->container->get('file.usage');
    $connection = Database::getConnection();
    $connection->insert('file_usage')
      ->fields([
        'fid' => $file->id(),
        'module' => 'testing',
        'type' => 'bar',
        'id' => 2,
        'count' => 3,
      ])
      ->execute();

    
'type' => 'media_library_widget',
    ])->save();

    // Configure the "Editorial" workflow to apply to image media.     $workflow = $this->createEditorialWorkflow();
    $workflow->getTypePlugin()->addEntityTypeAndBundle('media', 'image');
    $workflow->save();

    $image = File::create([
      'uri' => $this->getTestFiles('image')[0]->uri,
    ]);
    $image->setPermanent();
    $image->save();

    // Create a draft, published and archived media item.     $draft_media = Media::create([
      'name' => 'Hoglet',
      'bundle' => 'image',
      'field_media_image' => $image,
      'moderation_state' => 'draft',
    ]);
    $draft_media->save();
    $published_media = Media::create([
      

  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  /** * {@inheritdoc} */
  public function add(FileInterface $file$module$type$id$count = 1) {
    // Make sure that a used file is permanent.     if (!$file->isPermanent()) {
      $file->setPermanent();
      $file->save();
    }
  }

  /** * {@inheritdoc} */
  public function delete(FileInterface $file$module$type = NULL, $id = NULL, $count = 1) {
    // Do not actually mark files as temporary when the behavior is disabled.     if (!$this->configFactory->get('file.settings')->get('make_unused_managed_files_temporary')) {
      return;
    }
protected function createOrUpdate(string $uri, string $destination, bool $rename): FileInterface {
    $file = $this->loadByUri($uri);
    if ($file === NULL) {
      $file = File::create(['uri' => $uri]);
      $file->setOwnerId($this->currentUser->id());
    }

    if ($rename && is_file($destination)) {
      $file->setFilename($this->fileSystem->basename($destination));
    }

    $file->setPermanent();
    $file->save();

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

  public function testCustomFileUriField() {
    $uri = 'public://druplicon.txt';

    // Create a new file entity.     $file = File::create([
      'uid' => 1,
      'filename' => 'druplicon.txt',
      'uri' => $uri,
      'filemime' => 'text/plain',
    ]);
    $file->setPermanent();
    file_put_contents($file->getFileUri(), 'hello world');

    $file->save();

    $this->assertSame($uri$file->uri->value);
    $expected_url = base_path() . $this->siteDirectory . '/files/druplicon.txt';
    $this->assertSame($expected_url$file->uri->url);
  }

}
$media_type
        ->set('source_configuration', [
          'source_field' => $source_field->getName(),
        ])
        ->save();
    }

    // Create a file to upload.     $file = File::create([
      'uri' => 'public://llama.txt',
    ]);
    $file->setPermanent();
    $file->save();

    // Create a "Llama" media item.     $media = Media::create([
      'bundle' => 'camelids',
      'field_media_file' => [
        'target_id' => $file->id(),
      ],
    ]);
    $media
      ->setName('Llama')
      
'files' => [
            $filename => str_repeat('a', 3000),
          ],
        ],
      ],
    ]);

    $file = File::create([
      'uri' => 'vfs://drupal_root/sites/default/files/' . $filename,
      'uid' => $this->user->id(),
    ]);
    $file->setPermanent();
    $file->save();

    return Media::create([
      'bundle' => $media_type->id(),
      'name' => 'Mr. Jones',
      'field_media_file' => [
        'target_id' => $file->id(),
      ],
    ]);
  }

}
$file->save();

    // The image should be visible for its author.     $this->drupalGet($src);
    $this->assertSession()->statusCodeEquals(200);
    // The not-yet-permanent image should NOT be visible for anonymous.     $this->drupalLogout();
    $this->drupalGet($src);
    $this->assertSession()->statusCodeEquals(403);

    // Resave the file to be permanent.     $file->setPermanent();
    $file->save();

    // Create some nodes to ensure file usage count does not match the ID's     // of the nodes we are going to check.     for ($i = 0; $i < 5; $i++) {
      $this->drupalCreateNode([
        'type' => 'page',
        'uid' => $author->id(),
      ]);
    }

    

  protected function createFile() {
    // Create a new file entity.     $file = File::create([
      'uid' => 1,
      'filename' => 'druplicon.txt',
      'uri' => 'public://druplicon.txt',
      'filemime' => 'text/plain',
      'created' => 1,
      'changed' => 1,
    ]);
    $file->setPermanent();
    file_put_contents($file->getFileUri(), 'hello world');

    // Save it, inserting a new record.     $file->save();

    return $file;
  }

}
Home | Imprint | This part of the site doesn't use cookies.