Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add More stubs: lang_path, Eloquent\Builder::chunk, Database\Connection::transaction #305

Merged
merged 6 commits into from
Jan 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.4.0@62db5d4f6a7ae0a20f7cc5a4952d730272fc0863">
<file src="src/Handlers/Eloquent/RelationsMethodHandler.php">
<ArgumentTypeCoercion occurrences="1">
<code>$template_type_parameters</code>
</ArgumentTypeCoercion>
</file>
<file src="src/Providers/ModelStubProvider.php">
<PossiblyUndefinedMethod occurrences="1">
<code>databasePath</code>
</PossiblyUndefinedMethod>
<files psalm-version="5.6.0@e784128902dfe01d489c4123d69918a9f3c1eac5">
<file src="src/Handlers/Helpers/PathHandler.php">
<InvalidArgument>
<code>[$argument]</code>
</InvalidArgument>
<MixedAssignment>
<code>$argument</code>
</MixedAssignment>
</file>
</files>
5 changes: 2 additions & 3 deletions psalm.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<?xml version="1.0"?>
<psalm
errorLevel="2"
reportMixedIssues="false"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config config.xsd"
errorLevel="1"
errorBaseline="psalm-baseline.xml"
phpVersion="8.0"
>
Expand Down
7 changes: 5 additions & 2 deletions src/Fakes/FakeModelsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ public function getModels(): array
$models = [];

