Compare commits

..
17 changed files with 293 additions and 465 deletions
-59
View File
@@ -1,61 +1,5 @@
# Changelog # Changelog
## v3.5.1 - 2025-01-06
### What's Changed
* Remove duplicate config, fix ->can() by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1650
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.5.0...v3.5.1
## v3.5.0 - 2025-01-06
### What's Changed
* Add phpstorm meta argument hints by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1640
* Add meta override for user return types by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1642
* Use forked ContextFactory by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1643
* Remove php parser by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1644
* Also add eloquent template tags from base class by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1645
* Add more metadata by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1646
* Fixed generating PHPDoc for methods with class templates by @chack1172 in https://github.com/barryvdh/laravel-ide-helper/pull/1647
* Feat guess macro types by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1648
* Allow adding custom Macroable classes. by @mathieutu in https://github.com/barryvdh/laravel-ide-helper/pull/1629
* Add special `dev` to composer keywords by @jnoordsij in https://github.com/barryvdh/laravel-ide-helper/pull/1649
### New Contributors
* @chack1172 made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1647
* @mathieutu made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1629
* @jnoordsij made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1649
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.4.0...v3.5.0
## v3.4.0 - 2024-12-29
### What's Changed
* fix: add @template TModel of static for Eloquent by @imzyf in https://github.com/barryvdh/laravel-ide-helper/pull/1631
* Add templates to Eloquent by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1634
* Update testsuite for Generator, simplify service provider and mock by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1635
* Add option for only eloquent by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1636
* Add weak generics for array type objects by @LauJosefsen in https://github.com/barryvdh/laravel-ide-helper/pull/1621
* Make all "note" in README apply quote style by @hms5232 in https://github.com/barryvdh/laravel-ide-helper/pull/1590
* Update README.md by @Mtillmann in https://github.com/barryvdh/laravel-ide-helper/pull/1587
* Rename view var by @barryvdh and @pb30 in https://github.com/barryvdh/laravel-ide-helper/pull/1637 and https://github.com/barryvdh/laravel-ide-helper/pull/1563
* Format IDE helper by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1638
* Add TLDR section, update options by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1639
### New Contributors
* @imzyf made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1631
* @LauJosefsen made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1621
* @hms5232 made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1590
* @Mtillmann made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1587
* @pb30 made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1563
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.3.0...v3.4.0
## v3.3.0 - 2024-12-18 ## v3.3.0 - 2024-12-18
### What's Changed ### What's Changed
@@ -110,14 +54,11 @@
- Fix type of hashed model property to `string` - Fix type of hashed model property to `string`
### Changed ### Changed
- Update view "version" variable name to avoid potential conflicts - Update view "version" variable name to avoid potential conflicts
- Add support for EloquentBuilder generics introduced in Laravel 11.15. - Add support for EloquentBuilder generics introduced in Laravel 11.15.
- Drop support for Laravel versions earlier than 11.15. - Drop support for Laravel versions earlier than 11.15.
### Added ### Added
- Introduce `enforce_nullable_relationships` configuration option to control how nullable Eloquent relationships are enforced during static analysis. This provides flexibility for scenarios where application logic ensures data integrity without relying on database constraints. [#1580 / jeramyhing](https://github.com/barryvdh/laravel-ide-helper/pull/1580) - Introduce `enforce_nullable_relationships` configuration option to control how nullable Eloquent relationships are enforced during static analysis. This provides flexibility for scenarios where application logic ensures data integrity without relying on database constraints. [#1580 / jeramyhing](https://github.com/barryvdh/laravel-ide-helper/pull/1580)
-2
View File
@@ -115,8 +115,6 @@ Str::macro('concat', function(string $str1, string $str2) : string {
}); });
``` ```
You can add any custom Macroable traits to detect in the `macroable_traits` config option.
### Automatic PHPDocs for models ### Automatic PHPDocs for models
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
+7 -7
View File
@@ -11,8 +11,7 @@
"netbeans", "netbeans",
"sublime", "sublime",
"codeintel", "codeintel",
"phpdoc", "phpdoc"
"dev"
], ],
"authors": [ "authors": [
{ {
@@ -23,12 +22,14 @@
"require": { "require": {
"php": "^8.2", "php": "^8.2",
"ext-json": "*", "ext-json": "*",
"barryvdh/reflection-docblock": "^2.3", "barryvdh/reflection-docblock": "^2.2",
"composer/class-map-generator": "^1.0", "composer/class-map-generator": "^1.0",
"illuminate/console": "^11.15", "illuminate/console": "^11.15",
"illuminate/database": "^11.15", "illuminate/database": "^11.15",
"illuminate/filesystem": "^11.15", "illuminate/filesystem": "^11.15",
"illuminate/support": "^11.15" "illuminate/support": "^11.15",
"nikic/php-parser": "^4.18 || ^5",
"phpdocumentor/type-resolver": "^1.1.0"
}, },
"require-dev": { "require-dev": {
"ext-pdo_sqlite": "*", "ext-pdo_sqlite": "*",
@@ -39,8 +40,7 @@
"orchestra/testbench": "^9.2", "orchestra/testbench": "^9.2",
"phpunit/phpunit": "^10.5", "phpunit/phpunit": "^10.5",
"spatie/phpunit-snapshot-assertions": "^4 || ^5", "spatie/phpunit-snapshot-assertions": "^4 || ^5",
"vimeo/psalm": "^5.4", "vimeo/psalm": "^5.4"
"vlucas/phpdotenv": "^5"
}, },
"suggest": { "suggest": {
"illuminate/events": "Required for automatic helper generation (^6|^7|^8|^9|^10|^11)." "illuminate/events": "Required for automatic helper generation (^6|^7|^8|^9|^10|^11)."
@@ -65,7 +65,7 @@
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "3.5-dev" "dev-master": "3.4-dev"
}, },
"laravel": { "laravel": {
"providers": [ "providers": [
-14
View File
@@ -334,18 +334,4 @@ return [
// 'ide-helper:models --nowrite', // 'ide-helper:models --nowrite',
], ],
/*
|--------------------------------------------------------------------------
| Macroable Traits
|--------------------------------------------------------------------------
|
| Define which traits should be considered capable of adding Macro.
| You can add any custom trait that behaves like the original Laravel one.
|
*/
'macroable_traits' => [
Filament\Support\Concerns\Macroable::class,
Spatie\Macroable\Macroable::class,
],
]; ];
-43
View File
@@ -1,43 +0,0 @@
<?php
return collect(Illuminate\Support\Facades\Gate::abilities())
->map(function ($policy, $key) {
$reflection = new ReflectionFunction($policy);
$policyClass = null;
$closureThis = $reflection->getClosureThis();
if ($closureThis && get_class($closureThis) === Illuminate\Auth\Access\Gate::class) {
$vars = $reflection->getClosureUsedVariables();
if (isset($vars['callback'])) {
[$policyClass, $method] = explode('@', $vars['callback']);
$reflection = new ReflectionMethod($policyClass, $method);
}
}
return [
'key' => $key,
'uri' => $reflection->getFileName(),
'policy_class' => $policyClass,
'lineNumber' => $reflection->getStartLine(),
];
})
->merge(
collect(Illuminate\Support\Facades\Gate::policies())->flatMap(function ($policy, $model) {
$methods = (new ReflectionClass($policy))->getMethods();
return collect($methods)->map(function (ReflectionMethod $method) use ($policy) {
return [
'key' => $method->getName(),
'uri' => $method->getFileName(),
'policy_class' => $policy,
'lineNumber' => $method->getStartLine(),
];
})->filter(function ($ability) {
return !in_array($ability['key'], ['allow', 'deny']);
});
}),
)
->values()
->groupBy('key');
-64
View File
@@ -1,64 +0,0 @@
<?php
return collect(app("Illuminate\Contracts\Http\Kernel")->getMiddlewareGroups())
->merge(app("Illuminate\Contracts\Http\Kernel")->getRouteMiddleware())
->map(function ($middleware, $key) {
$result = [
'class' => null,
'uri' => null,
'startLine' => null,
'parameters' => null,
'groups' => [],
];
if (is_array($middleware)) {
$result['groups'] = collect($middleware)->map(function ($m) {
if (!class_exists($m)) {
return [
'class' => $m,
'uri' => null,
'startLine' => null,
];
}
$reflected = new ReflectionClass($m);
$reflectedMethod = $reflected->getMethod('handle');
return [
'class' => $m,
'uri' => $reflected->getFileName(),
'startLine' =>
$reflectedMethod->getFileName() === $reflected->getFileName()
? $reflectedMethod->getStartLine()
: null,
];
})->all();
return $result;
}
$reflected = new ReflectionClass($middleware);
$reflectedMethod = $reflected->getMethod('handle');
$result = array_merge($result, [
'class' => $middleware,
'uri' => $reflected->getFileName(),
'startLine' => $reflectedMethod->getStartLine(),
]);
$parameters = collect($reflectedMethod->getParameters())
->filter(function ($rc) {
return $rc->getName() !== 'request' && $rc->getName() !== 'next';
})
->map(function ($rc) {
return $rc->getName() . ($rc->isVariadic() ? '...' : '');
});
if ($parameters->isEmpty()) {
return $result;
}
return array_merge($result, [
'parameters' => $parameters->implode(','),
]);
});
+2 -19
View File
@@ -21,12 +21,6 @@ namespace PHPSTORM_META {
])); ]));
<?php endforeach; ?> <?php endforeach; ?>
<?php foreach ($userMethods as $method) : ?>
override(<?= $method ?>, map([
'' => \<?= $userModel ?>::class,
]));
<?php endforeach; ?>
<?php foreach ($configMethods as $method) : ?> <?php foreach ($configMethods as $method) : ?>
override(<?= $method ?>, map([ override(<?= $method ?>, map([
<?php foreach ($configValues as $name => $value) : ?> <?php foreach ($configValues as $name => $value) : ?>
@@ -88,19 +82,8 @@ namespace PHPSTORM_META {
<?php endif ?> <?php endif ?>
<?php if (isset($expectedArguments)) : ?> <?php if (isset($expectedArguments)) : ?>
<?php foreach ($expectedArguments as $arguments) : ?> <?php foreach ($expectedArguments as $function => $arguments) : ?>
<?php <?php foreach ($arguments as $index => $argumentSet) : ?>
$classes = isset($arguments['class']) ? (array) $arguments['class'] : [null];
$index = $arguments['index'] ?? 0;
$argumentSet = $arguments['argumentSet'];
$functions = [];
foreach ($classes as $class) {
foreach ((array) $arguments['method'] as $method) {
$functions[] = '\\' . ($class ? ltrim($class, '\\') . '::' : '') . $method . '()';
}
}
?>
<?php foreach ($functions as $function) : ?>
expectedArguments(<?= $function ?>, <?= $index ?>, argumentsSet('<?= $argumentSet ?>')); expectedArguments(<?= $function ?>, <?= $index ?>, argumentsSet('<?= $argumentSet ?>'));
<?php endforeach; ?> <?php endforeach; ?>
<?php endforeach; ?> <?php endforeach; ?>
+12 -53
View File
@@ -13,10 +13,8 @@ namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context; use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\ContextFactory;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag\MethodTag; use Barryvdh\Reflection\DocBlock\Tag\MethodTag;
use Barryvdh\Reflection\DocBlock\Tag\TemplateTag;
use Closure; use Closure;
use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
@@ -46,14 +44,9 @@ class Alias
protected $phpdoc = null; protected $phpdoc = null;
protected $classAliases = []; protected $classAliases = [];
protected $isMacroable = false;
/** @var ConfigRepository */ /** @var ConfigRepository */
protected $config; protected $config;
/** @var string[] */
protected $templateNames;
/** /**
* @param ConfigRepository $config * @param ConfigRepository $config
* @param string $alias * @param string $alias
@@ -62,13 +55,12 @@ class Alias
* @param array $magicMethods * @param array $magicMethods
* @param array $interfaces * @param array $interfaces
*/ */
public function __construct($config, $alias, $facade, $magicMethods = [], $interfaces = [], $isMacroable = false) public function __construct($config, $alias, $facade, $magicMethods = [], $interfaces = [])
{ {
$this->alias = $alias; $this->alias = $alias;
$this->magicMethods = $magicMethods; $this->magicMethods = $magicMethods;
$this->interfaces = $interfaces; $this->interfaces = $interfaces;
$this->config = $config; $this->config = $config;
$this->isMacroable = $isMacroable;
// Make the class absolute // Make the class absolute
$facade = '\\' . ltrim($facade, '\\'); $facade = '\\' . ltrim($facade, '\\');
@@ -90,7 +82,7 @@ class Alias
if (!empty($this->namespace)) { if (!empty($this->namespace)) {
try { try {
$this->classAliases = (new ContextFactory())->createFromReflector(new ReflectionClass($this->root))->getNamespaceAliases(); $this->classAliases = (new UsesResolver())->loadFromClass($this->root);
} catch (Throwable $e) { } catch (Throwable $e) {
$this->classAliases = []; $this->classAliases = [];
} }
@@ -354,8 +346,7 @@ class Alias
$magic, $magic,
$this->interfaces, $this->interfaces,
$this->classAliases, $this->classAliases,
$this->getReturnTypeNormalizers($class), $this->getReturnTypeNormalizers($class)
$this->getTemplateNames()
); );
} }
$this->usedMethods[] = $magic; $this->usedMethods[] = $magic;
@@ -387,8 +378,7 @@ class Alias
$method->name, $method->name,
$this->interfaces, $this->interfaces,
$this->classAliases, $this->classAliases,
$this->getReturnTypeNormalizers($reflection), $this->getReturnTypeNormalizers($reflection)
$this->getTemplateNames(),
); );
} }
$this->usedMethods[] = $method->name; $this->usedMethods[] = $method->name;
@@ -398,7 +388,8 @@ class Alias
// Check if the class is macroable // Check if the class is macroable
// (Eloquent\Builder is also macroable but doesn't use Macroable trait) // (Eloquent\Builder is also macroable but doesn't use Macroable trait)
if ($this->isMacroable || $class === EloquentBuilder::class) { $traits = collect($reflection->getTraitNames());
if ($traits->contains('Illuminate\Support\Traits\Macroable') || $class === EloquentBuilder::class) {
$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) {
@@ -485,62 +476,30 @@ class Alias
/** /**
* @param $prefix * @param $prefix
* @return string * @return string
* @throws \ReflectionException
*/ */
public function getPhpDocTemplates($prefix = "\t\t") public function getPhpDocTemplates($prefix = "\t\t")
{ {
$templateDoc = new DocBlock(''); $templateDoc = new DocBlock('');
$serializer = new DocBlockSerializer(1, $prefix); $serializer = new DocBlockSerializer(1, $prefix);
foreach ($this->getTemplateNames() as $templateName) {
$template = new TemplateTag('template', $templateName);
$template->setBound('static');
$template->setDocBlock($templateDoc);
$templateDoc->appendTag($template);
}
return $serializer->getDocComment($templateDoc);
}
/**
* @return string[]
*/
public function getTemplateNames()
{
if (!isset($this->templateNames)) {
$this->detectTemplateNames();
}
return $this->templateNames;
}
/**
* @return void
* @throws \ReflectionException
*/
protected function detectTemplateNames()
{
$templateNames = [];
foreach ($this->classes as $class) { foreach ($this->classes as $class) {
$reflection = new ReflectionClass($class); $reflection = new ReflectionClass($class);
$traits = collect($reflection->getTraitNames()); $traits = collect($reflection->getTraitNames());
$phpdoc = new DocBlock($reflection);
$templates = $phpdoc->getTagsByName('template');
/** @var TemplateTag $template */
foreach ($templates as $template) {
$templateNames[] = $template->getTemplateName();
}
foreach ($traits as $trait) { foreach ($traits as $trait) {
$phpdoc = new DocBlock(new ReflectionClass($trait)); $phpdoc = new DocBlock(new ReflectionClass($trait));
$templates = $phpdoc->getTagsByName('template'); $templates = $phpdoc->getTagsByName('template');
/** @var TemplateTag $template */ /** @var DocBlock\Tag\TemplateTag $template */
foreach ($templates as $template) { foreach ($templates as $template) {
$templateNames[] = $template->getTemplateName(); $template->setBound('static');
$template->setDocBlock($templateDoc);
$templateDoc->appendTag($template);
} }
} }
} }
$this->templateNames = $templateNames; return $serializer->getDocComment($templateDoc);
} }
/** /**
+32 -113
View File
@@ -12,8 +12,6 @@
namespace Barryvdh\LaravelIdeHelper\Console; namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Factories; use Barryvdh\LaravelIdeHelper\Factories;
use Dotenv\Parser\Entry;
use Dotenv\Parser\Parser;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
@@ -70,16 +68,9 @@ class MetaCommand extends Command
protected $configMethods = [ protected $configMethods = [
'\config()', '\config()',
'\Illuminate\Config\Repository::get()', '\Illuminate\Config\Repository::get()',
'\Illuminate\Config\Repository::set()',
'\Illuminate\Support\Facades\Config::get()', '\Illuminate\Support\Facades\Config::get()',
]; '\Illuminate\Support\Facades\Config::set()',
protected $userMethods = [
'\auth()->user()',
'\Illuminate\Contracts\Auth\Guard::user()',
'\Illuminate\Support\Facades\Auth::user()',
'\request()->user()',
'\Illuminate\Http\Request::user()',
'\Illuminate\Support\Facades\Request::user()',
]; ];
protected $templateCache = []; protected $templateCache = [];
@@ -144,8 +135,6 @@ class MetaCommand extends Command
return gettype($value); return gettype($value);
}); });
$defaultUserModel = $this->config->get('auth.providers.users.model', $this->config->get('auth.model', 'App\User'));
$content = $this->view->make('ide-helper::meta', [ $content = $this->view->make('ide-helper::meta', [
'bindings' => $bindings, 'bindings' => $bindings,
'methods' => $this->methods, 'methods' => $this->methods,
@@ -154,8 +143,6 @@ class MetaCommand extends Command
'configValues' => $configValues, 'configValues' => $configValues,
'expectedArgumentSets' => $this->getExpectedArgumentSets(), 'expectedArgumentSets' => $this->getExpectedArgumentSets(),
'expectedArguments' => $this->getExpectedArguments(), 'expectedArguments' => $this->getExpectedArguments(),
'userModel' => $defaultUserModel,
'userMethods' => $this->userMethods,
])->render(); ])->render();
$filename = $this->option('filename'); $filename = $this->option('filename');
@@ -202,106 +189,59 @@ class MetaCommand extends Command
protected function getExpectedArgumentSets() protected function getExpectedArgumentSets()
{ {
return [ return [
'auth' => $this->loadTemplate('auth')->keys()->filter()->toArray(),
'configs' => $this->loadTemplate('configs')->pluck('name')->filter()->toArray(), 'configs' => $this->loadTemplate('configs')->pluck('name')->filter()->toArray(),
'middleware' => $this->loadTemplate('middleware')->keys()->filter()->toArray(),
'routes' => $this->loadTemplate('routes')->pluck('name')->filter()->toArray(), 'routes' => $this->loadTemplate('routes')->pluck('name')->filter()->toArray(),
'views' => $this->loadTemplate('views')->pluck('key')->filter()->map(function ($value) { 'views' => $this->loadTemplate('views')->pluck('key')->filter()->map(function ($value) {
return (string) $value; return (string) $value;
})->toArray(), })->toArray(),
'translations' => $this->loadTemplate('translations')->filter()->keys()->toArray(), 'translations' => $this->loadTemplate('translations')->filter()->keys()->toArray(),
'env' => $this->getEnv(),
]; ];
} }
protected function getExpectedArguments() protected function getExpectedArguments()
{ {
return [ return [
[ '\config()' => [
'class' => '\Illuminate\Support\Facades\Gate', 0 => 'configs',
'method' => [
'has',
'allows',
'denies',
'check',
'any',
'none',
'authorize',
'inspect',
],
'argumentSet' => 'auth',
], ],
[ '\Illuminate\Config\Repository::get()' => [
'class' => ['\Illuminate\Support\Facades\Route', '\Illuminate\Support\Facades\Auth', 'Illuminate\Foundation\Auth\Access\Authorizable'], 0 => 'configs',
'method' => ['can', 'cannot', 'cant'],
'argumentSet' => 'auth',
], ],
[ '\Illuminate\Config\Repository::set()' => [
'class' => ['Illuminate\Contracts\Auth\Access\Authorizable'], 0 => 'configs',
'method' => ['can'],
'argumentSet' => 'auth',
], ],
[ '\Illuminate\Support\Facades\Config::get()' => [
'class' => ['\Illuminate\Config\Repository', '\Illuminate\Support\Facades\Config'], 0 => 'configs',
'method' => [
// 'get', // config() and Config::Get() are added with return type hints already
'getMany',
'set',
'string',
'integer',
'boolean',
'float',
'array',
'prepend',
'push',
],
'argumentSet' => 'configs',
], ],
[ '\Illuminate\Support\Facades\Config::set()' => [
'class' => ['\Illuminate\Support\Facades\Route', '\Illuminate\Routing\Router'], 0 => 'configs',
'method' => ['middleware', 'withoutMiddleware'],
'argumentSet' => 'middleware',
], ],
[ '\route()' => [
'method' => ['route', 'to_route', 'signedRoute'], 0 => 'routes',
'argumentSet' => 'routes',
], ],
[ '\Illuminate\Support\Facades\Route::get()' => [
'class' => [ 0 => 'routes',
'\Illuminate\Support\Facades\Redirect',
'\Illuminate\Support\Facades\URL',
'\Illuminate\Routing\Redirector',
'\Illuminate\Routing\UrlGenerator',
],
'method' => ['route', 'signedRoute', 'temporarySignedRoute'],
'argumentSet' => 'routes',
], ],
[ '\Illuminate\Routing\Router::get()' => [
'method' => 'view', 0 => 'routes',
'argumentSet' => 'views',
], ],
[ '\view()' => [
'class' => ['\Illuminate\Support\Facades\View', '\Illuminate\View\Factory'], 0 => 'views',
'method' => 'make',
'argumentSet' => 'views',
], ],
[ '\Illuminate\Support\Facades\View::make()' => [
'method' => ['__', 'trans'], 0 => 'views',
'argumentSet' => 'translations',
], ],
[ '\Illuminate\View\Factory::make()' => [
'class' => ['\Illuminate\Contracts\Translation\Translator'], 0 => 'views',
'method' => ['get'],
'argumentSet' => 'translations',
], ],
[ '\__()' => [
'method' => 'env', 0 => 'translations',
'argumentSet' => 'env',
], ],
[ '\trans()' => [
'class' => '\Illuminate\Support\Env', 0 => 'translations',
'method' => 'get', ],
'argumentSet' => 'env', '\Illuminate\Contracts\Translation\Translator::get()' => [
0 => 'translations',
], ],
]; ];
} }
@@ -313,13 +253,7 @@ class MetaCommand extends Command
{ {
if (!isset($this->templateCache[$name])) { if (!isset($this->templateCache[$name])) {
$file = __DIR__ . '/../../php-templates/' . basename($name) . '.php'; $file = __DIR__ . '/../../php-templates/' . basename($name) . '.php';
try { $value = $this->files->requireOnce($file) ?: [];
$value = $this->files->requireOnce($file) ?: [];
} catch (\Throwable $e) {
$value = [];
$this->warn('Cannot load template for ' . $name . ': ' . $e->getMessage());
}
if (!$value instanceof Collection) { if (!$value instanceof Collection) {
$value = collect($value); $value = collect($value);
} }
@@ -343,21 +277,6 @@ class MetaCommand extends Command
]; ];
} }
protected function getEnv()
{
$envPath = base_path('.env');
if (!file_exists($envPath)) {
return [];
}
$parser = new Parser();
$entries = $parser->parse(file_get_contents($envPath));
return collect($entries)->map(function (Entry $entry) {
return $entry->getName();
});
}
/** /**
* Remove our custom autoloader that we pushed onto the autoload stack * Remove our custom autoloader that we pushed onto the autoload stack
* *
+2 -4
View File
@@ -16,7 +16,6 @@ use Barryvdh\LaravelIdeHelper\Generator;
use Barryvdh\LaravelIdeHelper\Parsers\PhpDocReturnTypeParser; use Barryvdh\LaravelIdeHelper\Parsers\PhpDocReturnTypeParser;
use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context; use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\ContextFactory;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag; use Barryvdh\Reflection\DocBlock\Tag;
use Composer\ClassMapGenerator\ClassMapGenerator; use Composer\ClassMapGenerator\ClassMapGenerator;
@@ -50,6 +49,7 @@ use Illuminate\Support\Arr;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\View\Factory as ViewFactory; use Illuminate\View\Factory as ViewFactory;
use phpDocumentor\Reflection\Types\ContextFactory;
use ReflectionClass; use ReflectionClass;
use ReflectionNamedType; use ReflectionNamedType;
use ReflectionObject; use ReflectionObject;
@@ -1571,9 +1571,7 @@ class ModelsCommand extends Command
*/ */
protected function getUsedClassNames(ReflectionClass $reflection): array protected function getUsedClassNames(ReflectionClass $reflection): array
{ {
$namespaceAliases = array_flip(array_map(function ($alias) { $namespaceAliases = array_flip((new ContextFactory())->createFromReflector($reflection)->getNamespaceAliases());
return ltrim($alias, '\\');
}, (new ContextFactory())->createFromReflector($reflection)->getNamespaceAliases()));
$namespaceAliases[$reflection->getName()] = $reflection->getShortName(); $namespaceAliases[$reflection->getName()] = $reflection->getShortName();
return $namespaceAliases; return $namespaceAliases;
+27 -27
View File
@@ -17,6 +17,10 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\Macroable;
use PhpParser\Lexer\Emulative;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Parser\Php7;
use ReflectionClass; use ReflectionClass;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
@@ -35,7 +39,6 @@ class Generator
protected $magic = []; protected $magic = [];
protected $interfaces = []; protected $interfaces = [];
protected $helpers; protected $helpers;
protected array $macroableTraits = [];
/** /**
* @param \Illuminate\Config\Repository $config * @param \Illuminate\Config\Repository $config
@@ -210,10 +213,8 @@ class Generator
foreach ($realTimeFacadeFiles as $file) { foreach ($realTimeFacadeFiles as $file) {
try { try {
$name = $this->getFullyQualifiedClassNameInFile($file); $name = $this->getFullyQualifiedClassNameInFile($file);
if ($name) { $facades[$name] = $name;
$facades[$name] = $name; } catch (\Exception $e) {
}
} catch (\Throwable $e) {
continue; continue;
} }
} }
@@ -225,17 +226,26 @@ class Generator
{ {
$contents = file_get_contents($path); $contents = file_get_contents($path);
// Match namespace $parsers = new Php7(new Emulative());
preg_match('/namespace\s+([^;]+);/', $contents, $namespaceMatch);
$namespace = isset($namespaceMatch[1]) ? $namespaceMatch[1] : '';
// Match class name $parsed = collect($parsers->parse($contents) ?: []);
preg_match('/class\s+([a-zA-Z0-9_]+)/', $contents, $classMatch);
$className = isset($classMatch[1]) ? $classMatch[1] : '';
// Combine namespace and class name $namespace = $parsed->first(function ($node) {
if ($namespace && $className) { return $node instanceof Namespace_;
return $namespace . '\\' . $className; });
if ($namespace) {
$name = $namespace->name->toString();
$class = collect($namespace->stmts)->first(function ($node) {
return $node instanceof Class_;
});
if ($class) {
$name .= '\\' . $class->name->toString();
}
return $name;
} }
} }
@@ -342,7 +352,7 @@ class Generator
continue; continue;
} }
$aliases[] = new Alias($this->config, $class, $class, [], $this->interfaces, true); $aliases[] = new Alias($this->config, $class, $class, [], $this->interfaces);
} }
} }
@@ -364,18 +374,8 @@ class Generator
->filter(function ($class) { ->filter(function ($class) {
$traits = class_uses_recursive($class); $traits = class_uses_recursive($class);
if (isset($traits[Macroable::class])) { // Filter only classes with the macroable trait
return true; return isset($traits[Macroable::class]);
}
// Filter only classes with a macroable trait
foreach ($this->config->get('ide-helper.macroable_traits', []) as $trait) {
if (isset($traits[$trait])) {
return true;
}
}
return false;
}) })
->filter(function ($class) use ($aliases) { ->filter(function ($class) use ($aliases) {
$class = Str::start($class, '\\'); $class = Str::start($class, '\\');
-11
View File
@@ -5,15 +5,10 @@ namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Tag; use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
class Macro extends Method class Macro extends Method
{ {
protected $macroDefaults = [
\Illuminate\Http\Client\Factory::class => PendingRequest::class,
];
/** /**
* Macro constructor. * Macro constructor.
* *
@@ -82,12 +77,6 @@ class Macro extends Method
$this->phpdoc->appendTag(Tag::createInstance("@return {$type}")); $this->phpdoc->appendTag(Tag::createInstance("@return {$type}"));
} }
$class = ltrim($this->declaringClassName, '\\');
if (!$this->phpdoc->hasTag('return') && isset($this->macroDefaults[$class])) {
$type = $this->macroDefaults[$class];
$this->phpdoc->appendTag(Tag::createInstance("@return {$type}"));
}
} }
protected function concatReflectionTypes(?\ReflectionType $type): string protected function concatReflectionTypes(?\ReflectionType $type): string
+3 -8
View File
@@ -39,9 +39,6 @@ class Method
protected $classAliases; protected $classAliases;
protected $returnTypeNormalizers; protected $returnTypeNormalizers;
/** @var string[] */
protected $templateNames = [];
/** /**
* @param \ReflectionMethod|\ReflectionFunctionAbstract $method * @param \ReflectionMethod|\ReflectionFunctionAbstract $method
* @param string $alias * @param string $alias
@@ -50,9 +47,8 @@ class Method
* @param array $interfaces * @param array $interfaces
* @param array $classAliases * @param array $classAliases
* @param array $returnTypeNormalizers * @param array $returnTypeNormalizers
* @param string[] $templateNames
*/ */
public function __construct($method, $alias, $class, $methodName = null, $interfaces = [], array $classAliases = [], array $returnTypeNormalizers = [], array $templateNames = []) public function __construct($method, $alias, $class, $methodName = null, $interfaces = [], array $classAliases = [], array $returnTypeNormalizers = [])
{ {
$this->method = $method; $this->method = $method;
$this->interfaces = $interfaces; $this->interfaces = $interfaces;
@@ -60,7 +56,6 @@ class Method
$this->returnTypeNormalizers = $returnTypeNormalizers; $this->returnTypeNormalizers = $returnTypeNormalizers;
$this->name = $methodName ?: $method->name; $this->name = $methodName ?: $method->name;
$this->real_name = $method->isClosure() ? $this->name : $method->name; $this->real_name = $method->isClosure() ? $this->name : $method->name;
$this->templateNames = $templateNames;
$this->initClassDefinedProperties($method, $class); $this->initClassDefinedProperties($method, $class);
//Reference the 'real' function in the declaring class //Reference the 'real' function in the declaring class
@@ -89,7 +84,7 @@ class Method
*/ */
protected function initPhpDoc($method) protected function initPhpDoc($method)
{ {
$this->phpdoc = new DocBlock($method, new Context($this->namespace, $this->classAliases, generics: $this->templateNames)); $this->phpdoc = new DocBlock($method, new Context($this->namespace, $this->classAliases));
} }
/** /**
@@ -391,7 +386,7 @@ class Method
} }
if ($method) { if ($method) {
$namespace = $method->getDeclaringClass()->getNamespaceName(); $namespace = $method->getDeclaringClass()->getNamespaceName();
$phpdoc = new DocBlock($method, new Context($namespace, $this->classAliases, generics: $this->templateNames)); $phpdoc = new DocBlock($method, new Context($namespace, $this->classAliases));
if (strpos($phpdoc->getText(), '{@inheritdoc}') !== false) { if (strpos($phpdoc->getText(), '{@inheritdoc}') !== false) {
//Not at the end yet, try another parent/interface.. //Not at the end yet, try another parent/interface..
+124
View File
@@ -0,0 +1,124 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\Node\Stmt\UseUse;
use PhpParser\ParserFactory;
class UsesResolver
{
/**
* @param string $classFQN
* @return array
*/
public function loadFromClass(string $classFQN): array
{
return $this->loadFromFile(
$classFQN,
(new \ReflectionClass($classFQN))->getFileName()
);
}
/**
* @param string $classFQN
* @param string $filename
* @return array
*/
public function loadFromFile(string $classFQN, string $filename): array
{
return $this->loadFromCode(
$classFQN,
file_get_contents(
$filename
)
);
}
/**
* @param string $classFQN
* @param string $code
* @return array
*/
public function loadFromCode(string $classFQN, string $code): array
{
$classFQN = ltrim($classFQN, '\\');
$namespace = rtrim(
preg_replace(
'/([^\\\\]+)$/',
'',
$classFQN
),
'\\'
);
$parser = (new ParserFactory())->createForHostVersion();
$namespaceData = null;
foreach ($parser->parse($code) as $node) {
if ($node instanceof Namespace_ && $node->name->toCodeString() === $namespace) {
$namespaceData = $node;
break;
}
}
if ($namespaceData === null) {
return [];
}
/** @var Namespace_ $namespaceData */
$aliases = [];
foreach ($namespaceData->stmts as $stmt) {
if ($stmt instanceof Use_) {
if ($stmt->type !== Use_::TYPE_NORMAL) {
continue;
}
foreach ($stmt->uses as $use) {
/** @var UseUse $use */
$alias = $use->alias ?
$use->alias->name :
self::classBasename($use->name->toCodeString());
$aliases[$alias] = '\\' . $use->name->toCodeString();
}
} elseif ($stmt instanceof GroupUse) {
foreach ($stmt->uses as $use) {
/** @var UseUse $use */
$alias = $use->alias ?
$use->alias->name :
self::classBasename($use->name->toCodeString());
$aliases[$alias] = '\\' . $stmt->prefix->toCodeString() . '\\' . $use->name->toCodeString();
}
}
}
return $aliases;
}
/**
* @param string $classFQN
* @return string
*/
protected static function classBasename(string $classFQN): string
{
return preg_replace('/^.*\\\\([^\\\\]+)$/', '$1', $classFQN);
}
}
+27 -17
View File
@@ -7,6 +7,7 @@ namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\Alias; use Barryvdh\LaravelIdeHelper\Alias;
use Barryvdh\LaravelIdeHelper\Macro; use Barryvdh\LaravelIdeHelper\Macro;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
/** /**
@@ -15,6 +16,31 @@ use Illuminate\Support\Arr;
*/ */
class AliasTest extends TestCase class AliasTest extends TestCase
{ {
/**
* @covers ::detectMethods
*/
public function testDetectMethodsMacroableMacros(): void
{
// Mock
$macro = __FUNCTION__;
$alias = new AliasMock();
// Macros
Builder::macro(
$macro,
function () {
// empty
}
);
// Prepare
$alias->setClasses([Builder::class]);
$alias->detectMethods();
// Test
$this->assertNotNull($this->getAliasMacro($alias, Builder::class, $macro));
}
/** /**
* @covers ::detectMethods * @covers ::detectMethods
*/ */
@@ -24,7 +50,7 @@ class AliasTest extends TestCase
$macro = __FUNCTION__; $macro = __FUNCTION__;
$alias = new AliasMock(); $alias = new AliasMock();
// Macrosx // Macros
EloquentBuilder::macro( EloquentBuilder::macro(
$macro, $macro,
function () { function () {
@@ -40,21 +66,6 @@ class AliasTest extends TestCase
$this->assertNotNull($this->getAliasMacro($alias, EloquentBuilder::class, $macro)); $this->assertNotNull($this->getAliasMacro($alias, EloquentBuilder::class, $macro));
} }
/**
* @covers ::detectTemplateNames
*/
public function testTemplateNamesAreDetected(): void
{
// Mock
$alias = new AliasMock();
// Prepare
$alias->setClasses([EloquentBuilder::class]);
// Test
$this->assertSame(['TModel', 'TValue'], $alias->getTemplateNames());
}
protected function getAliasMacro(Alias $alias, string $class, string $method): ?Macro protected function getAliasMacro(Alias $alias, string $class, string $method): ?Macro
{ {
return Arr::first( return Arr::first(
@@ -71,7 +82,6 @@ class AliasTest extends TestCase
/** /**
* @internal * @internal
* @noinspection PhpMultipleClassesDeclarationsInOneFile * @noinspection PhpMultipleClassesDeclarationsInOneFile
* @template TValue
*/ */
class AliasMock extends Alias class AliasMock extends Alias
{ {
-23
View File
@@ -193,29 +193,6 @@ DOC;
$this->assertSame([], $method->getParamsWithDefault(false)); $this->assertSame([], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn()); $this->assertTrue($method->shouldReturn());
} }
public function testEloquentBuilderWithTemplates()
{
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('firstOr');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], [], ['TModel']);
$output = <<<'DOC'
/**
* Execute the query and get the first result or call a callback.
*
* @template TValue
* @param (\Closure(): TValue)|list<string> $columns
* @param (\Closure(): TValue)|null $callback
* @return TModel|TValue
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('firstOr', $method->getName());
$this->assertSame('\\' . EloquentBuilder::class, $method->getDeclaringClass());
}
} }
class ExampleClass class ExampleClass
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\UsesResolver;
use PHPUnit\Framework\TestCase;
class UsesResolverTest extends TestCase
{
/**
* Test that we can correctly load uses from supplied code
*/
public function testLoadFromCode()
{
$usesResolver = new UsesResolver();
$code = <<<'DOC'
<?php
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\UsesResolver as MyUsesResolver;
use PHPUnit\Framework\TestCase;
class UsesResolverTest extends TestCase
{
//
}
DOC;
$this->assertEquals(
$usesResolver->loadFromCode('Barryvdh\\LaravelIdeHelper\\Tests\\UsesResolverTest', $code),
[
'MyUsesResolver' => '\\Barryvdh\\LaravelIdeHelper\\UsesResolver',
'TestCase' => '\\PHPUnit\Framework\TestCase',
]
);
}
/**
* Test that we can correctly load uses from a class
*/
public function testLoadFromClass()
{
$usesResolver = new UsesResolver();
$this->assertEquals(
$usesResolver->loadFromClass(self::class),
[
'UsesResolver' => '\\Barryvdh\\LaravelIdeHelper\\UsesResolver',
'TestCase' => '\\PHPUnit\Framework\TestCase',
]
);
}
}