[1.0.x] Entity Usage Explorer

Created on 17 March 2025, 21 days ago

Project Link: https://www.drupal.org/project/entity_usage_explorer โ†’

Entity Usage Explorer โ†’ is a module designed to accurately track and display where entities are being used throughout a site, based on the current revision of entities.

Features

  • Views Field Plugin:
    • A customizable field plugin Base Entity Usage to display entity usage counts.
    • Can be rendered as plain text or as a clickable link leading to the entity usage overview page.
  • Entity Usage Overview Page:
    • Accessible at /admin/usage/{entity_type}/{entity_id}.
    • Displays a list of all places where the entity is referenced.
    • Lists entity usage across various types, including Menu Links, Nodes, Media, Block Content, Users, Paragraphs, etc.
  • Operations Link:
    • Adds a "Usage" operations link for all content entities.

Installation

  • Install via composer (composer require drupal/entity_usage_explorer) or download manually and place in the /modules/custom directory.
  • Enable via UI from Extend page or enable via Drush using drush en entity_usage_explorer

Similar Projects:

There is Entity Usage โ†’ module which provides the similar functionality, but there are certain limitations in that project:

  • It doesn't show the accurate usage on entities as per the current revision on entities.
  • It doesn't show the usage when the entity is being used on Menu links, or User entity etc.
  • To get the latest usage statistics, batch process need to be executed every time when changes are made on site.

The Entity Usage Explorer โ†’ module addresses all the mentioned concerns by accurately tracking and displaying entity usage across Drupal site. It offers a user-friendly interface for reviewing entity usage and provides custom Views field that can be seamlessly integrated into Drupal Views for enhanced reporting and analysis. The module instantly reflects changes in entity usage overview page, ensuring that you always have up-to-date information.

๐Ÿ“Œ Task
Status

Active

Component

module

Created by

