Problem/Motivation
EntityReferenceFormatterBase::getEntitiesToView()
sets $entity->_referringItem
but if the same entity is referred multiple times then the value gets overridden.
Steps to reproduce
Refer the same file twice, add something to $item->_attributes
in hook_entity_prepare_view
to both of the referring items, observe how GenericFileFormatter
makes a total hash of it: the first file link will get the attributes of the second and the second will get nothing.
Proposed resolution
// Add the referring item, in case the formatter needs it.
if ($entity->_referringItem) {
$entity = clone $entity;
}
$entity->_referringItem = $items[$delta];
$entity->_entityReferenceViewLangcode = $langcode;
$entities[$delta] = $entity;
The conditional cloning is new.
Remaining tasks
Make a PR, add a test.