Compare commits

...
28 Commits
Author SHA1 Message Date
Barry vd. Heuvel b91b959364 Create FUNDING.yml 2019-10-30 21:53:27 +01:00
naneri 9b0fbb4467 Added table of contents to Readme.md (#833) 2019-10-02 17:32:49 +02:00
Chris Morrell 6c8e847430 Add support for factory()->create() return types (#758)
* Revert "Forked release"

* Initial factory builder support

* Oops — fixed tabs

* Revert "Forked release"

* Whitespace

* Reverted more code

* Whitespace

* More whitespace

* Fixed PHPCS line
2019-10-01 20:18:19 +02:00
cxlblm 25b61c56fe __toString function has been DEPRECATED (#801)
* __toString function has been DEPRECATED

__toString function has been DEPRECATED as of PHP 7.1.0

* remove code

remove code
2019-09-17 07:08:26 +02:00
Alex 428d32cebd Add hasOneThrough to ide-helper:models (#807)
Added missing relation type.
2019-09-16 14:33:30 +02:00
Matthew Hailwood 51a72d7766 [PSR-12] Update param type array to use short array syntax (#828)
* Update Param type array to use short array syntax (PSR-12)

* Update Param type array to use short array syntax (PSR-12)
2019-09-16 11:52:59 +02:00
Patompong Savaengsuk d200f2284b Update readme.md (#825)
* Update readme.md

In version 2.6.5, this commit https://github.com/barryvdh/laravel-ide-helper/commit/f8a8cb18e0a42ae4131b7ed865fe792f9b34630c made it so library's consumer no longer need to pull in `doctrine/dbal` manually. I think we should mention that in the readme file as well. Although I'm not sure if it adds any value to the file itself or not.

* Remove note about doctrine/dbal from readme.md
2019-09-11 08:25:44 +02:00
Давид 8faae38655 Update readme.md (#824) 2019-09-10 15:46:31 +02:00
Barry vd. Heuvel 8740a9a158 Fix CS 2019-09-08 11:56:38 +02:00
liquid207 d344cdc842 Fix phpcs (#803) 2019-09-08 11:55:17 +02:00
Mandy Schoep 5e411ef104 Do not added instances of a anonymous class to the phpstorm_meta file (#806) 2019-09-08 11:46:25 +02:00
Barry vd. Heuvel 499a2113b3 Check if method exists 2019-09-08 11:45:23 +02:00
Barry vd. Heuvel f8a8cb18e0 Always require doctrine 2019-09-08 11:36:40 +02:00
Barry vd. Heuvel 16eb4f65ee Update readme.md 2019-09-03 19:51:13 +02:00
Kevin Bond 0edf8f750e remove monolog configuration (fixes #818) (#820) 2019-09-03 19:49:46 +02:00
Johan van Helden 1b15d2930b fix the identation in the config (#817) 2019-08-31 12:53:08 +02:00
Matthew Hailwood 3668e3821a Add support for custom cast classes (#816)
* Add support for custom cast classes

* Fix unrelated code style warning.
2019-08-30 07:32:01 +02:00
Barry vd. Heuvel 7b4cef1ea4 Update composer.json 2019-08-23 14:21:37 +02:00
Stanislas cd2a71d43c ModelsCommand: Remove question mark (#812)
Sorry this is a bit nitpicky 😅
2019-08-06 07:54:53 +02:00
edvordo c9132b28a6 Chages to x2Many relationships detection & adds relationship_count docBlock comment (#783)
* x to Many relationships are detected via a `Many` keyword in the relationship object class name
   * reason: example: `belongsTo` was incorrectly recognized as `belongsToMany`
 * adds `@property-read int|null $x2Many_relationship_method_name_count` model class docBlock comment
   * when model makes use of `withCount` or `loadCount` there is a property on the resource `$instance->relationship_method_count` that states the count of related models
   * can be `NULL` when `withCount` or `loadCount` aren't used
2019-06-18 16:38:42 +02:00
Guilherme Pressutto 8ab6e0536b Fixed meta not working with app()->makeWith() (#791) 2019-05-29 17:09:57 +02:00
Theodore R. Smith 87ebe458e9 Removed confusing README installation instructions (#786)
While installing this for my project, I didn't see the `--dev` instructions until I was literally editing this README for a pull request.

Since laravel-ide-helper is only designed for development purposes, let's just remove the superfluous entry altogether. Smart devs who for some crazy reason need it on prod will know to remove the `--dev`, while less knowledgeable devs won't shoot themselves in the foot accidentally.
2019-04-17 22:07:56 +02:00
leo108 9ef14f83be use Throwable instead of Exception (#779) 2019-03-27 05:56:31 +01:00
Brent Roose 39c148ad42 Support for custom builder classes (#782) 2019-03-26 11:38:22 +01:00
Francis Lavoie 2b3c9a2449 Fix BC introduced in #765 (#778)
See my comment https://github.com/barryvdh/laravel-ide-helper/pull/765#issuecomment-471014271:

The change in #765 made anonymous functions get reflected with `ReflectionMethod` instead of `ReflectionFunction`, which makes it lose the doc comment. This means that the generated helpers are missing their return types. This is because Closure is also an object and callable.

To fix it, Closure should be excluded from that new condition.
2019-03-12 11:38:49 +01:00
Matthew Brown 725711022b Make autoload exception more specific (#777)
This is a nice-to-have ([as I'm currently overriding it](https://github.com/psalm/laravel-psalm-plugin/commit/a700c89061d151d1c08851abd93d834f9183534d)), but might help other packages.
2019-03-05 10:24:51 +01:00
neoteknic 881f77156c Fix php 7.3 bug (#772) 2019-03-02 15:15:16 +01:00
neoteknic 0fad511954 Fix Bug PHP 7.3 & L5.8 (#774)
add cast (string) to disable bug ($type can be null)
2019-03-02 15:14:46 +01:00
12 changed files with 154 additions and 57 deletions
+12
View File
@@ -0,0 +1,12 @@
# These are supported funding model platforms
github: barryvdh
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+8 -11
View File
@@ -11,23 +11,20 @@
], ],
"require": { "require": {
"php": ">=7", "php": ">=7",
"illuminate/support": "^5.5,<5.9", "illuminate/support": "^5.5|^6",
"illuminate/console": "^5.5,<5.9", "illuminate/console": "^5.5|^6",
"illuminate/filesystem": "^5.5,<5.9", "illuminate/filesystem": "^5.5|^6",
"barryvdh/reflection-docblock": "^2.0.6", "barryvdh/reflection-docblock": "^2.0.6",
"composer/composer": "^1.6" "composer/composer": "^1.6",
"doctrine/dbal": "~2.3"
}, },
"require-dev": { "require-dev": {
"illuminate/config": "^5.1,<5.9", "illuminate/config": "^5.5|^6",
"illuminate/view": "^5.1,<5.9", "illuminate/view": "^5.5|^6",
"phpro/grumphp": "^0.14", "phpro/grumphp": "^0.14",
"phpunit/phpunit" : "4.*", "phpunit/phpunit" : "4.*",
"scrutinizer/ocular": "~1.1", "scrutinizer/ocular": "~1.1",
"squizlabs/php_codesniffer": "^3", "squizlabs/php_codesniffer": "^3"
"doctrine/dbal": "~2.3"
},
"suggest": {
"doctrine/dbal": "Load information from the database about models for phpdocs (~2.3)"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
+15 -14
View File
@@ -27,6 +27,18 @@ return array(
'include_fluent' => false, 'include_fluent' => false,
/*
|--------------------------------------------------------------------------
| Factory Builders
|--------------------------------------------------------------------------
|
| Set to true to generate factory generators for better factory()
| method auto-completion.
|
*/
'include_factory_builders' => false,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Write Model Magic methods | Write Model Magic methods
@@ -98,18 +110,7 @@ return array(
'Session' => array('Illuminate\Session\Store'), 'Session' => array('Illuminate\Session\Store'),
), ),
'magic' => array( 'magic' => array(),
'Log' => array(
'debug' => 'Monolog\Logger::addDebug',
'info' => 'Monolog\Logger::addInfo',
'notice' => 'Monolog\Logger::addNotice',
'warning' => 'Monolog\Logger::addWarning',
'error' => 'Monolog\Logger::addError',
'critical' => 'Monolog\Logger::addCritical',
'alert' => 'Monolog\Logger::addAlert',
'emergency' => 'Monolog\Logger::addEmergency',
)
),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@@ -189,10 +190,10 @@ return array(
| Cast the given "real type" to the given "type". | Cast the given "real type" to the given "type".
| |
*/ */
'type_overrides' => array( 'type_overrides' => array(
'integer' => 'int', 'integer' => 'int',
'boolean' => 'bool', 'boolean' => 'bool',
), ),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
+29 -17
View File
@@ -1,4 +1,4 @@
## Laravel 5 IDE Helper Generator ## Laravel IDE Helper Generator
[![Latest Version on Packagist][ico-version]][link-packagist] [![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md) [![Software License][ico-license]](LICENSE.md)
@@ -7,6 +7,19 @@
__For Laravel 4.x, check [version 1.11](https://github.com/barryvdh/laravel-ide-helper/tree/1.11)__ __For Laravel 4.x, check [version 1.11](https://github.com/barryvdh/laravel-ide-helper/tree/1.11)__
* [Complete phpDocs, directly from the source](#complete-phpdocs--directly-from-the-source)
* [Install](#install)
* [Automatic phpDoc generation for Laravel Facades](#automatic-phpdoc-generation-for-laravel-facades)
* [Automatic phpDocs for models](#automatic-phpdocs-for-models)
* [Automatic phpDocs generation for Laravel Fluent methods](#automatic-phpdocs-generation-for-laravel-fluent-methods)
* [Auto-completion for factory builders](#auto-completion-for-factory-builders)
- [PhpStorm Meta for Container instances](#phpstorm-meta-for-container-instances)
- [Lumen Install](#lumen-install)
+ [Enabling Facades](#enabling-facades)
+ [Adding the Service Provider](#adding-the-service-provider)
+ [Adding Additional Facades](#adding-additional-facades)
* [License](#license)
### Complete phpDocs, directly from the source ### Complete phpDocs, directly from the source
_Check out [this Laracasts video](https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15) for a quick introduction/explanation!_ _Check out [this Laracasts video](https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15) for a quick introduction/explanation!_
@@ -29,7 +42,7 @@ Note: You do need CodeComplice for Sublime Text: https://github.com/spectacles/C
Require this package with composer using the following command: Require this package with composer using the following command:
```bash ```bash
composer require barryvdh/laravel-ide-helper composer require --dev barryvdh/laravel-ide-helper
``` ```
After updating composer, add the service provider to the `providers` array in `config/app.php` After updating composer, add the service provider to the `providers` array in `config/app.php`
@@ -39,12 +52,6 @@ Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
``` ```
**Laravel 5.5** uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider. **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:
```bash
composer require --dev barryvdh/laravel-ide-helper
```
In Laravel, instead of adding the service provider in the `config/app.php` file, you can add the following code to your `app/Providers/AppServiceProvider.php` file, within the `register()` method: In Laravel, instead of adding the service provider in the `config/app.php` file, you can add the following code to your `app/Providers/AppServiceProvider.php` file, within the `register()` method:
```php ```php
@@ -75,8 +82,8 @@ You can configure your composer.json to do this after each commit:
"scripts":{ "scripts":{
"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"
] ]
}, },
``` ```
@@ -97,13 +104,6 @@ The `Illuminate/Support/helpers.php` is already set up, but you can add/remove y
### Automatic phpDocs for models ### Automatic phpDocs for models
> You need to add `doctrine/dbal: ~2.3` to require-dev in your own composer.json to get database columns.
```bash
composer require --dev doctrine/dbal
```
If you don't want to write your properties yourself, you can use the command `php artisan ide-helper:models` to generate If you don't want to write your properties yourself, you can use the command `php artisan ide-helper:models` to generate
phpDocs, based on table columns, relations and getters/setters. You can write the comments directly to your Model file, using the `--write (-W)` option. By default, you are asked to overwrite or write to a separate file (`_ide_helper_models.php`). You can force No with `--nowrite (-N)`. phpDocs, based on table columns, relations and getters/setters. You can write the comments directly to your Model file, using the `--write (-W)` option. By default, you are asked to overwrite or write to a separate file (`_ide_helper_models.php`). You can force No with `--nowrite (-N)`.
Please make sure to backup your models, before writing the info. Please make sure to backup your models, before writing the info.
@@ -169,6 +169,18 @@ After publishing vendor, simply change the `include_fluent` line your `config/id
And then run `php artisan ide-helper:generate` , you will now see all of the Fluent methods are recognized by your IDE. And then run `php artisan ide-helper:generate` , you will now see all of the Fluent methods are recognized by your IDE.
### Auto-completion for factory builders
If you would like the `factory()->create()` and `factory()->make()` methods to return the correct model class,
you can enable custom factory builders with the `include_factory_builders` line your `config/ide-helper.php` file.
```php
'include_factory_builders' => true,
```
For this to work, you must also publish the PhpStorm Meta file (see below).
## PhpStorm Meta for Container instances ## PhpStorm Meta for Container instances
It's possible to generate a PhpStorm meta file to [add support for factory design pattern](https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata). For Laravel, this means we can make PhpStorm understand what kind of object we are resolving from the IoC Container. For example, `events` will return an `Illuminate\Events\Dispatcher` object, so with the meta file you can call `app('events')` and it will autocomplete the Dispatcher methods. It's possible to generate a PhpStorm meta file to [add support for factory design pattern](https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata). For Laravel, this means we can make PhpStorm understand what kind of object we are resolving from the IoC Container. For example, `events` will return an `Illuminate\Events\Dispatcher` object, so with the meta file you can call `app('events')` and it will autocomplete the Dispatcher methods.
+10
View File
@@ -105,3 +105,13 @@ namespace Illuminate\Support {
class Fluent {} class Fluent {}
} }
<?php endif ?> <?php endif ?>
<?php foreach ($factories as $factory): ?>
namespace <?=$factory->getNamespaceName()?> {
/**
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> create($attributes = [])
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> make($attributes = [])
*/
class <?=$factory->getShortName()?>FactoryBuilder extends \Illuminate\Database\Eloquent\FactoryBuilder {}
}
<?php endforeach; ?>
+9
View File
@@ -20,6 +20,15 @@ namespace PHPSTORM_META {
])); ]));
<?php endforeach; ?> <?php endforeach; ?>
<?php if (count($factories)): ?>
override(\factory(0), map([
'' => '@FactoryBuilder',
<?php foreach($factories as $factory): ?>
'<?= $factory->getName() ?>' => \<?= $factory->getName() ?>FactoryBuilder::class,
<?php endforeach; ?>
]));
<?php endif; ?>
override(\Illuminate\Support\Arr::add(0), type(0)); override(\Illuminate\Support\Arr::add(0), type(0));
override(\Illuminate\Support\Arr::except(0), type(0)); override(\Illuminate\Support\Arr::except(0), type(0));
override(\Illuminate\Support\Arr::first(0), elementType(0)); override(\Illuminate\Support\Arr::first(0), elementType(0));
+3 -2
View File
@@ -10,6 +10,7 @@
namespace Barryvdh\LaravelIdeHelper; namespace Barryvdh\LaravelIdeHelper;
use Closure;
use ReflectionClass; use ReflectionClass;
use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context; use Barryvdh\Reflection\DocBlock\Context;
@@ -315,7 +316,7 @@ class Alias
{ {
foreach ($this->magicMethods as $magic => $real) { foreach ($this->magicMethods as $magic => $real) {
list($className, $name) = explode('::', $real); list($className, $name) = explode('::', $real);
if (!class_exists($className) && !interface_exists($className)) { if ((!class_exists($className) && !interface_exists($className)) || !method_exists($className, $name)) {
continue; continue;
} }
$method = new \ReflectionMethod($className, $name); $method = new \ReflectionMethod($className, $name);
@@ -395,7 +396,7 @@ class Alias
return new \ReflectionMethod($macro_func[0], $macro_func[1]); return new \ReflectionMethod($macro_func[0], $macro_func[1]);
} }
if (is_object($macro_func) && is_callable($macro_func)) { if (is_object($macro_func) && is_callable($macro_func) && !$macro_func instanceof Closure) {
return new \ReflectionMethod($macro_func, '__invoke'); return new \ReflectionMethod($macro_func, '__invoke');
} }
+10 -3
View File
@@ -10,6 +10,7 @@
namespace Barryvdh\LaravelIdeHelper\Console; namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Factories;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
@@ -47,6 +48,7 @@ class MetaCommand extends Command
protected $methods = [ protected $methods = [
'new \Illuminate\Contracts\Container\Container', 'new \Illuminate\Contracts\Container\Container',
'\Illuminate\Container\Container::makeWith(0)',
'\Illuminate\Contracts\Container\Container::make(0)', '\Illuminate\Contracts\Container\Container::make(0)',
'\Illuminate\Contracts\Container\Container::makeWith(0)', '\Illuminate\Contracts\Container\Container::makeWith(0)',
'\App::make(0)', '\App::make(0)',
@@ -76,6 +78,9 @@ class MetaCommand extends Command
*/ */
public function handle() public function handle()
{ {
// Needs to run before exception handler is registered
$factories = $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [];
$this->registerClassAutoloadExceptions(); $this->registerClassAutoloadExceptions();
$bindings = array(); $bindings = array();
@@ -87,10 +92,11 @@ class MetaCommand extends Command
try { try {
$concrete = $this->laravel->make($abstract); $concrete = $this->laravel->make($abstract);
if (is_object($concrete)) { $reflectionClass = new \ReflectionClass($concrete);
if (is_object($concrete) && !$reflectionClass->isAnonymous()) {
$bindings[$abstract] = get_class($concrete); $bindings[$abstract] = get_class($concrete);
} }
} catch (\Exception $e) { } catch (\Throwable $e) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->comment("Cannot make '$abstract': ".$e->getMessage()); $this->comment("Cannot make '$abstract': ".$e->getMessage());
} }
@@ -100,6 +106,7 @@ class MetaCommand extends Command
$content = $this->view->make('meta', [ $content = $this->view->make('meta', [
'bindings' => $bindings, 'bindings' => $bindings,
'methods' => $this->methods, 'methods' => $this->methods,
'factories' => $factories,
])->render(); ])->render();
$filename = $this->option('filename'); $filename = $this->option('filename');
@@ -135,7 +142,7 @@ class MetaCommand extends Command
protected function registerClassAutoloadExceptions() protected function registerClassAutoloadExceptions()
{ {
spl_autoload_register(function ($class) { spl_autoload_register(function ($class) {
throw new \Exception("Class '$class' not found."); throw new \ReflectionException("Class '$class' not found.");
}); });
} }
+26 -9
View File
@@ -96,7 +96,7 @@ class ModelsCommand extends Command
//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?" "Do you want to overwrite the existing model files? Choose no to write to $filename instead"
) )
) { ) {
$this->write = true; $this->write = true;
@@ -217,7 +217,7 @@ class ModelsCommand extends Command
$output .= $this->createPhpDocs($name); $output .= $this->createPhpDocs($name);
$ignore[] = $name; $ignore[] = $name;
$this->nullableColumns = []; $this->nullableColumns = [];
} catch (\Exception $e) { } catch (\Throwable $e) {
$this->error("Exception: " . $e->getMessage() . "\nCould not analyze class $name."); $this->error("Exception: " . $e->getMessage() . "\nCould not analyze class $name.");
} }
} }
@@ -290,7 +290,7 @@ class ModelsCommand extends Command
$realType = '\Illuminate\Support\Collection'; $realType = '\Illuminate\Support\Collection';
break; break;
default: default:
$realType = 'mixed'; $realType = class_exists($type) ? ('\\' . $type) : 'mixed';
break; break;
} }
@@ -446,15 +446,25 @@ class ModelsCommand extends Command
} }
} elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])) { } elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])) {
$reflection = new \ReflectionClass($model); $reflection = new \ReflectionClass($model);
$this->setMethod($method, '\Illuminate\Database\Eloquent\Builder|\\' . $reflection->getName());
$builder = get_class($model->newModelQuery());
$this->setMethod($method, "\\{$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')
) { ) {
//Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php //Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php
$reflection = new \ReflectionMethod($model, $method); $reflection = new \ReflectionMethod($model, $method);
// php 7.x type or fallback to docblock
$type = (string) $reflection->getReturnType() ?: $this->getReturnTypeFromDocBlock($reflection);
if ($returnType = $reflection->getReturnType()) {
$type = $returnType instanceof \ReflectionNamedType
? $returnType->getName()
: (string)$returnType;
} else {
// php 7.x type or fallback to docblock
$type = (string)$this->getReturnTypeFromDocBlock($reflection);
}
$file = new \SplFileObject($reflection->getFileName()); $file = new \SplFileObject($reflection->getFileName());
$file->seek($reflection->getStartLine() - 1); $file->seek($reflection->getStartLine() - 1);
@@ -470,6 +480,7 @@ class ModelsCommand extends Command
foreach (array( foreach (array(
'hasMany' => '\Illuminate\Database\Eloquent\Relations\HasMany', 'hasMany' => '\Illuminate\Database\Eloquent\Relations\HasMany',
'hasManyThrough' => '\Illuminate\Database\Eloquent\Relations\HasManyThrough', 'hasManyThrough' => '\Illuminate\Database\Eloquent\Relations\HasManyThrough',
'hasOneThrough' => '\Illuminate\Database\Eloquent\Relations\HasOneThrough',
'belongsToMany' => '\Illuminate\Database\Eloquent\Relations\BelongsToMany', 'belongsToMany' => '\Illuminate\Database\Eloquent\Relations\BelongsToMany',
'hasOne' => '\Illuminate\Database\Eloquent\Relations\HasOne', 'hasOne' => '\Illuminate\Database\Eloquent\Relations\HasOne',
'belongsTo' => '\Illuminate\Database\Eloquent\Relations\BelongsTo', 'belongsTo' => '\Illuminate\Database\Eloquent\Relations\BelongsTo',
@@ -480,7 +491,7 @@ class ModelsCommand extends Command
'morphedByMany' => '\Illuminate\Database\Eloquent\Relations\MorphToMany' 'morphedByMany' => '\Illuminate\Database\Eloquent\Relations\MorphToMany'
) as $relation => $impl) { ) as $relation => $impl) {
$search = '$this->' . $relation . '('; $search = '$this->' . $relation . '(';
if (stripos($code, $search) || stripos($impl, $type) !== false) { if (stripos($code, $search) || stripos($impl, (string)$type) !== false) {
//Resolve the relation's model to a Relation object. //Resolve the relation's model to a Relation object.
$methodReflection = new \ReflectionMethod($model, $method); $methodReflection = new \ReflectionMethod($model, $method);
if ($methodReflection->getNumberOfParameters()) { if ($methodReflection->getNumberOfParameters()) {
@@ -500,7 +511,7 @@ class ModelsCommand extends Command
'morphToMany', 'morphToMany',
'morphedByMany', 'morphedByMany',
]; ];
if (in_array($relation, $relations)) { if (strpos(get_class($relationObj), 'Many') !== false) {
//Collection or array of models (because Collection is Arrayable) //Collection or array of models (because Collection is Arrayable)
$this->setProperty( $this->setProperty(
$method, $method,
@@ -508,6 +519,12 @@ class ModelsCommand extends Command
true, true,
null null
); );
$this->setProperty(
Str::snake($method) . '_count',
'int|null',
true,
false
);
} elseif ($relation === "morphTo") { } elseif ($relation === "morphTo") {
// Model isn't specified because relation is polymorphic // Model isn't specified because relation is polymorphic
$this->setProperty( $this->setProperty(
@@ -721,7 +738,7 @@ class ModelsCommand extends Command
if (is_bool($default)) { if (is_bool($default)) {
$default = $default ? 'true' : 'false'; $default = $default ? 'true' : 'false';
} elseif (is_array($default)) { } elseif (is_array($default)) {
$default = 'array()'; $default = '[]';
} elseif (is_null($default)) { } elseif (is_null($default)) {
$default = 'null'; $default = 'null';
} elseif (is_int($default)) { } elseif (is_int($default)) {
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Barryvdh\LaravelIdeHelper;
use Exception;
use Illuminate\Database\Eloquent\Factory;
use ReflectionClass;
class Factories
{
public static function all()
{
$factories = [];
$factory = app(Factory::class);
$definitions = (new ReflectionClass(Factory::class))->getProperty('definitions');
$definitions->setAccessible(true);
foreach ($definitions->getValue($factory) as $factory_target => $config) {
try {
$factories[] = new ReflectionClass($factory_target);
} catch (Exception $exception) {
}
}
return $factories;
}
}
+1
View File
@@ -86,6 +86,7 @@ class Generator
->with('helpers', $this->helpers) ->with('helpers', $this->helpers)
->with('version', $app->version()) ->with('version', $app->version())
->with('include_fluent', $this->config->get('ide-helper.include_fluent', true)) ->with('include_fluent', $this->config->get('ide-helper.include_fluent', true))
->with('factories', $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [])
->render(); ->render();
} }
+1 -1
View File
@@ -321,7 +321,7 @@ class Method
if (is_bool($default)) { if (is_bool($default)) {
$default = $default ? 'true' : 'false'; $default = $default ? 'true' : 'false';
} elseif (is_array($default)) { } elseif (is_array($default)) {
$default = 'array()'; $default = '[]';
} elseif (is_null($default)) { } elseif (is_null($default)) {
$default = 'null'; $default = 'null';
} elseif (is_int($default)) { } elseif (is_int($default)) {