Big refactor

This commit is contained in:
Barry vd. Heuvel
2014-08-06 00:02:00 +02:00
parent 3151019947
commit 8193fa0763
8 changed files with 913 additions and 570 deletions
+140 -99
View File
@@ -25,7 +25,8 @@ use phpDocumentor\Reflection\DocBlock\Serializer as DocBlockSerializer;
*
* @author Barry vd. Heuvel <[email protected]>
*/
class ModelsCommand extends Command {
class ModelsCommand extends Command
{
/**
* The console command name.
@@ -49,7 +50,6 @@ class ModelsCommand extends Command {
protected $reset;
/**
* Execute the console command.
*
@@ -59,25 +59,31 @@ class ModelsCommand extends Command {
{
$filename = $this->option('filename');
$this->write = $this->option('write');
$this->dirs = array_merge($this->laravel['config']->get('laravel-ide-helper::model_locations'), $this->option('dir'));
$this->dirs = array_merge(
$this->laravel['config']->get('laravel-ide-helper::model_locations'),
$this->option('dir')
);
$model = $this->argument('model');
$ignore = $this->option('ignore');
$this->reset = $this->option('reset');
//If filename is default and Write is not specified, ask what to do
if(!$this->write && $filename === $this->filename && !$this->option('nowrite')){
if($this->confirm("Do you want to overwrite the existing model files? Choose no to write to $filename instead? (Yes/No): ")){
if (!$this->write && $filename === $this->filename && !$this->option('nowrite')) {
if ($this->confirm(
"Do you want to overwrite the existing model files? Choose no to write to $filename instead? (Yes/No): "
)
) {
$this->write = true;
}
}
$content = $this->generateDocs($model, $ignore);
if(!$this->write){
if (!$this->write) {
$written = \File::put($filename, $content);
if($written !== false){
if ($written !== false) {
$this->info("Model information was written to $filename");
}else{
} else {
$this->error("Failed to write model information to $filename");
}
}
@@ -113,7 +119,8 @@ class ModelsCommand extends Command {
);
}
protected function generateDocs($loadModels, $ignore = ''){
protected function generateDocs($loadModels, $ignore = '')
{
$output = "<?php
@@ -127,55 +134,57 @@ class ModelsCommand extends Command {
\n\n";
$hasDoctrine = interface_exists('Doctrine\DBAL\Driver');
if(empty($loadModels)){
if (empty($loadModels)) {
$models = $this->loadModels();
}else{
} else {
$models = array();
foreach($loadModels as $model){
foreach ($loadModels as $model) {
$models = array_merge($models, explode(',', $model));
}
}
$ignore = explode(',', $ignore);
foreach($models as $name){
if(in_array($name, $ignore)){
foreach ($models as $name) {
if (in_array($name, $ignore)) {
$this->comment("Ignoring model '$name'");
continue;
}else{
} else {
$this->comment("Loading model '$name'");
}
$this->properties = array();
$this->methods = array();
if(class_exists($name)){
if (class_exists($name)) {
try {
// handle abstract classes, interfaces, ...
$reflectionClass = new \ReflectionClass($name);
if (!$reflectionClass->IsInstantiable()) {
throw new \Exception($name . ' is not instanciable.');
}elseif(!$reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Model')){
} elseif (!$reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Model')) {
$this->comment("Class '$name' is not a model");
continue;
}
$model = new $name();
if($hasDoctrine){
if ($hasDoctrine) {
$this->getPropertiesFromTable($model);
}
$this->getPropertiesFromMethods($model);
$output .= $this->createPhpDocs($name);
}catch(\Exception $e){
$this->error("Exception: ".$e->getMessage()."\nCould not analyze class $name.");
} catch (\Exception $e) {
$this->error("Exception: " . $e->getMessage() . "\nCould not analyze class $name.");
}
}else{
} else {
$this->error("Class $name does not exist");
}
}
if(!$hasDoctrine){
$this->error("Warning: 'doctrine/dbal: ~2.3' is required to load database information. Please require that in your composer.json and run 'composer update'.");
if (!$hasDoctrine) {
$this->error(
"Warning: 'doctrine/dbal: ~2.3' is required to load database information. Please require that in your composer.json and run 'composer update'."
);
}
return $output;
@@ -183,12 +192,13 @@ class ModelsCommand extends Command {
}
protected function loadModels(){
protected function loadModels()
{
$models = array();
foreach($this->dirs as $dir){
foreach ($this->dirs as $dir) {
$dir = base_path() . '/' . $dir;
if(file_exists($dir)){
foreach(ClassMapGenerator::createMap($dir) as $model=> $path){
if (file_exists($dir)) {
foreach (ClassMapGenerator::createMap($dir) as $model => $path) {
$models[] = $model;
}
}
@@ -201,21 +211,22 @@ class ModelsCommand extends Command {
*
* @param \Illuminate\Database\Eloquent\Model $model
*/
protected function getPropertiesFromTable($model){
protected function getPropertiesFromTable($model)
{
$table = $model->getConnection()->getTablePrefix() . $model->getTable();
$schema = $model->getConnection()->getDoctrineSchemaManager($table);
$schema->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
$columns = $schema->listTableColumns($table);
if($columns){
if ($columns) {
foreach ($columns as $column) {
$name = $column->getName();
if(in_array($name, $model->getDates())){
if (in_array($name, $model->getDates())) {
$type = '\Carbon\Carbon';
}else{
$type = $column->getType()->getName();
switch($type){
} else {
$type = $column->getType()->getName();
switch ($type) {
case 'string':
case 'text':
case 'date':
@@ -245,7 +256,11 @@ class ModelsCommand extends Command {
$this->setProperty($name, $type, true, true);
$this->setMethod(Str::camel("where_".$name), '\Illuminate\Database\Query\Builder|\\'.get_class($model), array('$value'));
$this->setMethod(
Str::camel("where_" . $name),
'\Illuminate\Database\Query\Builder|\\' . get_class($model),
array('$value')
);
}
}
}
@@ -253,33 +268,42 @@ class ModelsCommand extends Command {
/**
* @param \Illuminate\Database\Eloquent\Model $model
*/
protected function getPropertiesFromMethods($model){
protected function getPropertiesFromMethods($model)
{
$methods = get_class_methods($model);
if($methods){
foreach($methods as $method){
if(Str::startsWith($method, 'get') && Str::endsWith($method, 'Attribute') && $method !== 'getAttribute'){
if ($methods) {
foreach ($methods as $method) {
if (Str::startsWith($method, 'get') && Str::endsWith(
$method,
'Attribute'
) && $method !== 'getAttribute'
) {
//Magic get<name>Attribute
$name = Str::snake(substr($method, 3, -9));
if(!empty($name)){
$name = Str::snake(substr($method, 3, -9));
if (!empty($name)) {
$this->setProperty($name, null, true, null);
}
}elseif(Str::startsWith($method, 'set') && Str::endsWith($method, 'Attribute') && $method !== 'setAttribute'){
} elseif (Str::startsWith($method, 'set') && Str::endsWith(
$method,
'Attribute'
) && $method !== 'setAttribute'
) {
//Magic set<name>Attribute
$name = Str::snake(substr($method, 3, -9));
if(!empty($name)){
$name = Str::snake(substr($method, 3, -9));
if (!empty($name)) {
$this->setProperty($name, null, null, true);
}
}elseif(Str::startsWith($method, 'scope') && $method !== 'scopeQuery'){
} elseif (Str::startsWith($method, 'scope') && $method !== 'scopeQuery') {
//Magic set<name>Attribute
$name = Str::camel(substr($method, 5));
if(!empty($name)){
$name = Str::camel(substr($method, 5));
if (!empty($name)) {
$reflection = new \ReflectionMethod($model, $method);
$args = $this->getParameters($reflection);
//Remove the first ($query) argument
array_shift($args);
$this->setMethod($name, '\\'.$reflection->class, $args);
$this->setMethod($name, '\\' . $reflection->class, $args);
}
}elseif(!method_exists('Eloquent', $method) && !Str::startsWith($method, 'get')){
} elseif (!method_exists('Eloquent', $method) && !Str::startsWith($method, 'get')) {
//Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php
$reflection = new \ReflectionMethod($model, $method);
@@ -288,24 +312,37 @@ class ModelsCommand extends Command {
$file->seek($reflection->getStartLine() - 1);
$code = '';
while ($file->key() < $reflection->getEndLine())
{
$code .= $file->current(); $file->next();
while ($file->key() < $reflection->getEndLine()) {
$code .= $file->current();
$file->next();
}
$begin = strpos($code, 'function(');
$code = substr($code, $begin, strrpos($code, '}') - $begin + 1);
foreach(array('hasMany', 'belongsToMany', 'hasOne', 'belongsTo', 'morphTo', 'morphMany', 'morphToMany') as $relation){
$search = '$this->'.$relation.'(';
if($pos = stripos($code, $search)){
foreach (array(
'hasMany',
'belongsToMany',
'hasOne',
'belongsTo',
'morphTo',
'morphMany',
'morphToMany'
) as $relation) {
$search = '$this->' . $relation . '(';
if ($pos = stripos($code, $search)) {
$code = substr($code, $pos + strlen($search));
$arguments = explode(',', substr($code, 0, stripos($code, ')')));
//Remove quotes, ensure 1 \ in front of the model
$returnModel = "\\".ltrim(trim($arguments[0], " \"'"), "\\");
if($relation === "belongsToMany" or $relation === 'hasMany' or $relation === 'morphMany' or $relation === 'morphToMany'){
$returnModel = "\\" . ltrim(trim($arguments[0], " \"'"), "\\");
if ($relation === "belongsToMany" or $relation === 'hasMany' or $relation === 'morphMany' or $relation === 'morphToMany') {
//Collection or array of models (because Collection is Arrayable)
$this->setProperty($method, '\Illuminate\Database\Eloquent\Collection|'.$returnModel.'[]', true, null);
}else{
$this->setProperty(
$method,
'\Illuminate\Database\Eloquent\Collection|' . $returnModel . '[]',
true,
null
);
} else {
//Single model is returned
$this->setProperty($method, $returnModel, true, null);
}
@@ -323,26 +360,28 @@ class ModelsCommand extends Command {
* @param bool|null $read
* @param bool|null $write
*/
protected function setProperty($name, $type = null, $read = null, $write = null){
if(!isset($this->properties[$name])){
protected function setProperty($name, $type = null, $read = null, $write = null)
{
if (!isset($this->properties[$name])) {
$this->properties[$name] = array();
$this->properties[$name]['type'] = 'mixed';
$this->properties[$name]['read'] = false;
$this->properties[$name]['write'] = false;
}
if($type !== null){
if ($type !== null) {
$this->properties[$name]['type'] = $type;
}
if($read !== null){
if ($read !== null) {
$this->properties[$name]['read'] = $read;
}
if($write !== null){
if ($write !== null) {
$this->properties[$name]['write'] = $write;
}
}
protected function setMethod($name, $type = '', $arguments=array()){
if(!isset($this->methods[$name])){
protected function setMethod($name, $type = '', $arguments = array())
{
if (!isset($this->methods[$name])) {
$this->methods[$name] = array();
$this->methods[$name]['type'] = $type;
$this->methods[$name]['arguments'] = $arguments;
@@ -353,55 +392,56 @@ class ModelsCommand extends Command {
* @param string $class
* @return string
*/
protected function createPhpDocs($class){
protected function createPhpDocs($class)
{
$reflection = new \ReflectionClass($class);
$namespace = $reflection->getNamespaceName();
$classname = $reflection->getShortName();
$originalDoc = $reflection->getDocComment();
if($this->reset){
if ($this->reset) {
$phpdoc = new DocBlock('', new Context($namespace));
}else{
} else {
$phpdoc = new DocBlock($reflection, new Context($namespace));
}
if(!$phpdoc->getText()){
if (!$phpdoc->getText()) {
$phpdoc->setText($class);
}
$properties = array();
$methods = array();
foreach($phpdoc->getTags() as $tag){
foreach ($phpdoc->getTags() as $tag) {
$name = $tag->getName();
if($name == "property" || $name == "property-read" || $name == "property-write"){
$properties[] =$tag->getVariableName();
}elseif($name == "method"){
if ($name == "property" || $name == "property-read" || $name == "property-write") {
$properties[] = $tag->getVariableName();
} elseif ($name == "method") {
$methods[] = $tag->getMethodName();
}
}
foreach($this->properties as $name => $property){
foreach ($this->properties as $name => $property) {
$name = "\$$name";
if(in_array($name, $properties)){
if (in_array($name, $properties)) {
continue;
}
if($property['read'] && $property['write']){
if ($property['read'] && $property['write']) {
$attr = 'property';
}elseif($property['write']){
} elseif ($property['write']) {
$attr = 'property-write';
}else{
} else {
$attr = 'property-read';
}
$tag = Tag::createInstance("@{$attr} {$property['type']} {$name}", $phpdoc);
$phpdoc->appendTag($tag);
}
foreach($this->methods as $name => $method){
if(in_array($name, $methods)){
foreach ($this->methods as $name => $method) {
if (in_array($name, $methods)) {
continue;
}
$arguments = implode(', ',$method['arguments']);
$arguments = implode(', ', $method['arguments']);
$tag = Tag::createInstance("@method static {$method['type']} {$name}({$arguments}) ", $phpdoc);
$phpdoc->appendTag($tag);
}
@@ -411,21 +451,21 @@ class ModelsCommand extends Command {
$docComment = $serializer->getDocComment($phpdoc);
if($this->write){
if ($this->write) {
$filename = $reflection->getFileName();
$contents = \File::get($filename);
if($originalDoc){
if ($originalDoc) {
$contents = str_replace($originalDoc, $docComment, $contents);
}else{
} else {
$needle = "class {$classname}";
$replace = "{$docComment}\nclass {$classname}";
$pos = strpos($contents,$needle);
$pos = strpos($contents, $needle);
if ($pos !== false) {
$contents = substr_replace($contents,$replace,$pos,strlen($needle));
$contents = substr_replace($contents, $replace, $pos, strlen($needle));
}
}
if(\File::put($filename, $contents)){
$this->info('Written new phpDocBlock to '.$filename);
if (\File::put($filename, $contents)) {
$this->info('Written new phpDocBlock to ' . $filename);
}
}
@@ -439,25 +479,26 @@ class ModelsCommand extends Command {
* @param $method
* @return array
*/
public function getParameters($method){
public function getParameters($method)
{
//Loop through the default values for paremeters, and make the correct output string
$params = array();
$paramsWithDefault = array();
foreach ($method->getParameters() as $param) {
$paramStr = '$'.$param->getName();
$paramStr = '$' . $param->getName();
$params[] = $paramStr;
if ($param->isOptional()) {
$default = $param->getDefaultValue();
if(is_bool($default)){
$default = $default? 'true':'false';
}elseif(is_array($default)){
if (is_bool($default)) {
$default = $default ? 'true' : 'false';
} elseif (is_array($default)) {
$default = 'array()';
}elseif(is_null($default)){
} elseif (is_null($default)) {
$default = 'null';
}elseif(is_int($default)){
} elseif (is_int($default)) {
//$default = $default;
}else{
$default = "'".trim($default)."'";
} else {
$default = "'" . trim($default) . "'";
}
$paramStr .= " = $default";
}