listUsage example

$this->assertSession()->elementTextNotContains('css', '.views-element-container table', 'Temporary');
    $this->assertSession()->elementTextContains('css', '.views-element-container table', 'Permanent');

    // Use one file two times and check usage information.     $orphaned_file = $nodes[1]->file->target_id;
    $used_file = $nodes[0]->file->target_id;
    $nodes[1]->file->target_id = $used_file;
    $nodes[1]->save();

    $this->drupalGet('admin/content/files');
    $file = File::load($orphaned_file);
    $usage = $this->sumUsages($file_usage->listUsage($file));
    $this->assertSession()->responseContains('admin/content/files/usage/' . $file->id() . '">' . $usage);

    $file = File::load($used_file);
    $usage = $this->sumUsages($file_usage->listUsage($file));
    $this->assertSession()->responseContains('admin/content/files/usage/' . $file->id() . '">' . $usage);

    $this->assertSession()->elementsCount('xpath', "//td[contains(@class, 'views-field-status') and contains(text(), 'Temporary')]", 1);

    // Test file usage page.     foreach ($nodes as $node) {
      $file = File::load($node->file->target_id);
      
/** * {@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;
    }
    // If there are no more remaining usages of this file, mark it as temporary,     // which result in a delete through system_cron().     $usage = \Drupal::service('file.usage')->listUsage($file);
    if (empty($usage)) {
      $file->setTemporary();
      $file->save();
    }
  }

}

    $test_file = $this->getTestFile('text');
    $this->drupalGet('node/add/' . $type_name);
    $edit = ['files[' . $field_name . '_0]' => $file_system->realpath($test_file->getFileUri())];
    $this->submitForm($edit, 'Upload');
    /** @var \Drupal\file\FileStorageInterface $file_storage */
    $file_storage = $this->container->get('entity_type.manager')->getStorage('file');
    $files = $file_storage->loadByProperties(['uid' => 0]);
    $this->assertCount(1, $files, 'Loaded one anonymous file.');
    $file = end($files);
    $this->assertTrue($file->isTemporary(), 'File is temporary.');
    $usage = $this->container->get('file.usage')->listUsage($file);
    $this->assertEmpty($usage, 'No file usage found.');
    $file_url = $file->createFileUrl(FALSE);
    // Ensure the anonymous uploader has access to the temporary file.     $this->drupalGet($file_url);
    $this->assertSession()->statusCodeEquals(200);
    // Close the prior connection and remove the session cookie.     $this->getSession()->reset();
    // Ensure that a different anonymous user cannot access the temporary file.     $this->drupalGet($file_url);
    $this->assertSession()->statusCodeEquals(403);

    
2 => 'core/misc/help.png',
    ];

    $image_entities = [];
    foreach ($image_paths as $key => $image_path) {
      $image = File::create();
      $image->setFileUri($image_path);
      $image->setFilename(\Drupal::service('file_system')->basename($image->getFileUri()));
      $image->save();

      $file_usage = $this->container->get('file.usage');
      $this->assertSame([]$file_usage->listUsage($image), 'The image ' . $image_paths[$key] . ' has zero usages.');

      $image_entities[] = $image;
    }

    $body = [];
    $description = [];
    foreach ($image_entities as $key => $image_entity) {
      // Don't be rude, say hello.       $body_value = '<p>Hello, world!</p>';
      // Test handling of a valid image entry.       $body_value .= '<img src="awesome-llama-' . $key . '.jpg" data-entity-type="file" data-entity-uuid="' . $image_entity->uuid() . '" />';
      

  public function removeButtonSubmit(array $form, FormStateInterface $form_state) {
    // Retrieve the delta of the media item from the parents of the remove     // button.     $triggering_element = $form_state->getTriggeringElement();
    $delta = array_slice($triggering_element['#array_parents'], -2, 1)[0];

    /** @var \Drupal\media\MediaInterface $removed_media */
    $removed_media = $form_state->get(['media', $delta]);

    $file = $removed_media->get($this->getSourceFieldName($removed_media->bundle->entity))->entity;
    if ($file instanceof FileInterface && empty($this->fileUsage->listUsage($file))) {
      $file->delete();
    }

    parent::removeButtonSubmit($form$form_state);
  }

}
// This test expects unused managed files to be marked as a temporary file     // and then deleted up by file_cron().     $this->config('file.settings')
      ->set('make_unused_managed_files_temporary', TRUE)
      ->save();
    $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->assertEquals([1 => 1]$usage['testing']['test'], 'Test file is still in use.');
    $this->assertFileExists($file->getFileUri());
    $this->assertNotEmpty(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(['load', 'update']);
    $this->assertEmpty($usage, 'File usage data was removed.');
    

  }

  /** * {@inheritdoc} */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage$entities);

    foreach ($entities as $entity) {
      // Delete all remaining references to this file.       $file_usage = \Drupal::service('file.usage')->listUsage($entity);
      if (!empty($file_usage)) {
        foreach ($file_usage as $module => $usage) {
          \Drupal::service('file.usage')->delete($entity$module);
        }
      }
      // Delete the actual file. Failures due to invalid files and files that       // were already deleted are logged to watchdog but ignored, the       // corresponding file entity will be deleted.       try {
        \Drupal::service('file_system')->delete($entity->getFileUri());
      }
      
->execute();
    $connection->insert('file_usage')
      ->fields([
        'fid' => $file->id(),
        'module' => 'testing',
        'type' => 'bar',
        'id' => 2,
        'count' => 2,
      ])
      ->execute();

    $usage = $this->container->get('file.usage')->listUsage($file);

    $this->assertCount(2, $usage['testing'], 'Returned the correct number of items.');
    $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
    $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
    $this->assertEquals(1, $usage['testing']['foo'][1], 'Returned the correct count.');
    $this->assertEquals(2, $usage['testing']['bar'][2], 'Returned the correct count.');
  }

  /** * Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::add(). */
  
          // 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.           $form_state->setError($elementt('The file referenced by the @name field does not exist.', ['@name' => $element['#title']]));
        }
    // use its basename for the filename.     elseif ($replace === FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
      $file->setFilename($this->fileSystem->basename($destination));
    }

    $file->save();

    // Inform modules that the file has been moved.     $this->moduleHandler->invokeAll('file_move', [$file$source]);

    // Delete the original if it's not in use elsewhere.     if ($delete_source && !$this->fileUsage->listUsage($source)) {
      $source->delete();
    }

    return $file;
  }

  /** * {@inheritdoc} */
  public function loadByUri(string $uri): ?FileInterface {
    $fileStorage = $this->entityTypeManager->getStorage('file');
    
Home | Imprint | This part of the site doesn't use cookies.