Use entity query in vocabularyIsEmpty

Created on 27 March 2023, over 1 year ago
Updated 28 July 2023, 11 months ago

Problem/Motivation

The service TaxonomyManagerHelper.php has a function vocabularyIsEmpty which is used to determine if a vocabulary with a specific vid has any terms. This is executed on every page load of a TaxonomyManagerForm and executes a full loadTree, which is very expensive if you have a large vocabulary.

Steps to reproduce

Visit any TaxonomyManagerForm of a vocabulary , buildForm then executes vocabularyIsEmpty

Proposed resolution

Replace loadTree in TaxonomyManagerHelper.php with an entity query, i.e.

diff --git a/src/TaxonomyManagerHelper.php b/src/TaxonomyManagerHelper.php
index 4070426..5923054 100644
--- a/src/TaxonomyManagerHelper.php
+++ b/src/TaxonomyManagerHelper.php
@@ -86,7 +86,12 @@ class TaxonomyManagerHelper {
   public function vocabularyIsEmpty($vid) {
     /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
     $term_storage = $this->taxonomyTypeManager;
-    return empty($term_storage->loadTree($vid));
+    return !$term_storage->getQuery()
+      ->accessCheck(FALSE)
+      ->condition('vid', $vid)
+      ->range(0, 1)
+      ->count()
+      ->execute();
   }
 
   /**

📌 Task
Status

Active

Version

2.0

Component

Code

Created by

🇩🇪Germany h1nds1ght

Live updates comments and jobs are added and updated live.
  • Performance

    It affects performance. It is often combined with the Needs profiling tag.

  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Production build 0.69.0 2024