Created
November 18, 2013 23:46
-
-
Save beeman/7537487 to your computer and use it in GitHub Desktop.
Triggered by a post on Facebook (https://www.facebook.com/groups/cake.community/permalink/673205099378177/) I started working on a method to list all the models plus their relations of a CakePHP application.
This file contains hidden or 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 | |
App::uses('Shell', 'Console'); | |
class RelationsShell extends Shell { | |
var $relations = array('hasMany', 'belongsTo', 'hasAndBelongsToMany'); | |
var $structure = array(); | |
/** | |
* Main method takes three arguments, the model to start with, the depth and enables output in json | |
*/ | |
function main() { | |
$this->getModelRelations(); | |
$model = isset($this->args[0]) ? $this->args[0] : null; | |
$level = isset($this->args[1]) ? $this->args[1] : null; | |
$json = isset($this->args[2]) ? $this->args[2] : null; | |
$result = array(); | |
if ($model) { | |
$result = $this->getModelStructure($model, $level, $json); | |
} else { | |
$result = 'Please pass a model as a parameter'; | |
} | |
pr($result); | |
} | |
/** | |
* Returns the nested Model structure | |
* @param type $model | |
* @param type $level | |
* @param type $json | |
* @return type | |
*/ | |
function getModelStructure($model = 'App', $level = 0, $json = null) { | |
$result[$model] = $this->getRelations($model, $level); | |
if ($json) { | |
$result = json_encode($result); | |
} | |
return $result; | |
} | |
/** | |
* Get al the relations from this model | |
* @param type $model | |
*/ | |
function getRelations($model, $level = 0, $current = 0) { | |
$result = array(); | |
if (isset($this->structure[$model])) { | |
$m = $this->structure[$model]; | |
foreach ($this->relations as $rel) { | |
if (isset($m[$rel])) { | |
foreach ($m[$rel] as $key => $value) { | |
if ($level > 0 && $current < $level) { | |
$models = $this->getRelations($key, $level, $current + 1); | |
} else { | |
$models = null; | |
} | |
$result[$rel][$key] = $models; | |
} | |
} | |
} | |
} else { | |
return '[ No such model ]'; | |
} | |
return $result; | |
} | |
/** | |
* Get all the models and return an array with all the relations | |
* @return type | |
*/ | |
function getModelRelations() { | |
$models = App::objects('Model'); | |
foreach ($models as $model) { | |
$instance = ClassRegistry::init($model); | |
$this->structure[$model]['hasMany'] = $instance->hasMany; | |
$this->structure[$model]['belongsTo'] = $instance->belongsTo; | |
$this->structure[$model]['hasAndBelongsToMany'] = $instance->hasAndBelongsToMany; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment