Skip to content

Counting what a grade or profile is used by

Two services answer one question: how much content would lose its disclosure if this grade or this profile were deleted. ai_disclosure.profile_usage is DisclosureProfileUsage, ai_disclosure.grade_usage is DisclosureGradeUsage. The module calls them from AiDisclosureProfileDeleteForm and AiDisclosureGradeDeleteForm, so the person confirming a deletion sees the cost first.

Both expose a single method, and both return the same shape:

public function countContent(string $id): array;
// ['explicit' => int, 'inherited' => int]

What the two numbers mean

explicit means the same thing for both. inherited does not.

Service explicit inherited
ai_disclosure.profile_usage the entity references the profile directly the entity gets it from the bundle default
ai_disclosure.grade_usage the entity references the grade directly the entity reaches the grade through a profile

Never add them together

The two numbers overlap by design. On a multilingual site one translation of an entity can be explicit while another is inherited, so that entity is counted in both totals. A sum would count it twice. Report the two figures side by side, the way the delete forms do.

Calling them

use Drupal\Core\StringTranslation\PluralTranslatableMarkup;

$usage = \Drupal::service('ai_disclosure.profile_usage');
$counts = $usage->countContent('editorial_default');

if ($counts['explicit'] || $counts['inherited']) {
  $message = new PluralTranslatableMarkup(
    $counts['explicit'],
    '1 item names this profile, and @inherited inherit it.',
    '@count items name this profile, and @inherited inherit it.',
    ['@inherited' => $counts['inherited']],
  );
}

ai_disclosure.grade_usage works the same way, with an ai_disclosure_grade machine name instead.

Inject the service rather than reaching for \Drupal::service() when the calling class already has a container.

What the numbers cover

Each figure is a count of distinct entities, summed across every entity type that carries an ai_disclosure field. The services discover those entity types themselves, so a caller never passes an entity type.

The counts come from the database, so they reflect what is saved. Unsaved changes sitting in a form are not part of them.