Created
August 11, 2015 04:48
-
-
Save drushman/70b03546af18cf326778 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get entities references of EntityDrupalWrapper | |
* | |
* For example: we have entity A with ref to B (on field_ref_b) and on entity B we have other ref to C (on field_ref_c) | |
* | |
* - Let get all entities B that entity A1 referenced | |
* get_entities_references($w_a, 'field_ref_b'); | |
* - Let get all entities C that entity A1 referenced | |
* get_entities_references($w_a, 'field_ref_b.field_ref_c'); | |
* - Unlimit get references "field_ref_b.field_ref_c.field_ref_d.field_ref_e...."; | |
* | |
* @param \EntityDrupalWrapper $wrapper | |
* @param type $refs_str | |
* @param type $delimiter | |
* @return type | |
*/ | |
function get_entities_references(\EntityDrupalWrapper $wrapper, $refs_str, $delimiter = '.') { | |
$return = array(); | |
// Split refs_str by delimiter. | |
$refs = explode($delimiter, $refs_str); | |
// No fields. | |
if (empty($refs)) { | |
return array(); | |
} | |
// Last of recursive. | |
$count = count($refs); | |
if ($count == 1) { | |
$ref = reset($refs); | |
if ($wrapper->__isset($ref)) { | |
$values = $wrapper->{$ref}->value(); | |
$return = is_array($values) ? $values : array($values); | |
} | |
return $return; | |
} | |
// Fetch entities by recursive fields. | |
foreach ($refs as $k => $ref) { | |
if (count($refs) <= 1) { | |
break; | |
} | |
// Marked processed. | |
unset($refs[$k]); | |
$_refs = $refs; | |
// Field not exist in wrapper | |
if (!$wrapper->__isset($ref)) { | |
continue; | |
} | |
// Being process field ref. | |
$fwrapper = $wrapper->{$ref}; | |
if ($fwrapper instanceof \EntityListWrapper) { | |
foreach ($fwrapper->getIterator() as $iwrapper) { | |
$result = get_entities_references($iwrapper, implode($delimiter, $_refs)); | |
$return = array_merge($result, $return); | |
} | |
} | |
elseif ($fwrapper instanceof \EntityDrupalWrapper) { | |
$result = get_entities_references($fwrapper, implode($delimiter, $_refs)); | |
$return = array_merge($result, $return); | |
} | |
} | |
return $return; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment