isPermanent example

// Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('rest.entity.entity_test.POST')
      ->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions('POST'));

    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    $this->assertSame([
      [
        'target_id' => '1',
        'display' => NULL,
        'description' => "The most fascinating file ever!",
      ],
    ], EntityTest::load(2)->get('field_rest_file_test')->getValue());
  }

  /** * Returns the normalized POST entity referencing the uploaded file. * * @return array * * @see ::testPostFileUpload() * @see \Drupal\Tests\rest\Functional\EntityResource\EntityTest\EntityTestResourceTestBase::getNormalizedPostEntity() */
// This inspects the HTML after the post of the translation, the file     // should be displayed on the original node.     $this->assertSession()->responseContains('file--mime-text-plain');
    $second_fid = $this->getLastFileId();

    \Drupal::entityTypeManager()->getStorage('file')->resetCache();

    /** @var \Drupal\file\FileInterface $file */

    // Ensure the file status of the first file permanent.     $file = File::load($first_fid);
    $this->assertTrue($file->isPermanent());

    // Ensure the file status of the second file is permanent.     $file = File::load($second_fid);
    $this->assertTrue($file->isPermanent());

    // Translate the node into dutch: remove the existing file.     $this->drupalGet('node/' . $default_language_node->id() . '/translations/add/en/nl');
    $this->submitForm([], 'Remove');

    // Upload a different file.     $edit = [];
    

  protected function assertEntity($id$name$uri$mime$size$created$changed$uid) {
    /** @var \Drupal\file\FileInterface $file */
    $file = File::load($id);
    $this->assertInstanceOf(FileInterface::class$file);
    $this->assertSame($name$file->getFilename());
    $this->assertSame($uri$file->getFileUri());
    $this->assertFileExists($uri);
    $this->assertSame($mime$file->getMimeType());
    $this->assertSame($size$file->getSize());
    // isPermanent(), isTemporary(), etc. are determined by the status column.     $this->assertTrue($file->isPermanent());
    $this->assertSame($created$file->getCreatedTime());
    $this->assertSame($changed$file->getChangedTime());
    $this->assertSame($uid$file->getOwnerId());
  }

}
// Add a new managed file.     $file = current($this->getTestFiles('image'));
    $image_file_path = \Drupal::service('file_system')->realpath($file->uri);
    $page->attachFileToField('files[custom_logo]', $image_file_path);
    $assert_session->waitForButton('custom_logo_remove_button');

    // Assert the new file is uploaded as temporary. This file should not be     // saved as permanent if settings are not submitted.     $image_field = $this->assertSession()->hiddenFieldExists('custom_logo[fids]');
    $file = File::load($image_field->getValue());
    $this->assertFalse($file->isPermanent());

    $page->pressButton('Save configuration');
    \Drupal::entityTypeManager()->getStorage('file')->resetCache();

    // Assert the uploaded file is saved as permanent.     $image_field = $this->assertSession()->hiddenFieldExists('custom_logo[fids]');
    $file = File::load($image_field->getValue());
    $this->assertTrue($file->isPermanent());
  }

  /** * Provides test data for ::testFormSettingsSubmissionHandler(). */
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
    $this->submitForm($edit, 'Upload');
    $this->submitForm([], 'Save');

    $fid = $this->getLastFileId();
    /** @var \Drupal\file\FileInterface $file */
    $file = $this->container->get('entity_type.manager')->getStorage('file')->load($fid);
    $file->setPermanent();
    $file->save();
    $this->assertTrue(\Drupal::service('file_system')->delete($file->getFileUri()));
    $file->save();
    $this->assertTrue($file->isPermanent());
    $file->delete();
  }

  /** * Verify that unused permanent files can be used. */
  public function testUnusedPermanentFileValidation() {

    // Create a permanent file without usages.     $file = $this->getTestFile('image');
    $file->setPermanent();
    

  public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
    $this->assertEquals($before->id()$after->id());
    $this->assertEquals($before->getOwner()->id()$after->getOwner()->id());
    $this->assertEquals($before->getFilename()$after->getFilename());
    $this->assertEquals($before->getFileUri()$after->getFileUri());
    $this->assertEquals($before->getMimeType()$after->getMimeType());
    $this->assertEquals($before->getSize()$after->getSize());
    $this->assertEquals($before->isPermanent()$after->isPermanent());
  }

  /** * 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. */
  public function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
    
// If referencing an existing file, only allow if there are existing           // references. This prevents unmanaged files from being deleted if           // this item were to be deleted. When files that are no longer in use           // are automatically marked as temporary (now disabled by default),           // it is not safe to reference a permanent file without usage. Adding           // a usage and then later on removing it again would delete the file,           // but it is unknown if and where it is currently referenced. However,           // when files are not marked temporary (and then removed)           // automatically, it is safe to add and remove usages, as it would           // simply return to the current state.           // @see https://www.drupal.org/node/2891902           if ($file->isPermanent() && \Drupal::config('file.settings')->get('make_unused_managed_files_temporary')) {
            $references = static::fileUsage()->listUsage($file);
            if (empty($references)) {
              // 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($elementt('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
            }
          }
        }
        else {
          // 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.
$this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('jsonapi.entity_test--entity_test.collection.post');
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument());
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    $this->assertSame([
      [
        'target_id' => '1',
        'display' => NULL,
        'description' => "The most fascinating file ever!",
      ],
    ], EntityTest::load(2)->get('field_rest_file_test')->getValue());
  }

  /** * Tests using the 'file upload and "use" file in single request" POST route. */
