EntityContext.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Drupal\Core\Plugin\Context;
  3. use Drupal\Core\Entity\EntityInterface;
  4. use Drupal\Core\Entity\EntityTypeInterface;
  5. /**
  6. * Class to provide a specific entity context.
  7. */
  8. class EntityContext extends Context {
  9. /**
  10. * Gets a context from an entity type ID.
  11. *
  12. * @param string $entity_type_id
  13. * Entity type ID from which a definition will be derived.
  14. * @param string $label
  15. * (optional) The label of the context.
  16. *
  17. * @return static
  18. */
  19. public static function fromEntityTypeId($entity_type_id, $label = NULL) {
  20. $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  21. return static::fromEntityType($entity_type, $label);
  22. }
  23. /**
  24. * Gets a context from an entity type.
  25. *
  26. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  27. * Entity type from which a definition will be derived.
  28. * @param string $label
  29. * (optional) The label of the context.
  30. *
  31. * @return static
  32. */
  33. public static function fromEntityType(EntityTypeInterface $entity_type, $label = NULL) {
  34. $definition = EntityContextDefinition::fromEntityType($entity_type);
  35. if ($label) {
  36. $definition->setLabel($label);
  37. }
  38. return new static($definition);
  39. }
  40. /**
  41. * Gets a context object from an entity.
  42. *
  43. * @param \Drupal\Core\Entity\EntityInterface $entity
  44. * Entity that provides a context.
  45. * @param string $label
  46. * (optional) The label of the context.
  47. *
  48. * @return static
  49. */
  50. public static function fromEntity(EntityInterface $entity, $label = NULL) {
  51. $context = static::fromEntityType($entity->getEntityType(), $label);
  52. $context->setContextValue($entity);
  53. return $context;
  54. }
  55. }