/**
* Finds relations of a model class.
*
* return values can be filtered by types 'belongs_to', 'many_many', 'has_many', 'has_one', 'pivot'
*
* @param ActiveRecord $modelClass
* @param array $types
*
* @return array
*/
public function getModelRelations($modelClass, $types = ['belongs_to', 'many_many', 'has_many', 'has_one', 'pivot'])
{
$reflector = new \ReflectionClass($modelClass);
$model = new $modelClass();
$stack = [];
$modelGenerator = new ModelGenerator();
foreach ($reflector->getMethods() as $method) {
if (in_array(substr($method->name, 3), $this->skipRelations)) {
continue;
}
// look for getters
if (substr($method->name, 0, 3) !== 'get') {
continue;
}
// skip class specific getters
$skipMethods = ['getRelation', 'getBehavior', 'getFirstError', 'getAttribute', 'getAttributeLabel', 'getOldAttribute'];
if (in_array($method->name, $skipMethods)) {
continue;
}
// check for relation
try {
$relation = @call_user_func(array($model, $method->name));
if ($relation instanceof \yii\db\ActiveQuery) {
#var_dump($relation->primaryModel->primaryKey);
if ($relation->multiple === false) {
$relationType = 'belongs_to';
} elseif ($this->isPivotRelation($relation)) {
# TODO: detecttion
$relationType = 'pivot';
} else {
$relationType = 'has_many';
}
if (in_array($relationType, $types)) {
$name = $modelGenerator->generateRelationName([$relation], $model->getTableSchema(), substr($method->name, 3), $relation->multiple);
$stack[$name] = $relation;
}
}
} catch (Exception $e) {
Yii::error('Error: ' . $e->getMessage(), __METHOD__);
}
}
return $stack;
}