1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| private function _getGroupRelatives($group, $relation, $options)
{
// Hash of opposite values for relation table, also used to check input validity
$opposite = array(
'ancestor' => 'descendant',
'descendant' => 'ancestor'
);
// Only accepts relations previouly defined
if (!isset($opposite[ $relation ])) {
throw new \Exception('Invalid relation type "'. $relation .'" in _getGroupRelatives()');
}
// Only accepts Group entity or ID
if ($group instanceof \Entities\Group) {
$group = $group->getId();
}
if (!is_numeric($group)) {
throw new \Exception('Invalid group parameter, expecting ID or Group entity');
}
$sql = 'SELECT * FROM `group` g
JOIN group_group gh ON gh.'. $relation .'_id = g.id
WHERE gh.'. $opposite[$relation] .'_id = :id';
$params = array('id' => $group);
/*
* Available options:
* false (default): get relatives without current group
* true: get relatives WITH current group (useful when entity is not yet loaded)
* integer: max depth of relations
* array(min, max): min and max depth of relations
*/
if ($options === false) {
// Relatives ONLY, do not include current group
$sql .= ' AND gh.depth > 0';
}
else if (is_int($options)) {
// Max depth
$sql .= ' AND gh.depth <= :max';
$params['max'] = $options;
}
else if (is_array($options) && count($options) === 2) {
// Min and max depth
$sql .= ' AND gh.depth BETWEEN :min AND :max';
$params['min'] = $options[isset($options['min']) ? 'min' : 0];
$params['max'] = $options[isset($options['max']) ? 'max' : 1];
}
// Mapping used for Entity, should be useful to put elsewere in the class or in the entity itself
$rsm = new ResultSetMapping;
$rsm->addEntityResult('\Entities\Group', 'g');
$rsm->addFieldResult('g', 'id', 'id');
$rsm->addFieldResult('g', 'name', 'name');
// Order by ascending depth by default
$sql .= ' ORDER BY gh.depth';
$query = $this->_em
->createNativeQuery($sql, $rsm)
->setParameters($params);
return new ArrayCollection($query->getResult());
} |
Partager