Skip to content

Instantly share code, notes, and snippets.

@sdboyer
Created April 1, 2013 13:24
Show Gist options
  • Save sdboyer/5284926 to your computer and use it in GitHub Desktop.
Save sdboyer/5284926 to your computer and use it in GitHub Desktop.
new prefix-agnostic config entity loader
<?php
/**
* Loads the correct type of ConfigEntity from a full configuration object name.
*
* ConfigEntity expects that the id passed to entity_load() will not include the
* config prefix used by the entity type being loaded. This is unhelpful for
* calling code that has the fully prefixed configuration object name and can
* not reliably know the specific type of ConfigEntity to load.
*
* This function figures out which type of entity the configuration object
* corresponds to, then performs the entity_load().
*
* Note: this should only be used if the calling code CANNOT safely know what
* type of ConfigEntity it should be loading ahead of time. Otherwise, use
* entity_load() directly.
*
* @param $name
* The full configuration object name, including prefix.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityInterface
*/
function config_load_entity_by_name($name) {
$entity = array_filter(entity_get_info(), function($entity_info) use ($name) {
return (isset($entity_info['config_prefix']) && strpos($name, $entity_info['config_prefix'] . '.') === 0);
});
list($type, $info) = each($entity);
$id = substr($name, strlen($info['config_prefix'] . '.'));
return entity_load($type, $id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment