DynamicEntityTypeParamConverterTrait.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace Drupal\Core\ParamConverter;
  3. /**
  4. * Provides a trait to replace dynamic entity types in routes.
  5. */
  6. trait DynamicEntityTypeParamConverterTrait {
  7. /**
  8. * Determines the entity type ID given a route definition and route defaults.
  9. *
  10. * @param mixed $definition
  11. * The parameter definition provided in the route options.
  12. * @param string $name
  13. * The name of the parameter.
  14. * @param array $defaults
  15. * The route defaults array.
  16. *
  17. * @return string
  18. * The entity type ID.
  19. *
  20. * @throws \Drupal\Core\ParamConverter\ParamNotConvertedException
  21. * Thrown when the dynamic entity type is not found in the route defaults.
  22. */
  23. protected function getEntityTypeFromDefaults($definition, $name, array $defaults) {
  24. $type_part = strstr($definition['type'], ':');
  25. if (!$type_part) {
  26. throw new ParamNotConvertedException(sprintf('The type definition "%s" is invalid. The expected format is "entity_revision:<entity_type_id>".', $definition['type']));
  27. }
  28. $entity_type_id = substr($type_part, 1);
  29. // If the entity type is dynamic, it will be pulled from the route defaults.
  30. if (strpos($entity_type_id, '{') === 0) {
  31. $entity_type_slug = substr($entity_type_id, 1, -1);
  32. if (!isset($defaults[$entity_type_slug])) {
  33. throw new ParamNotConvertedException(sprintf('The "%s" parameter was not converted because the "%s" parameter is missing.', $name, $entity_type_slug));
  34. }
  35. $entity_type_id = $defaults[$entity_type_slug];
  36. }
  37. return $entity_type_id;
  38. }
  39. }