// Bypass an issue https://github.com/barryvdh/laravel-ide-helper/issues/1414
foreach ($this->loadModels() as $probably_model_fqcn) {
if (is_string($probably_model_fqcn) && is_a($probably_model_fqcn, Model::class, true)) {
/** @var list<class-string> $classlike_fq_names */
$classlike_fq_names = $this->loadModels();
foreach ($classlike_fq_names as $probably_model_fqcn) {
if (is_a($probably_model_fqcn, Model::class, true)) {
$models[] = $probably_model_fqcn;
}
}
Expand Down Expand Up @@ -112,6 +114,7 @@ public function getPropertiesFromTable($model): void
}

if ($column->nullable) {
/** @psalm-suppress MixedArrayAssignment */
$this->nullableColumns[$name] = true;
}

Expand Down
7 changes: 7 additions & 0 deletions src/Handlers/Application/ContainerHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
use function in_array;
use function is_object;
use function strtolower;
use function is_string;
use function is_callable;

final class ContainerHandler implements AfterClassLikeVisitInterface, FunctionReturnTypeProviderInterface, MethodReturnTypeProviderInterface
{
Expand Down Expand Up @@ -86,6 +88,11 @@ public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event)

foreach ($bindings as $abstract) {
try {
if (!is_string($abstract) && !is_callable($abstract)) {
continue;
}

/** @psalm-suppress MixedArgument */
$concrete = ApplicationProvider::getApp()->make($abstract);

if (!is_object($concrete)) {
Expand Down
4 changes: 1 addition & 3 deletions src/Handlers/Application/OffsetHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ final class OffsetHandler implements
MethodVisibilityProviderInterface,
MethodParamsProviderInterface
{
/**
* @return array<class-string>
*/
/** @return list<class-string> */
public static function getClassLikeNames(): array
{
return ApplicationInterfaceProvider::getApplicationInterfaceClassLikes();
Expand Down
5 changes: 3 additions & 2 deletions src/Handlers/Eloquent/Schema/SchemaAggregator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use function is_string;
use function strtolower;
use function in_array;
use function is_array;

class SchemaAggregator
{
Expand Down Expand Up @@ -73,15 +74,15 @@ private function addClassStatements(array $stmts): void
if (
$stmt instanceof PhpParser\Node\Stmt\ClassMethod
&& $stmt->name->name === 'up'
&& $stmt->stmts
&& is_array($stmt->stmts)
) {
$this->addUpMethodStatements($stmt->stmts);
}
}
}

/**
* @param array<int, PhpParser\Node\Stmt> $stmts
* @param array<array-key, \PhpParser\Node\Stmt> $stmts
*/
private function addUpMethodStatements(array $stmts): void
{
Expand Down
11 changes: 7 additions & 4 deletions src/Handlers/Eloquent/Schema/SchemaColumn.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,21 @@ class SchemaColumn
/** @var bool */
public $nullable;

/** @var ?array<int, string> */
public $options;
/** @var array<int, string> */
public $options = [];

/**
* @param array<int, string>|null $options
*/
public function __construct(
string $name,
string $type,
bool $nullable = false,
?array $options = null
?array $options = []
) {
$this->name = $name;
$this->type = $type;
$this->nullable = $nullable;
$this->options = $options;
$this->options = $options ?: [];
}
}
33 changes: 30 additions & 3 deletions src/Handlers/Helpers/PathHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,22 @@

final class PathHandler implements FunctionReturnTypeProviderInterface, MethodReturnTypeProviderInterface
{
/**
* @inheritDoc
* @see https://laravel.com/docs/master/helpers#paths
*/
public static function getFunctionIds(): array
{
return ['app_path', 'base_path', 'config_path', 'database_path', 'resource_path', 'public_path', 'storage_path'];
return [
'app_path',
'base_path',
'config_path',
'database_path',
'lang_path',
'resource_path',
'public_path',
'storage_path',
];
}

public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $event): ?Union
Expand All @@ -43,9 +56,19 @@ public static function getClassLikeNames(): array
];
}

/** @inheritDoc */
public static function getMethodReturnType(MethodReturnTypeProviderEvent $event): ?Union
{
$methods = ['path', 'basepath', 'configpath', 'databasepath', 'resourcepath'];
$methods = [
'path',
'basepath',
'configpath',
'databasepath',
'langpath',
'resourcepath',
'publicpath',
'storagepath',
];

$method_name_lowercase = $event->getMethodNameLowercase();

Expand All @@ -56,11 +79,15 @@ public static function getMethodReturnType(MethodReturnTypeProviderEvent $event)
/**
* @psalm-suppress MissingClosureReturnType
*/
return self::resolveReturnType($event->getCallArgs(), function (array $args = []) use ($method_name_lowercase) {
return self::resolveReturnType($event->getCallArgs(), static function (array $args = []) use ($method_name_lowercase) {
return ApplicationProvider::getApp()->{$method_name_lowercase}(...$args);
});
}

/**
* @param list<\PhpParser\Node\Arg> $call_args
* @param \Closure(array<array-key, \PhpParser\Node\Arg>=): mixed $closure
*/
private static function resolveReturnType(array $call_args, Closure $closure): ?Union
{
// we're going to do some dynamic analysis here. Were going to invoke the closure that is wrapping the
Expand Down
3 changes: 3 additions & 0 deletions src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,17 @@ public function __invoke(RegistrationInterface $registration, ?SimpleXMLElement
$this->registerStubs($registration);
}

/** @return array<array-key, string> */
protected function getCommonStubs(): array
{
return array_merge(
glob(dirname(__DIR__) . '/stubs/Contracts/*.stubphp'),
glob(dirname(__DIR__) . '/stubs/Database/*.stubphp'),
glob(dirname(__DIR__) . '/stubs/*.stubphp')
);
}

/** @return array<array-key, string> */
protected function getStubsForVersion(string $version): array
{
[$majorVersion] = explode('.', $version);
Expand Down
1 change: 1 addition & 0 deletions src/Providers/ApplicationInterfaceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

final class ApplicationInterfaceProvider
{
/** @return list<class-string> */
public static function getApplicationInterfaceClassLikes(): array
{
return [
Expand Down
32 changes: 26 additions & 6 deletions src/Providers/ApplicationProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public static function bootApp(): void
$app = self::getApp();

if ($app instanceof Application) {
$app->make(Kernel::class)->bootstrap();
/** @var \Illuminate\Contracts\Console\Kernel $consoleApp */
$consoleApp = $app->make(Kernel::class);
$consoleApp->bootstrap();
} else {
$app->boot();
}
Expand All @@ -44,9 +46,17 @@ public static function getApp(): LaravelApplication | LumenApplication
}

if (file_exists($applicationPath = __DIR__ . '/../../../../bootstrap/app.php')) { // plugin installed to vendor
/** @psalm-suppress MixedAssignment */
$app = require $applicationPath;
if (! $app instanceof LaravelApplication && ! $app instanceof LumenApplication) {
throw new \RuntimeException('Could not instantiate Application: unknown path.');
}
} elseif (file_exists($applicationPath = getcwd() . '/bootstrap/app.php')) { // Local Dev
/** @psalm-suppress MixedAssignment */
$app = require $applicationPath;
if (! $app instanceof LaravelApplication && ! $app instanceof LumenApplication) {
throw new \RuntimeException('Could not instantiate Application: unknown path.');
}
} else { // Packages
$app = (new self())->createApplication();
}
Expand Down Expand Up @@ -77,28 +87,36 @@ protected function resolveApplicationBootstrappers($app)
// we want to keep the default psalm exception handler, otherwise the Laravel one will always return exit codes
// of 0
//$app->make('Illuminate\Foundation\Bootstrap\HandleExceptions')->bootstrap($app);
/** @psalm-suppress MixedMethodCall */
$app->make('Illuminate\Foundation\Bootstrap\RegisterFacades')->bootstrap($app);
/** @psalm-suppress MixedMethodCall */
$app->make('Illuminate\Foundation\Bootstrap\SetRequestForConsole')->bootstrap($app);
/** @psalm-suppress MixedMethodCall */
$app->make('Illuminate\Foundation\Bootstrap\RegisterProviders')->bootstrap($app);

$this->getEnvironmentSetUp($app);

/** @psalm-suppress MixedMethodCall */
$app->make('Illuminate\Foundation\Bootstrap\BootProviders')->bootstrap($app);

foreach ($this->getPackageBootstrappers($app) as $bootstrap) {
/** @psalm-suppress MixedMethodCall */
$app->make($bootstrap)->bootstrap($app);
}

/** @psalm-suppress MixedMethodCall */
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

$app['router']->getRoutes()->refreshNameLookups();
/** @var \Illuminate\Routing\Router $router */
$router = $app['router'];
$router->getRoutes()->refreshNameLookups();

/**
* @psalm-suppress MissingClosureParamType
* @psalm-suppress UnusedClosureParam
*/
$app->resolving('url', static function ($url, $app) {
$app['router']->getRoutes()->refreshNameLookups();
$app->resolving('url', static function ($url, $app) use ($router) {
$router->getRoutes()->refreshNameLookups();
});
}

Expand All @@ -107,12 +125,14 @@ protected function resolveApplicationBootstrappers($app)
*/
protected function getEnvironmentSetUp($app): void
{
$app['config']->set('app.key', 'AckfSECXIvnK5r28GVIWUAxmbBSjTsmF');
/** @var \Illuminate\Config\Repository $config */
$config = $app['config'];
$config->set('app.key', 'AckfSECXIvnK5r28GVIWUAxmbBSjTsmF');

// in testing, we want ide-helper to load our test models. Unfortunately this has to be a relative path, with
// the base path being inside of orchestra/testbench-core/laravel

$app['config']->set('ide-helper.model_locations', [
$config->set('ide-helper.model_locations', [
'../../../../tests/Models',
]);
}
Expand Down
11 changes: 6 additions & 5 deletions src/Providers/FacadeStubProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Symfony\Component\Console\Output\NullOutput;

use function unlink;
use function is_array;

final class FacadeStubProvider implements GeneratesStubs
{
Expand All @@ -21,11 +22,11 @@ public static function generateStubFile(): void

// The \Eloquent mixin has less specific return types than our custom plugin can determine, so we unset it here
// to not taint our analysis
if ($ideHelperExtra = $config->get('ide-helper.extra')) {
if (isset($ideHelperExtra['Eloquent'])) {
unset($ideHelperExtra['Eloquent']);
$config->set('ide-helper.extra', $ideHelperExtra);
}
/** @var mixed $ideHelperExtra */
$ideHelperExtra = $config->get('ide-helper.extra');
if (is_array($ideHelperExtra) && isset($ideHelperExtra['Eloquent'])) {
unset($ideHelperExtra['Eloquent']);
$config->set('ide-helper.extra', $ideHelperExtra);
}

$fake_filesystem = new FakeFilesystem();
Expand Down
1 change: 1 addition & 0 deletions src/Providers/ModelStubProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public static function generateStubFile(): void
throw new \RuntimeException('Unsupported Application type.');
}

/** @var string $migrations_directory */
$migrations_directory = $app->databasePath('migrations/');

$project_analyzer = ProjectAnalyzer::getInstance();
Expand Down
1 change: 1 addition & 0 deletions src/Util/ContainerResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ private static function resolveFromApplicationContainer(string $abstract): ?stri

// dynamic analysis to resolve the actual type from the container
try {
/** @var mixed $concrete */
$concrete = ApplicationProvider::getApp()->make($abstract);
} catch (\Throwable $e) {
return null;
Expand Down
19 changes: 19 additions & 0 deletions stubs/Database/ManagesTransactions.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Illuminate\Database\Concerns;

trait ManagesTransactions
{
/**
* Execute a Closure within a transaction.
*
* @template TCallbackReturnType
*
* @param \Closure($this): TCallbackReturnType $callback
* @param positive-int $attempts
* @return TCallbackReturnType
*
* @throws \Throwable
*/
public function transaction(\Closure $callback, $attempts = 1) {}
}
7 changes: 7 additions & 0 deletions stubs/EloquentBuilder.stubphp
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ class Builder
*/
public function whereRelation($relation, $column, $operator = null, $value = null) {}

/**
* @param positive-int $count
* @param callable(\Illuminate\Database\Eloquent\Collection<int, TModel>, int): mixed $callback
* @return bool
*/
public function chunk($count, $callback) {}

/**
* @param string $relation
* @param \Closure|string|array<int, string>|\Illuminate\Database\Query\Expression $column
Expand Down
2 changes: 2 additions & 0 deletions tests/acceptance/AbortIf.feature
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Feature: abort_if()
return $nullable;
}
"""
When I run Psalm
Then I see no errors

Scenario: abort_if asserts not null
Given I have the following code
Expand Down
Loading