Skip to content

Console commands #45

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

Merged
merged 6 commits into from
Apr 16, 2019
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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ This extension provides following features:
* Provides correct return type for `ContainerInterface::get()` and `::has()` methods.
* Provides correct return type for `Controller::get()` and `::has()` methods.
* Provides correct return type for `Request::getContent()` method based on the `$asResource` parameter.
* Provides correct return type for `HeaderBag::get()` method based on the `$first` parameter.
* Provides correct return type for `Envelope::all()` method based on the `$stampFqcn` parameter.
* Notifies you when you try to get an unregistered service from the container.
* Notifies you when you try to get a private service from the container.
* Optionally correct return types for `InputInterface::getArgument()`, `::getOption`, `::hasArgument`, and `::hasOption`.

## Usage

Expand Down Expand Up @@ -55,3 +58,21 @@ parameters:
```

Be aware that it may hide genuine errors in your application.

## Console command analysis

You can opt in for more advanced analysis by providing the console application from your own application. This will allow the correct argument and option types to be inferred when accessing $input->getArgument() or $input->getOption().

```
parameters:
symfony:
console_application_loader: tests/console-application.php
```

For example, in a Symfony project, `console-application.php` would look something like this:

```php
require dirname(__DIR__).'/../config/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
return new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
```
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@
"phpstan/phpstan-phpunit": "^0.11",
"symfony/framework-bundle": "^3.0 || ^4.0",
"squizlabs/php_codesniffer": "^3.3.2",
"symfony/serializer": "^3|^4",
"symfony/messenger": "^4.2"
"symfony/serializer": "^3.0 || ^4.0",
"symfony/messenger": "^4.2",
"symfony/console": "^3.0 || ^4.0"
},
"conflict": {
"symfony/framework-bundle": "<3.0"
Expand Down
41 changes: 41 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
parameters:
symfony:
container_xml_path: null
constant_hassers: true
console_application_loader: null

rules:
- PHPStan\Rules\Symfony\ContainerInterfacePrivateServiceRule
- PHPStan\Rules\Symfony\ContainerInterfaceUnknownServiceRule
- PHPStan\Rules\Symfony\UndefinedArgumentRule
- PHPStan\Rules\Symfony\InvalidArgumentDefaultValueRule
- PHPStan\Rules\Symfony\UndefinedOptionRule
- PHPStan\Rules\Symfony\InvalidOptionDefaultValueRule

services:
# console resolver
-
factory: PHPStan\Symfony\ConsoleApplicationResolver
arguments: [%symfony.console_application_loader%]

# service map
symfony.serviceMapFactory:
class: PHPStan\Symfony\ServiceMapFactory
Expand Down Expand Up @@ -55,3 +66,33 @@ services:
-
factory: PHPStan\Type\Symfony\EnvelopeReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]

# InputInterface::getArgument() return type
-
factory: PHPStan\Type\Symfony\InputInterfaceGetArgumentDynamicReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]

# InputInterface::hasArgument() type specification
-
factory: PHPStan\Type\Symfony\ArgumentTypeSpecifyingExtension
tags: [phpstan.typeSpecifier.methodTypeSpecifyingExtension]

# InputInterface::hasArgument() return type
-
factory: PHPStan\Type\Symfony\InputInterfaceHasArgumentDynamicReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]

# InputInterface::getOption() return type
-
factory: PHPStan\Type\Symfony\InputInterfaceGetOptionDynamicReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]

# InputInterface::hasOption() type specification
-
factory: PHPStan\Type\Symfony\OptionTypeSpecifyingExtension
tags: [phpstan.typeSpecifier.methodTypeSpecifyingExtension]

# InputInterface::hasOption() return type
-
factory: PHPStan\Type\Symfony\InputInterfaceHasOptionDynamicReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
2 changes: 2 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ parameters:
excludes_analyse:
- */tests/tmp/*
- */tests/*/Example*.php
- */tests/*/console_application_loader.php
- */tests/*/envelope_all.php
- */tests/*/header_bag_get.php
- */tests/*/request_get_content.php
- */tests/*/serializer.php
2 changes: 1 addition & 1 deletion src/Rules/Symfony/ContainerInterfacePrivateServiceRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$serviceId = ServiceMap::getServiceIdFromNode($node->args[0]->value, $scope);
$serviceId = $this->serviceMap::getServiceIdFromNode($node->args[0]->value, $scope);
if ($serviceId !== null) {
$service = $this->serviceMap->getService($serviceId);
if ($service !== null && !$service->isPublic()) {
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Symfony/ContainerInterfaceUnknownServiceRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$serviceId = ServiceMap::getServiceIdFromNode($node->args[0]->value, $scope);
$serviceId = $this->serviceMap::getServiceIdFromNode($node->args[0]->value, $scope);
if ($serviceId !== null) {
$service = $this->serviceMap->getService($serviceId);
$serviceIdType = $scope->getType($node->args[0]->value);
Expand Down
78 changes: 78 additions & 0 deletions src/Rules/Symfony/InvalidArgumentDefaultValueRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
use function sprintf;

final class InvalidArgumentDefaultValueRule implements Rule
{

public function getNodeType(): string
{
return MethodCall::class;
}

/**
* @param \PhpParser\Node $node
* @param \PHPStan\Analyser\Scope $scope
* @return (string|\PHPStan\Rules\RuleError)[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node instanceof MethodCall) {
throw new ShouldNotHappenException();
};

if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf($scope->getType($node->var))->yes()) {
return [];
}
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'addArgument') {
return [];
}
if (!isset($node->args[3])) {
return [];
}

$modeType = isset($node->args[1]) ? $scope->getType($node->args[1]->value) : new NullType();
if ($modeType instanceof NullType) {
$modeType = new ConstantIntegerType(2); // InputArgument::OPTIONAL
}
$modeTypes = TypeUtils::getConstantScalars($modeType);
if (count($modeTypes) !== 1) {
return [];
}
if (!$modeTypes[0] instanceof ConstantIntegerType) {
return [];
}
$mode = $modeTypes[0]->getValue();

$defaultType = $scope->getType($node->args[3]->value);

// not an array
if (($mode & 4) !== 4 && !(new UnionType([new StringType(), new NullType()]))->isSuperTypeOf($defaultType)->yes()) {
return [sprintf('Parameter #4 $default of method Symfony\Component\Console\Command\Command::addArgument() expects string|null, %s given.', $defaultType->describe(VerbosityLevel::typeOnly()))];
}

// is array
if (($mode & 4) === 4 && !(new UnionType([new ArrayType(new IntegerType(), new StringType()), new NullType()]))->isSuperTypeOf($defaultType)->yes()) {
return [sprintf('Parameter #4 $default of method Symfony\Component\Console\Command\Command::addArgument() expects array<int, string>|null, %s given.', $defaultType->describe(VerbosityLevel::typeOnly()))];
}

return [];
}

}
86 changes: 86 additions & 0 deletions src/Rules/Symfony/InvalidOptionDefaultValueRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
use function sprintf;

final class InvalidOptionDefaultValueRule implements Rule
{

public function getNodeType(): string
{
return MethodCall::class;
}

/**
* @param \PhpParser\Node $node
* @param \PHPStan\Analyser\Scope $scope
* @return (string|\PHPStan\Rules\RuleError)[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node instanceof MethodCall) {
throw new ShouldNotHappenException();
};

if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf($scope->getType($node->var))->yes()) {
return [];
}
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'addOption') {
return [];
}
if (!isset($node->args[4])) {
return [];
}

$modeType = isset($node->args[2]) ? $scope->getType($node->args[2]->value) : new NullType();
if ($modeType instanceof NullType) {
$modeType = new ConstantIntegerType(1); // InputOption::VALUE_NONE
}
$modeTypes = TypeUtils::getConstantScalars($modeType);
if (count($modeTypes) !== 1) {
return [];
}
if (!$modeTypes[0] instanceof ConstantIntegerType) {
return [];
}
$mode = $modeTypes[0]->getValue();

$defaultType = $scope->getType($node->args[4]->value);

// not an array
if (($mode & 8) !== 8) {
$checkType = new UnionType([new StringType(), new IntegerType(), new NullType()]);
if (($mode & 4) === 4) { // https://symfony.com/doc/current/console/input.html#options-with-optional-arguments
$checkType = TypeCombinator::union($checkType, new ConstantBooleanType(false));
}
if (!$checkType->isSuperTypeOf($defaultType)->yes()) {
return [sprintf('Parameter #5 $default of method Symfony\Component\Console\Command\Command::addOption() expects %s, %s given.', $checkType->describe(VerbosityLevel::typeOnly()), $defaultType->describe(VerbosityLevel::typeOnly()))];
}
}

// is array
if (($mode & 8) === 8 && !(new UnionType([new ArrayType(new IntegerType(), new StringType()), new NullType()]))->isSuperTypeOf($defaultType)->yes()) {
return [sprintf('Parameter #5 $default of method Symfony\Component\Console\Command\Command::addOption() expects array<int, string>|null, %s given.', $defaultType->describe(VerbosityLevel::typeOnly()))];
}

return [];
}

}
90 changes: 90 additions & 0 deletions src/Rules/Symfony/UndefinedArgumentRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use InvalidArgumentException;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\PrettyPrinter\Standard;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\ShouldNotHappenException;
use PHPStan\Symfony\ConsoleApplicationResolver;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Symfony\Helper;
use PHPStan\Type\TypeUtils;
use function count;
use function sprintf;

final class UndefinedArgumentRule implements Rule
{

/** @var \PHPStan\Symfony\ConsoleApplicationResolver */
private $consoleApplicationResolver;

/** @var \PhpParser\PrettyPrinter\Standard */
private $printer;

public function __construct(ConsoleApplicationResolver $consoleApplicationResolver, Standard $printer)
{
$this->consoleApplicationResolver = $consoleApplicationResolver;
$this->printer = $printer;
}

public function getNodeType(): string
{
return MethodCall::class;
}

/**
* @param \PhpParser\Node $node
* @param \PHPStan\Analyser\Scope $scope
* @return (string|\PHPStan\Rules\RuleError)[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node instanceof MethodCall) {
throw new ShouldNotHappenException();
};

$classReflection = $scope->getClassReflection();
if ($classReflection === null) {
throw new ShouldNotHappenException();
}

if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf(new ObjectType($classReflection->getName()))->yes()) {
return [];
}
if (!(new ObjectType('Symfony\Component\Console\Input\InputInterface'))->isSuperTypeOf($scope->getType($node->var))->yes()) {
return [];
}
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'getArgument') {
return [];
}
if (!isset($node->args[0])) {
return [];
}

$argType = $scope->getType($node->args[0]->value);
$argStrings = TypeUtils::getConstantStrings($argType);
if (count($argStrings) !== 1) {
return [];
}
$argName = $argStrings[0]->getValue();

$errors = [];
foreach ($this->consoleApplicationResolver->findCommands($classReflection) as $name => $command) {
try {
$command->getDefinition()->getArgument($argName);
} catch (InvalidArgumentException $e) {
if ($scope->getType(Helper::createMarkerNode($node->var, $argType, $this->printer))->equals($argType)) {
continue;
}
$errors[] = sprintf('Command "%s" does not define argument "%s".', $name, $argName);
}
}

return $errors;
}

}
Loading