Skip to content

Instantly share code, notes, and snippets.

@doublejosh
Last active August 29, 2015 14:01
Show Gist options
  • Save doublejosh/6777b8d88915308202db to your computer and use it in GitHub Desktop.
Save doublejosh/6777b8d88915308202db to your computer and use it in GitHub Desktop.
Agnostic current entity loader function
<?php
/**
* Utility function to agnosticly get the current menu object.
* Structured like menu_get_object(), but the passed type will be set for you.
*
* @param string (reference) $return_type
*
* return object
* Entity object of current menu callback page.
*/
function _my_module_menu_get_any_object(&$return_type) {
// Figure out how this entity is loaded.
$type = FALSE;
$item = menu_get_item();
$vals = array_values($item['load_functions']);
$load_function = $vals[0];
$arg_position = array_search($load_function, $item['load_functions']);
// Compare to entity types.
$entity_info = entity_get_info();
foreach($entity_info as $i => $e) {
if ($e['load hook'] == $load_function) {
$type = $i;
}
}
// Many happy returns.
if ($type && $obj = menu_get_object($type, $arg_position)) {
if(is_object($obj)) {
$return_type = $type;
return $obj;
}
else {
return FALSE;
}
}
else {
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment