Compare commits

..
25 Commits
Author SHA1 Message Date
Barry vd. Heuvel 1d01f5b278 Update Eloquent Builder 2013-06-07 12:26:54 +02:00
Barry vd. Heuvel 2466f5a5a4 Update readme 2013-06-07 11:33:12 +02:00
Barry vd. Heuvel bbbdd02708 Refactor and add comments 2013-06-07 11:26:57 +02:00
Barry vd. Heuvel d8a6bfbf21 Update readme 2013-06-06 15:13:02 +02:00
Barry vd. Heuvel ce4e9804ef Use full namespace 2013-06-06 13:48:53 +02:00
Barry vd. Heuvel 12845b38f0 Use declaring class
When function is inherited, link to the original class.
2013-06-06 13:45:32 +02:00
Barry vd. Heuvel 0b3b8b95cd Merge sublime and netbeans/phpstorm
Gives some warnings for phpStorm, but only in the helper file, so
doesn't affect the autocomplete / warnings in application code.
2013-06-06 13:45:05 +02:00
Barry vd. Heuvel 2ee05260d5 Simplify sublime output 2013-06-06 13:19:15 +02:00
Barry vd. Heuvel ec302acc3f Make __construct return @self 2013-06-05 17:45:24 +02:00
Barry vd. Heuvel e0b47835f4 roll back static for relations 2013-06-04 15:36:39 +02:00
Barry vd. Heuvel a0f6a370e1 Tweak return values 2013-06-04 15:34:56 +02:00
Barry vd. Heuvel 77c8bfa05a Fix default model path 2013-06-04 14:46:18 +02:00
Barry vd. Heuvel 62deba4171 Make builder work for relations
Fixes #22
2013-06-04 14:12:47 +02:00
Barry vd. Heuvel 32918908fc Add delete to non-static methods 2013-06-04 14:12:23 +02:00
Barry vd. Heuvel cca1b5896e Only allow relative path 2013-05-30 21:26:02 +02:00
Barry vd. Heuvel 3afc4a3ade Add dir option and fix namespace for models 2013-05-30 21:22:00 +02:00
Barry vd. Heuvel 3ac68d5446 Change order 2013-05-30 21:40:02 +03:00
Barry vd. Heuvel 26f09bccbf Throw error when compiled.php exists 2013-05-30 21:39:12 +03:00
Barry vd. Heuvel a4ab0a5969 Allow writing directly to models 2013-05-30 12:45:26 +02:00
Barry vd. Heuvel b0b324b8cc Use reflection and reflectiondocblock
Load the original docblock and append the changes. This way, you can
just copy the new comments in whole (next step, replace in file..)
2013-05-30 11:54:45 +02:00
Barry vd. Heuvel dab594804b Map enum to string
Fixes #19
2013-05-30 10:15:56 +02:00
Barry vd. Heuvel 83d5fe048d Revert changes 2013-05-29 17:32:38 +02:00
Barry vd. Heuvel 77b1bc923e Set mapping for enum 2013-05-29 18:31:33 +03:00
Barry vd. Heuvel 9090aeb766 Catch getType
Hopefully fixes #19
2013-05-29 18:24:43 +03:00
Barry vd. Heuvel a5c16b0751 update readme 2013-05-29 10:28:23 +02:00
4 changed files with 192 additions and 89 deletions
+19 -19
View File
@@ -1,19 +1,21 @@
## Laravel IDE Helper & Generator
## Laravel IDE Helper Generator
### Complete phpDocs, directly from the source
Add the helper file to your laravel folder (not in a public folder). The file isn't used by Laravel, but it has to be indexed by your IDE.
This packages generates a file that your IDE can understand, so it can provide accurate autocompletion. Generation is done, based on the files in your project, so they are alway up-to-date.
If you don't want to generate it, you can add a pre-generated file to the root folder of your laravel project. (But this isn't as up-to-date as self generated files)
* Netbeans and PHPStorm version: https://gist.github.com/barryvdh/5227822
* SublimeText CodeIntel version: https://gist.github.com/barryvdh/5227814
* Generated version: https://gist.github.com/barryvdh/5227822
Note: You do need CodeIntel for Sublime Text: https://github.com/Kronuz/SublimeCodeIntel
### Automatic phpDoc generation for Laravel Facades
Require this package in your composer.json:
Require this package in your composer.json and run composer update (or run `composer require barryvdh/laravel-ide-helper:1.*` directly):
"barryvdh/laravel-ide-helper": "1.*"
And add the ServiceProvider to the providers array in app/config/app.php
After updating composer, add the ServiceProvider to the providers array in app/config/app.php
'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider',
@@ -21,18 +23,14 @@ You can now re-generate the docs yourself (for future updates) in artisan
php artisan ide-helper:generate
If you use SublimeText CodeIntel, the format is a bit different. So add --sublime (or -S) to your command
php artisan ide-helper:generate -S
Note: You do need CodeIntel for Sublime Text: https://github.com/Kronuz/SublimeCodeIntel
Note: bootstrap/compiled.php has to be cleared first, so run `php artisan clear-compiled` before generating (and `php artisan optimize` after..)
You can configure your composer.json to do this after each commit:
"scripts":{
"post-update-cmd":[
"php artisan optimize",
"php artisan ide-helper:generate",
"php artisan optimize",
]
},
@@ -49,24 +47,26 @@ You can choose to include helper files. This is not enabled by default, but you
The Illuminate/Support/helpers.php is already set-up, but you can add/remove your own files in the config file.
### Work in progress: Model docs
### Automatic phpDocs for Models
If you don't want to write your properties yourself, you can use the (experimental) command `ide-helper:models` to generate
phpDocs, based on table columns, relations and getters/setters. Very alpha, so please provide feedback if you want.
Docs are written to a phpfile in the root of the project, so you can move the docs to the real model.
If you don't want to write your properties yourself, you can use the command `ide-helper:models` to generate
phpDocs, based on table columns, relations and getters/setters. Still in beta, so please provide feedback if you want.
Docs are written to a phpfile (_ide_helper_models.php) in the root of the project, so you can move the docs to the real model.
For now, only models in app/models are scanned. The optional argument tells what models to use.
You can now also write the comments directly to your Model file, using the -W argument. Please make sure to backup your models, before writing the info.
It should keep the existing comments and only append new properties/methods. The existing phpdoc is replaced, or added if not found.
For now, only models in app/models are scanned. The optional argument tells what models to use (also outside app/models).
`php artisan ide-helper:models Post,User`
Note: With namespaces, uses \\ instead of \
`php artisan ide-helper:models API\\User`
This creates a file with the phpDocs for each Model. You should check and change them to be more accurate.
It doesn't know if datetimes are returned as string or DateTime/Carbon, but I assume they are.
Also, all relations are Eloquent|Eloquent[] by default, you can change them to the actual Model.
After copying the phpdocs to your model, you can clear the file, so your IDE only uses the real source.
### License
The Laravel IDE Helper Generator is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
The Laravel IDE Helper Generator is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
@@ -42,7 +42,6 @@ class GeneratorCommand extends Command {
protected $nonstatic;
protected $onlyExtend;
protected $helpers;
protected $sublime;
/**
@@ -52,34 +51,35 @@ class GeneratorCommand extends Command {
*/
public function fire()
{
$filename = $this->argument('filename');
if($this->option('memory')){
$this->useMemoryDriver();
}
$this->extra = \Config::get('laravel-ide-helper::extra');
$this->nonstatic = \Config::get('laravel-ide-helper::nonstatic');
$this->onlyExtend = \Config::get('laravel-ide-helper::only_extend');
if( $this->option('helpers') || (\Config::get('laravel-ide-helper::include_helpers') && ! $this->option('nohelpers'))){
$this->helpers = \Config::get('laravel-ide-helper::helper_files');
if (file_exists($compiled = base_path().'/bootstrap/compiled.php')){
$this->error('Error generating IDE Helper: first delete bootstrap/compiled.php (php artisan clear-compiled)');
}else{
$this->helpers = array();
}
$this->sublime = $this->option('sublime') || \Config::get('laravel-ide-helper::sublime');
$content = $this->generateDocs();
$written = \File::put($filename, $content);
if($written !== false){
$this->info("A new helper file was written to $filename");
}else{
$this->error("The helper file could not be created at $filename");
}
$filename = $this->argument('filename');
if($this->option('memory')){
$this->useMemoryDriver();
}
$this->extra = \Config::get('laravel-ide-helper::extra');
$this->nonstatic = \Config::get('laravel-ide-helper::nonstatic');
$this->onlyExtend = \Config::get('laravel-ide-helper::only_extend');
if( $this->option('helpers') || (\Config::get('laravel-ide-helper::include_helpers') && ! $this->option('nohelpers'))){
$this->helpers = \Config::get('laravel-ide-helper::helper_files');
}else{
$this->helpers = array();
}
$content = $this->generateDocs();
$written = \File::put($filename, $content);
if($written !== false){
$this->info("A new helper file was written to $filename");
}else{
$this->error("The helper file could not be created at $filename");
}
}
}
protected function useMemoryDriver(){
@@ -113,7 +113,7 @@ class GeneratorCommand extends Command {
return array(
array('helpers', "H", InputOption::VALUE_NONE, 'Include the helper files'),
array('memory', "M", InputOption::VALUE_NONE, 'Use sqlite memory driver'),
array('sublime', "S", InputOption::VALUE_NONE, 'Use different style for SublimeText CodeIntel'),
array('sublime', "S", InputOption::VALUE_NONE, 'DEPRECATED: Use different style for SublimeText CodeIntel'),
);
}
@@ -135,21 +135,26 @@ class GeneratorCommand extends Command {
*/
namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
//Get all aliases
$aliases = $aliasLoader->getAliases();
foreach($aliases as $alias => $facade){
try{
//If possible, get the facade root
if(method_exists($facade, 'getFacadeRoot')){
$root = get_class($facade::getFacadeRoot());
}else{
$root = $facade;
}
//If it doesn't exist, skip it
if(!class_exists($root) && !interface_exists($root)){
$this->error("Class $root is not found.");
continue;
}
//When the database connection is not set, some classes will be skipped
}catch(\PDOException $e){
$this->error("PDOException: ".$e->getMessage()."\nPlease configure your database connection correctly, or use the sqlite memory driver (-M). Skipping $facade.");
continue;
@@ -158,6 +163,7 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
continue;
}
//Get the namespace from the alias.
if(strpos($alias, '\\') !== false){
$parts = explode('\\', $alias);
$alias = array_pop($parts);
@@ -167,43 +173,49 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
}
try{
//Reflect on the class
$reflection = new \ReflectionClass($root);
$output .= "namespace $namespace {\n";
//Some classes extend the facade
if($root !== $facade or in_array($alias, $this->onlyExtend)){
//If the root class is not the same as the facade extend it.
$output .= " class $alias extends $facade{\n";
}else{
$output .= " class $alias{\n";
}
$output .= "\t/**\n\t * @var \\$root \$root\n\t */\n\t static private \$root;\n\n";
//If they extend, don't include them.
if(!in_array($alias, $this->onlyExtend))
{
$usedMethods = array();
//Check if there are non-static methods for this alias
if(array_key_exists($alias, $this->nonstatic) ){
$nonstaticMethods = $this->nonstatic[$alias];
}else{
$nonstaticMethods = array();
}
//Get all public methods for this class
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if($methods)
{
foreach ($methods as $method)
{
//Skip methods that are already used
if(!in_array($method->name, $usedMethods)){
$static = !in_array($method->name, $nonstaticMethods);
$output .= $this->parseMethod($method, $alias, $root, $static);
$declaringClass = $method->getDeclaringClass();
$output .= $this->parseMethod($method, $alias, $static);
$usedMethods[] = $method->name;
}
}
}
//Add extra methods, from other classes (magic calls)
if(array_key_exists($alias, $this->extra)){
$i = 2;
foreach($this->extra[$alias] as $extraClass){
if(!class_exists($extraClass) && !interface_exists($extraClass)){
continue;
@@ -213,13 +225,11 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if($methods)
{
$rootParam = "root".$i++;
$output .= "\t/**\n\t * @var \\$extraClass \$$rootParam\n\t */\n\t static private \$$rootParam;\n\n";
foreach ($methods as $method)
{
if(!in_array($method->name, $usedMethods)){
$static = !in_array($method->name, $nonstaticMethods);
$output .= $this->parseMethod($method, $alias, $extraClass, $static, $rootParam);
$output .= $this->parseMethod($method, $alias, $static);
$usedMethods[] = $method->name;
}
@@ -237,6 +247,7 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
}
//Include the helper file, if requested
if(!empty($helpers)){
foreach($helpers as $helper){
if (file_exists($helper)){
@@ -256,19 +267,24 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
* @param string $rootParam
* @return string
*/
protected function parseMethod($method, $alias, $root, $static = true, $rootParam = 'root'){
protected function parseMethod($method, $alias, $static = true){
$output = '';
// Don't add the __clone() functions
if($method->name === '__clone'){
return $output;
}
$namespace = $method->getDeclaringClass()->getNamespaceName();
//Create a DocBlock and serializer instance
$phpdoc = new DocBlock($method, new Context($namespace));
$serializer = new DocBlockSerializer(1, "\t");
//Get the short + long description from the DocBlock
$description = $phpdoc->getText();
//Loop through parents/interfaces, to fill in {@inheritdoc}
if(strpos($description, '{@inheritdoc}') !== false){
$inheritdoc = $this->getInheritDoc($method);
$inheritDescription = $inheritdoc->getText();
@@ -276,6 +292,7 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
$description = str_replace('{@inheritdoc}', $inheritDescription, $description);
$phpdoc->setText($description);
//Add the tags that are inherited
$inheritTags = $inheritdoc->getTags();
if($inheritTags){
foreach($inheritTags as $tag){
@@ -285,6 +302,7 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
}
}
//Make the method static
$phpdoc->appendTag(Tag::createInstance('@static', $phpdoc));
//Looping through the parameters and re-setting the type, to get the expanded type (with namespace)
@@ -302,27 +320,34 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
}
}
//Get the return type and adjust them for beter autocomplete
$returnTags = $phpdoc->getTagsByName('return');
if($returnTags){
/** @var $tag */
$tag = reset($returnTags);
$returnValue = $tag->getType();
if(!$this->sublime and $alias == 'Eloquent' and
if($method->name == "__construct"){
$returnValue = 'self';
}elseif($alias == 'Eloquent' and
(in_array($method->name, array('pluck', 'first', 'fill', 'newInstance', 'newFromBuilder', 'create', 'find', 'findOrFail'))
or $returnValue === '\Illuminate\Database\Query\Builder')){
//Reference the calling class, to provide more accurate auto-complete
$returnValue = "static";
}elseif(!$this->sublime and $alias == 'Eloquent' and in_array($method->name, array('all', 'get'))){
$returnValue .= "static";
}elseif($alias == 'Eloquent' and in_array($method->name, array('all', 'get'))){
$returnValue .= "|\Eloquent[]|static[]";
}elseif($alias == 'Eloquent' and in_array($method->name, array('hasOne', 'hasMany', 'belongsTo', 'belongsToMany', 'morphOne', 'morphTo', 'morphMany'))){
$returnValue .= "|\Eloquent";
}
$tag->setContent($returnValue . " ". $tag->getDescription());
}else{
$returnValue = null;
}
//Write the output, using the DocBlock serializer
$output .= $serializer->getDocComment($phpdoc) ."\n\t public ".($static ? 'static' : '')." function ".$method->name."(";
//Loop through the default values for paremeters, and make the correct output string
$params = array();
$paramsWithDefault = array();
foreach ($method->getParameters() as $param) {
@@ -348,14 +373,14 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
$output .= implode($paramsWithDefault, ", ");
$output .= "){\r\n";
$return = ($returnValue && $returnValue !== "void") ? 'return' : '';
//Only return when not a constructor and not void.
$return = ($returnValue && $returnValue !== "void" && $method->name !== "__construct") ? 'return' : '';
if($this->sublime){
$output .= "\t\t\$$rootParam = new $root();\r\n";
$output .= "\t\t$return \$$rootParam->";
}else{
$output .= "\t\t$return static::\$$rootParam->";
}
//Reference the 'real' function in the declaringclass
$root = $method->getDeclaringClass()->getName();
$output .= "\t\t$return \\$root::";
//Write the default parameters in the function call
$output .= $method->name."(".implode($params, ", ").");\r\n";
$output .= "\t }\n\n";
@@ -369,6 +394,7 @@ namespace {\n\tdie('Only to be used as an helper for your IDE');\n}\n\n";
protected function getInheritDoc($reflectionMethod){
$parentClass = $reflectionMethod->getDeclaringClass()->getParentClass();
//Get either a parent or the interface
if($parentClass){
$method = $parentClass->getMethod($reflectionMethod->getName());
}else{
+99 -22
View File
@@ -13,6 +13,10 @@ use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\ClassLoader\ClassMapGenerator;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Context;
use phpDocumentor\Reflection\DocBlock\Tag;
use phpDocumentor\Reflection\DocBlock\Serializer as DocBlockSerializer;
/**
* A command to generate autocomplete information for your IDE
*
@@ -36,6 +40,9 @@ class ModelsCommand extends Command {
protected $properties = array();
protected $methods = array();
protected $write = false;
protected $dir;
/**
@@ -46,16 +53,19 @@ class ModelsCommand extends Command {
public function fire()
{
$filename = $this->option('filename');
$this->write = $this->option('write');
$this->dir = $this->option('dir');
$model = $this->argument('model');
$content = $this->generateDocs($model);
$written = \File::put($filename, $content);
if($written !== false){
$this->info("Model information was written to $filename");
}else{
$this->error("Failed to write model information to $filename");
if(!$this->write){
$written = \File::put($filename, $content);
if($written !== false){
$this->info("Model information was written to $filename");
}else{
$this->error("Failed to write model information to $filename");
}
}
}
@@ -83,6 +93,8 @@ class ModelsCommand extends Command {
{
return array(
array('filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the helper file', '_ide_helper_models.php'),
array('dir', 'D', InputOption::VALUE_OPTIONAL, 'The model dir','app/models'),
array('write', 'W', InputOption::VALUE_NONE, 'Write to Model file'),
);
}
@@ -129,24 +141,33 @@ class ModelsCommand extends Command {
protected function loadModels(){
$dir = base_path().'/'.$this->dir;
$models = array();
foreach(ClassMapGenerator::createMap(app_path().'/models') as $model=> $path){
$models[] = $model;
if(file_exists($dir)){
foreach(ClassMapGenerator::createMap($dir) as $model=> $path){
$models[] = $model;
}
}
return $models;
}
/**
* Load the properties from the database table.
*
* @param \Illuminate\Database\Eloquent\Model $model
*/
protected function getPropertiesFromTable($model){
$table = $model->getTable();
$schema = $model->getConnection()->getDoctrineSchemaManager($table);
$schema->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
$columns = $schema->listTableColumns($table);
$properties = array();
if($columns){
foreach ($columns as $column) {
$name = $column->getName();
$type = $column->getType()->getName();
switch($type){
case 'string':
case 'text':
@@ -180,6 +201,9 @@ class ModelsCommand extends Command {
}
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
*/
protected function getPropertiesFromMethods($model){
$methods = get_class_methods($model);
if($methods){
@@ -242,6 +266,12 @@ class ModelsCommand extends Command {
}
}
/**
* @param string $name
* @param string|null $type
* @param bool|null $read
* @param bool|null $write
*/
protected function setProperty($name, $type = null, $read = null, $write = null){
if(!isset($this->properties[$name])){
$this->properties[$name] = array();
@@ -270,18 +300,38 @@ class ModelsCommand extends Command {
}
}
/**
* @param string $class
* @return string
*/
protected function createPhpDocs($class){
if(strpos($class, '\\') !== false){
$parts = explode('\\', $class);
$class = array_pop($parts);
$namespace = implode($parts, '\\');
}else{
$namespace = '';
$reflection = new \ReflectionClass($class);
$namespace = $reflection->getNamespaceName();
$classname = $reflection->getShortName();
$originalDoc = $reflection->getDocComment();
$phpdoc = new DocBlock($reflection, new Context($namespace));
if(!$phpdoc->getText()){
$phpdoc->setText("Generated properties for $class");
}
$output = "namespace $namespace{\n";
$output .= "\t/**\n\t *\n\t * Generated properties for $class\n\t *\n";
$properties = array();
$methods = array();
foreach($phpdoc->getTags() as $tag){
$name = $tag->getName();
if($name == "property" || $name == "property-read" || $name == "property-write"){
$properties[] =$tag->getVariableName();
}elseif($name == "method"){
$methods[] = $tag->getMethodName();
}
}
foreach($this->properties as $name => $property){
$name = "\$$name";
if(in_array($name, $properties)){
continue;
}
if($property['read'] && $property['write']){
$attr = 'property';
}elseif($property['write']){
@@ -289,16 +339,43 @@ class ModelsCommand extends Command {
}else{
$attr = 'property-read';
}
$type = $property['type'];
$output .= "\t * @$attr $type \$$name \n";
$tag = Tag::createInstance("@{$attr} {$property['type']} {$name}", $phpdoc);
$phpdoc->appendTag($tag);
}
foreach($this->methods as $name => $method){
$type = $method['type'];
$output .= "\t * @method $type $name() \n";
if(in_array($name, $methods)){
continue;
}
$name = "$name()";
$tag = Tag::createInstance("@method {$method['type']} {$name}", $phpdoc);
$phpdoc->appendTag($tag);
}
$output .= "\t *\n\t */\n\tclass $class {}\n}\n\n";
$serializer = new DocBlockSerializer();
$serializer->getDocComment($phpdoc);
$docComment = $serializer->getDocComment($phpdoc);
if($this->write){
$filename = $reflection->getFileName();
$contents = \File::get($filename);
if($originalDoc){
$contents = str_replace($originalDoc, $docComment, $contents);
}else{
$needle = "class {$classname}";
$replace = "{$docComment}\nclass {$classname}";
$pos = strpos($contents,$needle);
if ($pos !== false) {
$contents = substr_replace($contents,$replace,$pos,strlen($needle));
}
}
if(\File::put($filename, $contents)){
$this->info('Written new phpDocBlock to '.$filename);
}
}
$output = "namespace {$namespace}{\n{$docComment}\n\tclass {$classname} {}\n}\n\n";
return $output;
}
+2 -2
View File
@@ -55,7 +55,7 @@ return array(
'Auth' => array('Illuminate\Auth\Guard'),
'Cache' => array('Illuminate\Cache\StoreInterface', 'Illuminate\Cache\Repository'),
'DB' => array('Illuminate\Database\Connection'),
'Eloquent' => array('Illuminate\Database\Query\Builder'),
'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'),
'Queue' => array('Illuminate\Queue\QueueInterface'),
),
@@ -70,7 +70,7 @@ return array(
*/
'nonstatic' => array(
'Eloquent' => array('freshTimestamp', 'newCollection', 'toArray', 'toJson', 'toSql'),
'Eloquent' => array('freshTimestamp', 'newCollection', 'toArray', 'toJson', 'toSql', 'delete'),
),
/*