function EntityFieldManager::getFieldLabels

Overrides EntityFieldManagerInterface::getFieldLabels

File

core/lib/Drupal/Core/Entity/EntityFieldManager.php, line 700

Class

EntityFieldManager
Manages the discovery of entity fields.

Namespace

Drupal\Core\Entity

Code

public function getFieldLabels(string $entity_type, string $field_name) : array {
    $label_counter = [];
    $all_labels = [];
    // Count the number of fields per label per field storage.
    foreach (array_keys($this->entityTypeBundleInfo
        ->getBundleInfo($entity_type)) as $bundle) {
        $bundle_fields = array_filter($this->getFieldDefinitions($entity_type, $bundle), function ($field_definition) {
            return $field_definition instanceof FieldConfigInterface;
        });
        if (isset($bundle_fields[$field_name])) {
            $field = $bundle_fields[$field_name];
            $label = $field->getLabel();
            $label_counter[$label] = isset($label_counter[$label]) ? ++$label_counter[$label] : 1;
            $all_labels[$label] = TRUE;
        }
    }
    if (empty($label_counter)) {
        return [
            $field_name,
            $all_labels,
        ];
    }
    // Sort the field labels by the most used label and return the most used
    // one. If the counts are equal, sort by the label to ensure the result is
    // deterministic.
    uksort($label_counter, function ($a, $b) use ($label_counter) {
        if ($label_counter[$a] === $label_counter[$b]) {
            return strcmp($a, $b);
        }
        return $label_counter[$b] <=> $label_counter[$a];
    });
    $label_counter = array_keys($label_counter);
    return [
        $label_counter[0],
        $all_labels,
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.