Skip to content

Instantly share code, notes, and snippets.

@beeman
Created November 18, 2013 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beeman/7537487 to your computer and use it in GitHub Desktop.
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.
<?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