Invokes a method on all the fields of a given entity.
@todo Remove _field_invoke() and friends when field types and formatters are turned into plugins.
string $method: The name of the method to invoke.
callable $target_function: A function that receives an $instance object and returns the object on which the method should be invoked.
Drupal\Core\Entity\EntityInterface $entity: The fully formed $entity_type entity.
mixed $a: (optional) A parameter for the invoked method. Defaults to NULL.
mixed $b: (optional) A parameter for the invoked method. Defaults to NULL.
array $options: (optional) An associative array of additional options, with the following keys:
array An array of returned values.
function field_invoke_method($method, $target_function, EntityInterface $entity, &$a = NULL, &$b = NULL, array $options = array()) {
// Merge default options.
$default_options = array(
'deleted' => FALSE,
'langcode' => NULL,
);
$options += $default_options;
$entity_type = $entity
->entityType();
// Determine the list of instances to iterate on.
$instances = _field_invoke_get_instances($entity_type, $entity
->bundle(), $options);
// Iterate through the instances and collect results.
$return = array();
foreach ($instances as $instance) {
// Let the function determine the target object on which the method should be
// called.
$target = call_user_func($target_function, $instance);
if (method_exists($target, $method)) {
$field = field_info_field_by_id($instance['field_id']);
$field_name = $field['field_name'];
// Determine the list of languages to iterate on.
$available_langcodes = field_available_languages($entity_type, $field);
$langcodes = _field_language_suggestion($available_langcodes, $options['langcode'], $field_name);
foreach ($langcodes as $langcode) {
$items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
$result = $target
->{$method}($entity, $langcode, $items, $a, $b);
if (isset($result)) {
// For methods with array results, we merge results together.
// For methods with scalar results, we collect results in an array.
if (is_array($result)) {
$return = array_merge($return, $result);
}
else {
$return[] = $result;
}
}
// Populate $items back in the field values, but avoid replacing missing
// fields with an empty array (those are not equivalent on update).
if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
$entity->{$field_name}[$langcode] = $items;
}
}
}
}
return $return;
}