๐Ÿ‡ฎ๐Ÿ‡ณIndia keshav patel

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @keshav patel
  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia keshav patel

    I've gone through Apply for permission to opt into security advisory coverage โ†’ page to understand all the requirements.

    Changing status to "Needs review".

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia vishal.kadam Mumbai

    Thank you for applying!

    Please read Review process for security advisory coverage: What to expect โ†’ for more details and Security advisory coverage application checklist โ†’ to understand what reviewers look for. Tips for ensuring a smooth review โ†’ gives some hints for a smoother review.

    The important notes are the following.

    • If you have not done it yet, you should run phpcs --standard=Drupal,DrupalPractice on the project, which alone fixes most of what reviewers would report.
    • For the time this application is open, only your commits are allowed.
    • The purpose of this application is giving you a new drupal.org role that allows you to opt projects into security advisory coverage, either projects you already created, or projects you will create. The project status won't be changed by this application and no other user will be able to opt projects into security advisory policy.
    • We only accept an application per user. If you change your mind about the project to use for this application, or it is necessary to use a different project for the application, please update the issue summary with the link to the correct project and the issue title with the project name and the branch to review.

    To the reviewers

    Please read How to review security advisory coverage applications โ†’ , Application workflow โ†’ , What to cover in an application review โ†’ , and Tools to use for reviews โ†’ .

    The important notes are the following.

    • It is preferable to wait for a Code Review Administrator before commenting on newly created applications. Code Review Administrators will do some preliminary checks that are necessary before any change on the project files is suggested.
    • Reviewers should show the output of a CLI tool โ†’ only once per application.
    • It may be best to have the applicant fix things before further review.

    For new reviewers, I would also suggest to first read In which way the issue queue for coverage applications is different from other project queues โ†’ .

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia vishal.kadam Mumbai
  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia vishal.kadam Mumbai

    1. FILE: README.md

    The README file is missing the required sections โ†’ including Requirements.

    2. FILE: entity_usage_explorer.module

    /**
     * @file
     * The module file.
     */

    The usual description for a .module file is โ€œHook implementations for the [module name] moduleโ€, where [module name] is the module name given in the .info.yml file.

    3. FILE: templates/entity-usage-overview-page.html.twig

    Twig code needs to be correctly indented. Drupal uses two spaces for indentation, not four spaces or tabs.

    Strings shown in the user interface must be translatable. That holds true also for strings used in template files.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia keshav patel

    Thanks for the feedback @vishalkadam โ†’ .

    Fixed all reported issues, please review.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia vishal.kadam Mumbai

    Rest looks fine to me.

    Letโ€™s wait for a Code Review Administrator to take a look and if everything goes fine, you will get the role.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia keshav patel

    Thanks for the review @vishal.kadam โ†’ .

    Also, as mentioned on What to expect from the review process โ†’ section:

    Once all issues have been addressed:
    The reviewers will change the status of the issue to Reviewed & tested by the community

    Please change the status to RTBC.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia vishal.kadam Mumbai
  • ๐Ÿ‡ฎ๐Ÿ‡นItaly apaderno Brescia, ๐Ÿ‡ฎ๐Ÿ‡น
    • The following points are just a start and don't necessarily encompass all of the changes that may be necessary
    • A specific point may just be an example and may apply in other places
    • A review is about code that does not follow the coding standards, contains possible security issue, or does not correctly use the Drupal API
    • The single review points are not ordered, not even by importance

    src/UsageService.php

      /**
       * Summary of loadContentEntityTypes.
       */
      public function loadContentEntityTypes() : array {
        $entity_definitions = $this->entityTypeManager->getDefinitions();
    
        $content_entity_types = [];
    
        foreach ($entity_definitions as $entity_type_id => $definition) {
          if ($definition->entityClassImplements(ContentEntityInterface::class)) {
            $content_entity_types[] = $entity_type_id;
          }
        }
    
        return $content_entity_types;
      }
    
      /**
       * Implements getEntityReferences().
       */
      public function getEntityReferences($entity_type, $bundle_to_query) {
        $target_type = '';
        $entity_tables = $this->database->query("SHOW TABLES LIKE '%{$entity_type}__%'")->fetchAllKeyed(0, 0);
        $matches = [];
    
        foreach ($entity_tables as $table) {
          $prefix_key = str_replace("{$entity_type}__", '', $table);
          $column = $this->database->query("SHOW COLUMNS FROM `$table` LIKE '%target_id%'")->fetch();
    
          if ($column) {
            $column_name = $column->Field;
            if (str_ends_with($column_name, '_target_id')) {
              $suffix_key = str_replace('_target_id', '', $column_name);
    
              if ($prefix_key === $suffix_key) {
                $field_name = $prefix_key;
                $storage = $this->entityTypeManager->getStorage('field_storage_config')->load("{$entity_type}." . $field_name);
                if ($storage && in_array($storage->getType(), ['entity_reference', 'entity_reference_revisions', 'file'])) {
                  $target_type = $storage->getSettings()['target_type'];
                }
                if ($bundle_to_query == $target_type) {
                  $matches[] = [
                    'table' => $table,
                    'column' => $column_name,
                    'field_name' => $field_name,
                    'key' => $prefix_key,
                    'target_type' => $target_type ?? 'Not an entity reference field',
                  ];
                }
              }
            }
          }
        }
    
        return $matches;
      }
    
      /**
       * Implements getEntityUsage().
       */
      public function getEntityUsage(string $target_entity, int $entity_id): array {
        $data = [];
        $entity_types = $this->loadContentEntityTypes();
        foreach ($entity_types as $entity_type) {
          if ($entity_type == 'menu_link_content') {
            $menu_record = $this->getEntityUsageInMenu($target_entity, $entity_id);
            if (!empty($menu_record)) {
              $data[$entity_type] = $menu_record;
            }
          }
    
          $matches = $this->getEntityReferences($entity_type, $target_entity);
          if (!empty($matches)) {
            $data[$entity_type] = [];
            foreach ($matches as $match) {
              $query = $this->database->select($match['table'], 't')
                ->fields('t')
                ->condition($match['column'], $entity_id)
                ->execute();
    
              $result = $query->fetchAll();
              if (!empty($result)) {
                $data[$entity_type] = array_merge($data[$entity_type], $result);
              }
            }
          }
        }
    
        return $data;
      }
    

    None of those documentation comments are correct. A short description starting with Implements is for hook implementations. For other functions and methods, a documentation comment needs to contain at least a short description, a description of the parameters (if they are used), and a description of the returned value (if it is not void).

        $target_type = '';
        $entity_tables = $this->database->query("SHOW TABLES LIKE '%{$entity_type}__%'")->fetchAllKeyed(0, 0);
        $matches = [];
    
        foreach ($entity_tables as $table) {
          $prefix_key = str_replace("{$entity_type}__", '', $table);
          $column = $this->database->query("SHOW COLUMNS FROM `$table` LIKE '%target_id%'")->fetch();
    

    Drupal core does not query entity tables in that way, which is not necessary to verify a specific database table exists to then query it.

    src/Controller/UsageOverviewController.php

    Since that class does not use any method from the parent class, it does not need to use ControllerBase as parent class. Controllers do not need to have a parent class; as long as they implement \Drupal\Core\DependencyInjection\ContainerInjectionInterface, they are fine.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia keshav patel

    Hello @avpaderno โ†’ , Thanks for a thorough review!
    I've worked on suggested improvements, please check.

Production build 0.71.5 2024