Merge pull request #1 from barryvdh/master

merge master
This commit is contained in:
ApolloPY
2018-11-30 20:26:36 +08:00
committed by GitHub
16 changed files with 299 additions and 102 deletions
+3 -7
View File
@@ -1,10 +1,9 @@
language: php language: php
php: php:
- 5.5
- 5.6
- 7.0 - 7.0
- 7.1 - 7.1
- 7.2
# This triggers builds to run on the new TravisCI infrastructure. # This triggers builds to run on the new TravisCI infrastructure.
# See: http://docs.travis-ci.com/user/workers/container-based-infrastructure/ # See: http://docs.travis-ci.com/user/workers/container-based-infrastructure/
@@ -17,7 +16,7 @@ cache:
matrix: matrix:
include: include:
- php: 5.5 - php: 7.0
env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"'
before_script: before_script:
@@ -25,7 +24,4 @@ before_script:
script: script:
- vendor/bin/phpcs --standard=psr2 src/ - vendor/bin/phpcs --standard=psr2 src/
- vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover - vendor/bin/phpunit
after_script:
- if [[ $TRAVIS_PHP_VERSION != 'hhvm' && $TRAVIS_PHP_VERSION != '7.0' ]]; then php vendor/bin/ocular code-coverage:upload --format=php-clover coverage.clover; fi
+2 -2
View File
@@ -1,6 +1,6 @@
# The MIT License (MIT) # The MIT License (MIT)
Copyright (c) 2016 Barry vd. Heuvel <barryvdh@gmail.com> Copyright (c) Barry vd. Heuvel <barryvdh@gmail.com>
> Permission is hereby granted, free of charge, to any person obtaining a copy > Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal > of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ Copyright (c) 2016 Barry vd. Heuvel <[email protected]>
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE. > THE SOFTWARE.
+14 -12
View File
@@ -10,19 +10,20 @@
} }
], ],
"require": { "require": {
"php": ">=5.4.0", "php": ">=7",
"illuminate/support": "^5.0,<5.6", "illuminate/support": "^5.5,<5.8",
"illuminate/console": "^5.0,<5.6", "illuminate/console": "^5.5,<5.8",
"illuminate/filesystem": "^5.0,<5.6", "illuminate/filesystem": "^5.5,<5.8",
"barryvdh/reflection-docblock": "^2.0.4", "barryvdh/reflection-docblock": "^2.0.5",
"symfony/class-loader": "^2.3|^3.0" "composer/composer": "^1.6"
}, },
"require-dev": { "require-dev": {
"illuminate/config": "^5.0,<5.6", "illuminate/config": "^5.1,<5.8",
"illuminate/view": "^5.0,<5.6", "illuminate/view": "^5.1,<5.8",
"phpro/grumphp": "^0.14",
"phpunit/phpunit" : "4.*", "phpunit/phpunit" : "4.*",
"scrutinizer/ocular": "~1.1", "scrutinizer/ocular": "~1.1",
"squizlabs/php_codesniffer": "~2.3", "squizlabs/php_codesniffer": "^3",
"doctrine/dbal": "~2.3" "doctrine/dbal": "~2.3"
}, },
"suggest": { "suggest": {
@@ -35,16 +36,17 @@
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
":vendor\\:package_name\\": "tests" "Barryvdh\\LaravelIdeHelper\\": "tests"
} }
}, },
"scripts": { "scripts": {
"test": "phpunit", "test": "phpunit",
"cs": "phpcs --standard=psr2 src/" "check-style": "phpcs -p --standard=PSR2 src/",
"fix-style": "phpcbf -p --standard=PSR2 src/"
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.5-dev"
}, },
"laravel": { "laravel": {
"providers": [ "providers": [
+4 -4
View File
@@ -153,13 +153,13 @@ return array(
| |
| For example, normally you would see this: | For example, normally you would see this:
| |
| * @property \Carbon\Carbon $created_at | * @property \Illuminate\Support\Carbon $created_at
| * @property \Carbon\Carbon $updated_at | * @property \Illuminate\Support\Carbon $updated_at
| |
| With this enabled, the properties will be this: | With this enabled, the properties will be this:
| |
| * @property \Carbon\Carbon $createdAt | * @property \Illuminate\Support\Carbon $createdAt
| * @property \Carbon\Carbon $updatedAt | * @property \Illuminate\Support\Carbon $updatedAt
| |
| Note, it is currently an all-or-nothing option. | Note, it is currently an all-or-nothing option.
| |
+15
View File
@@ -0,0 +1,15 @@
parameters:
git_dir: .
bin_dir: vendor/bin
tasks:
phpunit:
config_file: ~
testsuite: ~
group: []
always_execute: false
phpcs:
standard: PSR2
warning_severity: ~
ignore_patterns:
- tests/
triggered_by: [php]
+2 -9
View File
@@ -10,7 +10,7 @@
processIsolation="false" processIsolation="false"
stopOnFailure="false"> stopOnFailure="false">
<testsuites> <testsuites>
<testsuite name=":vendor Test Suite"> <testsuite name="Unit Tests">
<directory>tests</directory> <directory>tests</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
@@ -19,11 +19,4 @@
<directory suffix=".php">src/</directory> <directory suffix=".php">src/</directory>
</whitelist> </whitelist>
</filter> </filter>
<logging> </phpunit>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage" charset="UTF-8" yui="true" highlight="true"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
+5 -5
View File
@@ -37,6 +37,7 @@ After updating composer, add the service provider to the `providers` array in `c
```php ```php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
``` ```
**Laravel 5.5** uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.
To install this package on only development systems, add the `--dev` flag to your composer command: To install this package on only development systems, add the `--dev` flag to your composer command:
@@ -66,7 +67,7 @@ You can now re-generate the docs yourself (for future updates)
php artisan ide-helper:generate php artisan ide-helper:generate
``` ```
Note: `bootstrap/compiled.php` has to be cleared first, so run `php artisan clear-compiled` before generating (and `php artisan optimize` after). Note: `bootstrap/compiled.php` has to be cleared first, so run `php artisan clear-compiled` before generating.
You can configure your composer.json to do this after each commit: You can configure your composer.json to do this after each commit:
@@ -75,8 +76,7 @@ You can configure your composer.json to do this after each commit:
"post-update-cmd": [ "post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate", "Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan ide-helper:generate", "php artisan ide-helper:generate",
"php artisan ide-helper:meta", "php artisan ide-helper:meta"
"php artisan optimize"
] ]
}, },
``` ```
@@ -122,8 +122,8 @@ php artisan ide-helper:models Post
* @property integer $author_id * @property integer $author_id
* @property string $title * @property string $title
* @property string $text * @property string $text
* @property \Carbon\Carbon $created_at * @property \Illuminate\Support\Carbon $created_at
* @property \Carbon\Carbon $updated_at * @property \Illuminate\Support\Carbon $updated_at
* @property-read \User $author * @property-read \User $author
* @property-read \Illuminate\Database\Eloquent\Collection|\Comment[] $comments * @property-read \Illuminate\Database\Eloquent\Collection|\Comment[] $comments
*/ */
+16 -4
View File
@@ -1,4 +1,14 @@
<?= '<?php' ?> <?= '<?php' ?>
<?php
/**
* @var \Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_alias_ns
* @var \Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_extends_ns
* @var bool $include_fluent
* @var string $helpers
*/
?>
// @formatter:off
/** /**
* A helper file for Laravel 5, to provide autocomplete information to your IDE * A helper file for Laravel 5, to provide autocomplete information to your IDE
@@ -15,6 +25,7 @@
namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> { namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> {
<?php foreach($aliases as $alias): ?> <?php foreach($aliases as $alias): ?>
<?= trim($alias->getDocComment(' ')) ?>
<?= $alias->getClassType() ?> <?= $alias->getExtendsClass() ?> { <?= $alias->getClassType() ?> <?= $alias->getExtendsClass() ?> {
<?php foreach($alias->getMethods() as $method): ?> <?php foreach($alias->getMethods() as $method): ?>
@@ -25,7 +36,7 @@ namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> {
//Method inherited from <?= $method->getDeclaringClass() ?> //Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?> <?php endif; ?>
<?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>); <?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getRealName() ?>(<?= $method->getParams() ?>);
} }
<?php endforeach; ?> <?php endforeach; ?>
} }
@@ -47,7 +58,7 @@ namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> {
//Method inherited from <?= $method->getDeclaringClass() ?> //Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?> <?php endif; ?>
<?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>); <?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getRealName() ?>(<?= $method->getParams() ?>);
} }
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?>} <?php endif; ?>}
@@ -71,7 +82,7 @@ namespace Illuminate\Support {
* @method Fluent charset(string $charset) Add the character set modifier * @method Fluent charset(string $charset) Add the character set modifier
* @method Fluent collation(string $collation) Add the collation modifier * @method Fluent collation(string $collation) Add the collation modifier
* @method Fluent comment(string $comment) Add comment * @method Fluent comment(string $comment) Add comment
* @method Fluent default(mixed $value) Add the default modifier * @method Fluent default($value) Add the default modifier
* @method Fluent first() Select first row * @method Fluent first() Select first row
* @method Fluent index(string $name = null) Add the in dex clause * @method Fluent index(string $name = null) Add the in dex clause
* @method Fluent on(string $table) `on` of a foreign key * @method Fluent on(string $table) `on` of a foreign key
@@ -79,10 +90,11 @@ namespace Illuminate\Support {
* @method Fluent onUpdate(string $action) `on update` of a foreign key * @method Fluent onUpdate(string $action) `on update` of a foreign key
* @method Fluent primary() Add the primary key modifier * @method Fluent primary() Add the primary key modifier
* @method Fluent references(string $column) `references` of a foreign key * @method Fluent references(string $column) `references` of a foreign key
* @method Fluent nullable() Add the nullable modifier * @method Fluent nullable(bool $value = true) Add the nullable modifier
* @method Fluent unique(string $name = null) Add unique index clause * @method Fluent unique(string $name = null) Add unique index clause
* @method Fluent unsigned() Add the unsigned modifier * @method Fluent unsigned() Add the unsigned modifier
* @method Fluent useCurrent() Add the default timestamp value * @method Fluent useCurrent() Add the default timestamp value
* @method Fluent change() Add the change modifier
*/ */
class Fluent {} class Fluent {}
} }
+2
View File
@@ -1,5 +1,7 @@
<?= '<?php' ?> <?= '<?php' ?>
// @formatter:off
namespace PHPSTORM_META { namespace PHPSTORM_META {
/** /**
+98 -8
View File
@@ -10,6 +10,12 @@
namespace Barryvdh\LaravelIdeHelper; namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag\MethodTag;
use ReflectionClass;
class Alias class Alias
{ {
protected $alias; protected $alias;
@@ -27,6 +33,7 @@ class Alias
protected $valid = false; protected $valid = false;
protected $magicMethods = array(); protected $magicMethods = array();
protected $interfaces = array(); protected $interfaces = array();
protected $phpdoc = null;
/** /**
* @param string $alias * @param string $alias
@@ -53,10 +60,17 @@ class Alias
} }
$this->addClass($this->root); $this->addClass($this->root);
$this->detectFake();
$this->detectNamespace(); $this->detectNamespace();
$this->detectClassType(); $this->detectClassType();
$this->detectExtendsNamespace(); $this->detectExtendsNamespace();
if (!empty($this->namespace)) {
//Create a DocBlock and serializer instance
$this->phpdoc = new DocBlock(new ReflectionClass($alias), new Context($this->namespace));
}
if ($facade === '\Illuminate\Database\Eloquent\Model') { if ($facade === '\Illuminate\Database\Eloquent\Model') {
$this->usedMethods = array('decrement', 'increment'); $this->usedMethods = array('decrement', 'increment');
} }
@@ -107,7 +121,7 @@ class Alias
{ {
return $this->extends; return $this->extends;
} }
/** /**
* Get the class short name which this alias extends * Get the class short name which this alias extends
* *
@@ -117,7 +131,7 @@ class Alias
{ {
return $this->extendsClass; return $this->extendsClass;
} }
/** /**
* Get the namespace of the class which this alias extends * Get the namespace of the class which this alias extends
* *
@@ -158,7 +172,7 @@ class Alias
/** /**
* Get the methods found by this Alias * Get the methods found by this Alias
* *
* @return array * @return array|Method[]
*/ */
public function getMethods() public function getMethods()
{ {
@@ -167,6 +181,30 @@ class Alias
return $this->methods; return $this->methods;
} }
/**
* Detect class returned by ::fake()
*/
protected function detectFake()
{
$facade = $this->facade;
if (!method_exists($facade, 'fake')) {
return;
}
$real = $facade::getFacadeRoot();
try {
$facade::fake();
$fake = $facade::getFacadeRoot();
if ($fake !== $real) {
$this->addClass(get_class($fake));
}
} finally {
$facade::swap($real);
}
}
/** /**
* Detect the namespace * Detect the namespace
*/ */
@@ -180,7 +218,7 @@ class Alias
$this->short = $this->alias; $this->short = $this->alias;
} }
} }
/** /**
* Detect the extends namespace * Detect the extends namespace
*/ */
@@ -273,7 +311,7 @@ class Alias
$method = new \ReflectionMethod($className, $name); $method = new \ReflectionMethod($className, $name);
$class = new \ReflectionClass($className); $class = new \ReflectionClass($className);
if (!in_array($method->name, $this->usedMethods)) { if (!in_array($magic, $this->usedMethods)) {
if ($class !== $this->root) { if ($class !== $this->root) {
$this->methods[] = new Method($method, $this->alias, $class, $magic, $this->interfaces); $this->methods[] = new Method($method, $this->alias, $class, $magic, $this->interfaces);
} }
@@ -319,10 +357,9 @@ class Alias
$properties = $reflection->getStaticProperties(); $properties = $reflection->getStaticProperties();
$macros = isset($properties['macros']) ? $properties['macros'] : []; $macros = isset($properties['macros']) ? $properties['macros'] : [];
foreach ($macros as $macro_name => $macro_func) { foreach ($macros as $macro_name => $macro_func) {
$function = new \ReflectionFunction($macro_func);
// Add macros // Add macros
$this->methods[] = new Macro( $this->methods[] = new Macro(
$function, $this->getMacroFunction($macro_func),
$this->alias, $this->alias,
$reflection, $reflection,
$macro_name, $macro_name,
@@ -333,6 +370,59 @@ class Alias
} }
} }
/**
* @param $macro_func
*
* @return \ReflectionFunctionAbstract
* @throws \ReflectionException
*/
protected function getMacroFunction($macro_func)
{
if (is_array($macro_func) && is_callable($macro_func)) {
return new \ReflectionMethod($macro_func[0], $macro_func[1]);
}
return new \ReflectionFunction($macro_func);
}
/*
* Get the docblock for this alias
*
* @param string $prefix
* @return mixed
*/
public function getDocComment($prefix = "\t\t")
{
$serializer = new DocBlockSerializer(1, $prefix);
if ($this->phpdoc) {
$this->removeDuplicateMethodsFromPhpDoc();
return $serializer->getDocComment($this->phpdoc);
}
return '';
}
/**
* Removes method tags from the doc comment that already appear as functions inside the class.
* This prevents duplicate function errors in the IDE.
*
* @return void
*/
protected function removeDuplicateMethodsFromPhpDoc()
{
$methods = count($this->methods) > 0 ? $this->methods : $this->getMethods();
$methodNames = array_map(function (Method $method) {
return $method->getName();
}, $methods);
foreach ($this->phpdoc->getTags() as $tag) {
if ($tag instanceof MethodTag && in_array($tag->getMethodName(), $methodNames)) {
$this->phpdoc->deleteTag($tag);
}
}
}
/** /**
* Output an error. * Output an error.
* *
-1
View File
@@ -115,7 +115,6 @@ class GeneratorCommand extends Command
if ($written !== false) { if ($written !== false) {
$this->info("A new helper file was written to $filename"); $this->info("A new helper file was written to $filename");
Eloquent::writeEloquentModelHelper($this, $this->files);
} else { } else {
$this->error("The helper file could not be created at $filename"); $this->error("The helper file could not be created at $filename");
} }
+5 -1
View File
@@ -122,7 +122,11 @@ class MetaCommand extends Command
$abstracts = $this->laravel->getBindings(); $abstracts = $this->laravel->getBindings();
// Return the abstract names only // Return the abstract names only
return array_keys($abstracts); $keys = array_keys($abstracts);
sort($keys);
return $keys;
} }
/** /**
+61 -11
View File
@@ -10,14 +10,15 @@
namespace Barryvdh\LaravelIdeHelper\Console; namespace Barryvdh\LaravelIdeHelper\Console;
use Composer\Autoload\ClassMapGenerator;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\Filesystem;
use ReflectionClass;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\ClassLoader\ClassMapGenerator;
use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context; use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Tag; use Barryvdh\Reflection\DocBlock\Tag;
@@ -56,6 +57,7 @@ class ModelsCommand extends Command
protected $write = false; protected $write = false;
protected $dirs = array(); protected $dirs = array();
protected $reset; protected $reset;
protected $keep_text;
/** /**
* @var bool[string] * @var bool[string]
*/ */
@@ -86,12 +88,15 @@ class ModelsCommand extends Command
$model = $this->argument('model'); $model = $this->argument('model');
$ignore = $this->option('ignore'); $ignore = $this->option('ignore');
$this->reset = $this->option('reset'); $this->reset = $this->option('reset');
if ($this->option('smart-reset')) {
$this->keep_text = $this->reset = true;
}
$this->write_model_magic_where = $this->laravel['config']->get('ide-helper.write_model_magic_where', true); $this->write_model_magic_where = $this->laravel['config']->get('ide-helper.write_model_magic_where', true);
//If filename is default and Write is not specified, ask what to do //If filename is default and Write is not specified, ask what to do
if (!$this->write && $filename === $this->filename && !$this->option('nowrite')) { if (!$this->write && $filename === $this->filename && !$this->option('nowrite')) {
if ($this->confirm( if ($this->confirm(
"Do you want to overwrite the existing model files? Choose no to write to $filename instead? (Yes/No): " "Do you want to overwrite the existing model files? Choose no to write to $filename instead?"
) )
) { ) {
$this->write = true; $this->write = true;
@@ -136,6 +141,7 @@ class ModelsCommand extends Command
array('write', 'W', InputOption::VALUE_NONE, 'Write to Model file'), array('write', 'W', InputOption::VALUE_NONE, 'Write to Model file'),
array('nowrite', 'N', InputOption::VALUE_NONE, 'Don\'t write to Model file'), array('nowrite', 'N', InputOption::VALUE_NONE, 'Don\'t write to Model file'),
array('reset', 'R', InputOption::VALUE_NONE, 'Remove the original phpdocs instead of appending'), array('reset', 'R', InputOption::VALUE_NONE, 'Remove the original phpdocs instead of appending'),
array('smart-reset', 'r', InputOption::VALUE_NONE, 'Refresh the properties/methods list, but keep the text'),
array('ignore', 'I', InputOption::VALUE_OPTIONAL, 'Which models to ignore', ''), array('ignore', 'I', InputOption::VALUE_OPTIONAL, 'Which models to ignore', ''),
); );
} }
@@ -145,6 +151,8 @@ class ModelsCommand extends Command
$output = "<?php $output = "<?php
// @formatter:off
/** /**
* A helper file for your Eloquent Models * A helper file for your Eloquent Models
* Copy the phpDocs from this file to the correct Model, * Copy the phpDocs from this file to the correct Model,
@@ -179,10 +187,9 @@ class ModelsCommand extends Command
if (class_exists($name)) { if (class_exists($name)) {
try { try {
// handle abstract classes, interfaces, ... // handle abstract classes, interfaces, ...
$reflectionClass = new \ReflectionClass($name); $reflectionClass = new ReflectionClass($name);
if (!$reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Model') if (!$reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Model')) {
|| $reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Relations\Pivot')) {
continue; continue;
} }
@@ -277,7 +284,7 @@ class ModelsCommand extends Command
break; break;
case 'date': case 'date':
case 'datetime': case 'datetime':
$realType = '\Carbon\Carbon'; $realType = '\Illuminate\Support\Carbon';
break; break;
case 'collection': case 'collection':
$realType = '\Illuminate\Support\Collection'; $realType = '\Illuminate\Support\Collection';
@@ -291,6 +298,10 @@ class ModelsCommand extends Command
continue; continue;
} else { } else {
$this->properties[$name]['type'] = $this->getTypeOverride($realType); $this->properties[$name]['type'] = $this->getTypeOverride($realType);
if (isset($this->nullableColumns[$name])) {
$this->properties[$name]['type'] .= '|null';
}
} }
} }
} }
@@ -337,7 +348,7 @@ class ModelsCommand extends Command
foreach ($columns as $column) { foreach ($columns as $column) {
$name = $column->getName(); $name = $column->getName();
if (in_array($name, $model->getDates())) { if (in_array($name, $model->getDates())) {
$type = '\Carbon\Carbon'; $type = '\Illuminate\Support\Carbon';
} else { } else {
$type = $column->getType()->getName(); $type = $column->getType()->getName();
switch ($type) { switch ($type) {
@@ -433,6 +444,9 @@ class ModelsCommand extends Command
array_shift($args); array_shift($args);
$this->setMethod($name, '\Illuminate\Database\Eloquent\Builder|\\' . $reflection->class, $args); $this->setMethod($name, '\Illuminate\Database\Eloquent\Builder|\\' . $reflection->class, $args);
} }
} elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])) {
$reflection = new \ReflectionClass($model);
$this->setMethod($method, '\Illuminate\Database\Eloquent\Builder|\\' . $reflection->getName());
} elseif (!method_exists('Illuminate\Database\Eloquent\Model', $method) } elseif (!method_exists('Illuminate\Database\Eloquent\Model', $method)
&& !Str::startsWith($method, 'get') && !Str::startsWith($method, 'get')
) { ) {
@@ -460,17 +474,30 @@ class ModelsCommand extends Command
'morphOne', 'morphOne',
'morphTo', 'morphTo',
'morphMany', 'morphMany',
'morphToMany' 'morphToMany',
'morphedByMany'
) as $relation) { ) as $relation) {
$search = '$this->' . $relation . '('; $search = '$this->' . $relation . '(';
if ($pos = stripos($code, $search)) { if ($pos = stripos($code, $search)) {
//Resolve the relation's model to a Relation object. //Resolve the relation's model to a Relation object.
$methodReflection = new \ReflectionMethod($model, $method);
if ($methodReflection->getNumberOfParameters()) {
return;
}
$relationObj = $model->$method(); $relationObj = $model->$method();
if ($relationObj instanceof Relation) { if ($relationObj instanceof Relation) {
$relatedModel = '\\' . get_class($relationObj->getRelated()); $relatedModel = '\\' . get_class($relationObj->getRelated());
$relations = ['hasManyThrough', 'belongsToMany', 'hasMany', 'morphMany', 'morphToMany']; $relations = [
'hasManyThrough',
'belongsToMany',
'hasMany',
'morphMany',
'morphToMany',
'morphedByMany',
];
if (in_array($relation, $relations)) { if (in_array($relation, $relations)) {
//Collection or array of models (because Collection is Arrayable) //Collection or array of models (because Collection is Arrayable)
$this->setProperty( $this->setProperty(
@@ -575,13 +602,19 @@ class ModelsCommand extends Command
protected function createPhpDocs($class) protected function createPhpDocs($class)
{ {
$reflection = new \ReflectionClass($class); $reflection = new ReflectionClass($class);
$namespace = $reflection->getNamespaceName(); $namespace = $reflection->getNamespaceName();
$classname = $reflection->getShortName(); $classname = $reflection->getShortName();
$originalDoc = $reflection->getDocComment(); $originalDoc = $reflection->getDocComment();
$keyword = $this->getClassKeyword($reflection);
if ($this->reset) { if ($this->reset) {
$phpdoc = new DocBlock('', new Context($namespace)); $phpdoc = new DocBlock('', new Context($namespace));
if ($this->keep_text) {
$phpdoc->setText(
(new DocBlock($reflection, new Context($namespace)))->getText()
);
}
} else { } else {
$phpdoc = new DocBlock($reflection, new Context($namespace)); $phpdoc = new DocBlock($reflection, new Context($namespace));
} }
@@ -661,7 +694,7 @@ class ModelsCommand extends Command
} }
} }
$output = "namespace {$namespace}{\n{$docComment}\n\tclass {$classname} extends \Eloquent {}\n}\n\n"; $output = "namespace {$namespace}{\n{$docComment}\n\t{$keyword}class {$classname} extends \Eloquent {}\n}\n\n";
return $output; return $output;
} }
@@ -764,4 +797,21 @@ class ModelsCommand extends Command
$this->setMethod('onlyTrashed', '\Illuminate\Database\Query\Builder|\\' . get_class($model), []); $this->setMethod('onlyTrashed', '\Illuminate\Database\Query\Builder|\\' . get_class($model), []);
} }
} }
/**
* @param ReflectionClass $reflection
* @return string
*/
private function getClassKeyword(ReflectionClass $reflection)
{
if ($reflection->isFinal()) {
$keyword = 'final ';
} elseif ($reflection->isAbstract()) {
$keyword = 'abstract ';
} else {
$keyword = '';
}
return $keyword;
}
} }
+12 -7
View File
@@ -209,14 +209,14 @@ class Generator
if (array_key_exists($name, $this->extra)) { if (array_key_exists($name, $this->extra)) {
$alias->addClass($this->extra[$name]); $alias->addClass($this->extra[$name]);
} }
$aliases[] = $alias; $aliases[] = $alias;
} }
} }
return $aliases; return $aliases;
} }
/** /**
* Regroup aliases by namespace of extended classes * Regroup aliases by namespace of extended classes
* *
@@ -228,7 +228,7 @@ class Generator
return $alias->getExtendsNamespace(); return $alias->getExtendsNamespace();
}); });
} }
/** /**
* Regroup aliases by namespace of alias * Regroup aliases by namespace of alias
* *
@@ -265,15 +265,20 @@ class Generator
'Schema' => 'Illuminate\Support\Facades\Schema', 'Schema' => 'Illuminate\Support\Facades\Schema',
'Session' => 'Illuminate\Support\Facades\Session', 'Session' => 'Illuminate\Support\Facades\Session',
'Storage' => 'Illuminate\Support\Facades\Storage', 'Storage' => 'Illuminate\Support\Facades\Storage',
//'Validator' => 'Illuminate\Support\Facades\Validator', 'Validator' => 'Illuminate\Support\Facades\Validator',
'Gate' => 'Illuminate\Support\Facades\Gate',
]; ];
$facades = array_merge($facades, $this->config->get('app.aliases', [])); $facades = array_merge($facades, $this->config->get('app.aliases', []));
// Only return the ones that actually exist // Only return the ones that actually exist
return array_filter($facades, function ($alias) { return array_filter(
return class_exists($alias); $facades,
}); function ($alias) {
return class_exists($alias);
},
ARRAY_FILTER_USE_KEY
);
} }
/** /**
+23 -24
View File
@@ -10,38 +10,37 @@ class Macro extends Method
/** /**
* Macro constructor. * Macro constructor.
* *
* @param \ReflectionFunction $method * @param \ReflectionFunctionAbstract $method
* @param string $alias * @param string $alias
* @param \ReflectionClass $class * @param \ReflectionClass $class
* @param null $methodName * @param null $methodName
* @param array $interfaces * @param array $interfaces
*/ */
public function __construct(\ReflectionFunction $method, $alias, $class, $methodName = null, $interfaces = array()) public function __construct(
$method,
$alias,
$class,
$methodName = null,
$interfaces = array()
) {
parent::__construct($method, $alias, $class, $methodName, $interfaces);
}
/**
* @param \ReflectionFunctionAbstract $method
*/
protected function initPhpDoc($method)
{ {
$this->method = $method;
$this->interfaces = $interfaces;
$this->name = $methodName ?: $method->name;
$this->namespace = $class->getNamespaceName();
//Create a DocBlock and serializer instance
$this->phpdoc = new DocBlock($method); $this->phpdoc = new DocBlock($method);
}
//Normalize the description and inherit the docs from parents/interfaces /**
try { * @param \ReflectionFunctionAbstract $method
$this->normalizeParams($this->phpdoc); * @param \ReflectionClass $class
$this->normalizeReturn($this->phpdoc); */
$this->normalizeDescription($this->phpdoc); protected function initClassDefinedProperties($method, \ReflectionClass $class)
} catch (\Exception $e) { {
} $this->namespace = $class->getNamespaceName();
//Get the parameters, including formatted default values
$this->getParameters($method);
//Make the method static
$this->phpdoc->appendTag(Tag::createInstance('@static', $this->phpdoc));
//Reference the 'real' function in the declaringclass
$this->declaringClassName = '\\' . ltrim($class->name, '\\'); $this->declaringClassName = '\\' . ltrim($class->name, '\\');
$this->root = '\\' . ltrim($class->getName(), '\\');
} }
} }
+37 -7
View File
@@ -26,29 +26,32 @@ class Method
protected $method; protected $method;
protected $output = ''; protected $output = '';
protected $declaringClassName;
protected $name; protected $name;
protected $namespace; protected $namespace;
protected $params = array(); protected $params = array();
protected $params_with_default = array(); protected $params_with_default = array();
protected $interfaces = array(); protected $interfaces = array();
protected $real_name;
protected $return = null; protected $return = null;
/** /**
* @param \ReflectionMethod $method * @param \ReflectionMethod|\ReflectionFunctionAbstract $method
* @param string $alias * @param string $alias
* @param \ReflectionClass $class * @param \ReflectionClass $class
* @param string|null $methodName * @param string|null $methodName
* @param array $interfaces * @param array $interfaces
*/ */
public function __construct(\ReflectionMethod $method, $alias, $class, $methodName = null, $interfaces = array()) public function __construct($method, $alias, $class, $methodName = null, $interfaces = array())
{ {
$this->method = $method; $this->method = $method;
$this->interfaces = $interfaces; $this->interfaces = $interfaces;
$this->name = $methodName ?: $method->name; $this->name = $methodName ?: $method->name;
$this->namespace = $method->getDeclaringClass()->getNamespaceName(); $this->real_name = $method->name;
$this->initClassDefinedProperties($method, $class);
//Create a DocBlock and serializer instance //Create a DocBlock and serializer instance
$this->phpdoc = new DocBlock($method, new Context($this->namespace)); $this->initPhpDoc($method);
//Normalize the description and inherit the docs from parents/interfaces //Normalize the description and inherit the docs from parents/interfaces
try { try {
@@ -64,12 +67,29 @@ class Method
//Make the method static //Make the method static
$this->phpdoc->appendTag(Tag::createInstance('@static', $this->phpdoc)); $this->phpdoc->appendTag(Tag::createInstance('@static', $this->phpdoc));
//Reference the 'real' function in the declaringclass //Reference the 'real' function in the declaring class
$declaringClass = $method->getDeclaringClass();
$this->declaringClassName = '\\' . ltrim($declaringClass->name, '\\');
$this->root = '\\' . ltrim($class->getName(), '\\'); $this->root = '\\' . ltrim($class->getName(), '\\');
} }
/**
* @param \ReflectionMethod $method
*/
protected function initPhpDoc($method)
{
$this->phpdoc = new DocBlock($method, new Context($this->namespace));
}
/**
* @param \ReflectionMethod $method
* @param \ReflectionClass $class
*/
protected function initClassDefinedProperties($method, \ReflectionClass $class)
{
$declaringClass = $method->getDeclaringClass();
$this->namespace = $declaringClass->getNamespaceName();
$this->declaringClassName = '\\' . ltrim($declaringClass->name, '\\');
}
/** /**
* Get the class wherein the function resides * Get the class wherein the function resides
* *
@@ -112,6 +132,16 @@ class Method
return $this->name; return $this->name;
} }
/**
* Get the real method name
*
* @return string
*/
public function getRealName()
{
return $this->real_name;
}
/** /**
* Get the parameters for this method * Get the parameters for this method
* *