function ContextProviderTrait::upcastEntityId
Upcasts an entity id to a full entity object.
Returns the entity object if the upcast was successful, otherwise returns NULL.
@todo Rather than returning NULL, we should probably throw an exception. That way the calling code may attempt an upcast, then continue on as it used to if the upcast fails.
Parameters
string $id: The unique entity id to upcast to a full entity.
string $type: The entity data type. For example, "entity:node".
Return value
\Drupal\Core\Entity\EntityInterface|null The upcasted entity object (if successful) or null (if not).
2 calls to ContextProviderTrait::upcastEntityId()
- RulesActionBase::execute in src/
Core/ RulesActionBase.php - Executes the plugin.
- RulesConditionBase::evaluate in src/
Core/ RulesConditionBase.php - Evaluates the condition and returns TRUE or FALSE accordingly.
File
-
src/
Context/ ContextProviderTrait.php, line 87
Class
- ContextProviderTrait
- A trait implementing the ContextProviderInterface.
Namespace
Drupal\rules\ContextCode
public function upcastEntityId($id, $type) {
// If the passed value is (accidentally) already an object, just return it.
if (is_object($id)) {
return $id;
}
$paramConverterManager = \Drupal::service('paramconverter_manager');
/** @var \Drupal\Core\ParamConverter\ParamConverterInterface $param_converter */
$param_converter = $paramConverterManager->getConverter('paramconverter.entity');
// The $name variable is just an arbitrary slug for use in the route object.
$name = 'id_to_upcast';
// The $definition variable declares what datatype the slug represents.
$definition = [
'type' => $type,
];
// The Route class used here is just a data structure for holding data
// necessary for a route definition. Creating an object of this type does
// not in any way affect routing on the site. We only use Route here because
// the paramconverter_manager requires this structure for one of its inputs.
$route = new Route('/{$name}');
// Check that the definition can be upcast and if so do it.
if ($param_converter->applies($definition, $name, $route)) {
$defaults = [
$name => $id,
];
$upcasted_object = $param_converter->convert(strtolower($id), $definition, $name, $defaults);
return $upcasted_object;
}
else {
return NULL;
}
}