public function EntityFieldVariable::evaluate in Business Rules 2.x
Same name and namespace in other branches
- 8 src/Plugin/BusinessRulesVariable/EntityFieldVariable.php \Drupal\business_rules\Plugin\BusinessRulesVariable\EntityFieldVariable::evaluate()
Evaluate the variable.
Parameters
\Drupal\business_rules\Entity\Variable $variable: The variable to be evaluated.
\Drupal\business_rules\Events\BusinessRulesEvent $event: The dispatched event.
Return value
\Drupal\business_rules\VariableObject|\Drupal\business_rules\VariablesSet The evaluated variables.
Overrides BusinessRulesVariablePlugin::evaluate
File
- src/
Plugin/ BusinessRulesVariable/ EntityFieldVariable.php, line 94
Class
- EntityFieldVariable
- Class EntityValue.
Namespace
Drupal\business_rules\Plugin\BusinessRulesVariableCode
public function evaluate(Variable $variable, BusinessRulesEvent $event) {
$field_name = $variable
->getSettings('field');
$data = $variable
->getSettings('data');
$variableSet = new VariablesSet();
switch ($data) {
case self::CURRENT_DATA:
$entity = $event
->getArgument('entity');
break;
case self::ORIGINAL_DATA:
$entity = $event
->getArgument('entity_unchanged');
break;
}
try {
$value = $entity
->get($field_name)
->getValue();
// Check if value is a entity reference.
/** @var \Drupal\field\Entity\FieldConfig $field_definition */
$field_definition = $entity
->getFieldDefinition($field_name);
if ($field_definition
->getType() == 'entity_reference') {
$entity_references = $entity
->get($field_name)
->referencedEntities();
foreach ($entity_references as $key => $item) {
$value[$key]['entity_reference_label'] = $item
->label();
}
}
} catch (\Exception $e) {
throw $e;
}
$arr_label = [];
if (count($value) === 1) {
if (isset($value[0]['value'])) {
$value = $value[0]['value'];
}
elseif (isset($value[0]['target_id'])) {
$value = $value[0]['target_id'];
}
else {
$value = NULL;
}
}
else {
$arr_value = [];
foreach ($value as $key => $item) {
if (isset($item['value'])) {
$arr_value[] = $item['value'];
$multi_val = new VariableObject($variable
->id() . "[{$key}]", $item['value'], $variable
->getType());
}
elseif (isset($item['target_id'])) {
$arr_value[] = $item['target_id'];
$multi_val = new VariableObject($variable
->id() . "[{$key}]", $item['target_id'], $variable
->getType());
$title = new VariableObject($variable
->id() . "[{$key}]->label", $item['entity_reference_label'], $variable
->getType());
$variableSet
->append($title);
$arr_label[] = $item['entity_reference_label'];
}
else {
$arr_value[] = NULL;
$multi_val = new VariableObject($variable
->id() . "[{$key}]", NULL, $variable
->getType());
}
$variableSet
->append($multi_val);
}
$value = $arr_value;
}
$variableObject = new VariableObject($variable
->id(), $value, $variable
->getType());
$variableSet
->append($variableObject);
if (count($arr_label)) {
$variableObject = new VariableObject($variable
->id() . '->label', $arr_label, $variable
->getType());
$variableSet
->append($variableObject);
}
return $variableSet;
}