public function assertFileEntryNotExists($file$message) {
    $this->container->get('entity_type.manager')->getStorage('file')->resetCache();
    $message = $message ?? new FormattableMarkup('File %file exists in database at the correct path.', ['%file' => $file->getFileUri()]);
    $this->assertNull(File::load($file->id())$message);
  }

  /** * Asserts that a file's status is set to permanent in the database. */
  public function assertFileIsPermanent(FileInterface $file$message = NULL) {
    $message = $message ?? new FormattableMarkup('File %file is permanent.', ['%file' => $file->getFileUri()]);
    $this->assertTrue($file->isPermanent()$message);
  }

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

    // Check that the correct hooks were called.     $this->assertFileHooksCalled(['insert']);

    // Verify that a new file ID is set when saving a new file to the database.     $this->assertGreaterThan(0, $file->id());
    $loaded_file = File::load($file->id());
    $this->assertNotNull($loaded_file, 'Record exists in the database.');
    $this->assertEquals($file->isPermanent()$loaded_file->isPermanent(), 'Status was saved correctly.');
    $this->assertEquals(filesize($file->getFileUri())$file->getSize(), 'File size was set correctly.');
    // Verify that the new file size was set correctly.     $this->assertGreaterThan(1, $file->getChangedTime());
    $this->assertEquals('en', $loaded_file->langcode->value, 'Langcode was defaulted correctly.');

    // Resave the file, updating the existing record.     file_test_reset();
    $file->status->value = 7;
    $file->save();

    // Check that the correct hooks were called.

  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')) {
      

  public function testSingleValues() {
    // Create a new file entity from scratch so we know the values.     $file = $this->createFile('druplicon.txt', NULL, 'public');
    $by_fid_file = File::load($file->id());
    $this->assertFileHookCalled('load');
    $this->assertIsObject($by_fid_file);
    $this->assertEquals($file->id()$by_fid_file->id(), 'Loading by fid got the same fid.');
    $this->assertEquals($file->getFileUri()$by_fid_file->getFileUri(), 'Loading by fid got the correct filepath.');
    $this->assertEquals($file->getFilename()$by_fid_file->getFilename(), 'Loading by fid got the correct filename.');
    $this->assertEquals($file->getMimeType()$by_fid_file->getMimeType(), 'Loading by fid got the correct MIME type.');
    $this->assertEquals($file->isPermanent()$by_fid_file->isPermanent(), 'Loading by fid got the correct status.');
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  }

  /** * This will test loading file data from the database. */
  public function testMultiple() {
    // Create a new file entity.     $file = $this->createFile('druplicon.txt', NULL, 'public');

    // Load by path.
return $file;
  }

  /** * {@inheritdoc} */
  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);
    $entities = array_filter($entitiesfunction D$file) {
      /** @var \Drupal\file\FileInterface $file */
      return $file->isPermanent() || $file->getOwnerId() === $this->currentUser->id();
    });
    return $entities;
  }

}
/** * {@inheritdoc} */
  public function testPost() {
    $file_storage = $this->container->get('entity_type.manager')->getStorage('file');

    // Step 1: upload file, results in File entity marked temporary.     $this->uploadFile();
    $file = $file_storage->loadUnchanged(3);
    $this->assertTrue($file->isTemporary());
    $this->assertFalse($file->isPermanent());

    // Step 2: create Media entity using the File, makes File entity permanent.     parent::testPost();
    $file = $file_storage->loadUnchanged(3);
    $this->assertFalse($file->isTemporary());
    $this->assertTrue($file->isPermanent());
  }

  /** * Tests the 'file_upload' REST resource plugin. * * This test duplicates some of the 'file_upload' REST resource plugin test * coverage. * * @see \Drupal\Tests\rest\Functional\FileUploadResourceTestBase */
    $filename = 'Текстовый файл.txt';

    $result = $this->fileRepository->writeData($contents, 'public://' . $filename);
    $this->assertNotFalse($result, 'Unnamed file saved correctly.');

    $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
    assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
    $this->assertEquals('public', $stream_wrapper_manager::getScheme($result->getFileUri()), "File was placed in Drupal's files directory.");
    $this->assertEquals($filename, \Drupal::service('file_system')->basename($result->getFileUri()), 'File was named correctly.');
    $this->assertEquals($contentsfile_get_contents($result->getFileUri()), 'Contents of the file are correct.');
    $this->assertEquals('text/plain', $result->getMimeType(), 'A MIME type was set.');
    $this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");

    // Check that the correct hooks were called.     $this->assertFileHooksCalled(['insert']);

    // Verify that what was returned is what's in the database.     $this->assertFileUnchanged($result, File::load($result->id()));
  }

  /** * Tests writeData() when renaming around an existing file. * * @covers ::writeData */
Home | Imprint | This part of the site doesn't use cookies.