proget-hq / phpstan-yii2 Goto Github PK
View Code? Open in Web Editor NEWYii2 extension for PHPStan
License: MIT License
Yii2 extension for PHPStan
License: MIT License
Hello everyone 👋
I announced today that PHPStan 1.0 is going to be released on November 1st 2021.
I'm approaching you as one of the most popular PHPStan extensions. I'd love if you could prepare your code for PHPStan 1.0 in advance so that it's ready to release on the same day.
Here's a brief guide how to approach the upgrade:
"phpstan/phpstan": "^1.0"
, add "minimum-stability": "dev"
and "prefer-stable": true
if necessary.Thank you!
Here are the BC breaks. The list is huge but most of those have very little impact.
There are new rules around using PHPStan internals in regard to backward compatibility promise: https://phpstan.org/developing-extensions/backward-compatibility-promise
It's possible that not everything you use is covered by it - so I'm here to help you to transition to correct usage, or add some @api
annotations in PHPStan itself so that more is covered by the promise. Let me know!
max
is now level 9. Feel free to update max
to 8
if your code isn't ready.numeric-string
(it was previously described as string&numeric
), and also array shapes.baselineNeon
error formatter, use --generate-baseline
CLI option instead (phpstan/phpstan-src@492cfbc)polluteCatchScopeWithTryAssignments
config parameter (phpstan/phpstan-src@8933c7e)autoload_files
parameter - use Discovering Symbols instead (phpstan/phpstan-src@7a21246)autoload_directories
parameter - use Discovering Symbols instead (phpstan/phpstan-src@f67b48a)bootstrap
parameter - use bootstrapFiles
instead (phpstan/phpstan-src@1baa294)implicitThrows
configuration parameter to exceptions.implicitThrows
(phpstan/phpstan-src@96b7c48)--paths-file
CLI option (phpstan/phpstan-src@5670cf2)dump-deps
command (phpstan/phpstan-src@9c7017c)excludes_analyse
option, use excludePaths
instead (phpstan/phpstan-src@d25c5e5)The following are interesting only if you create a custom ruleset in your configuration file:
DeadCatchRule
, replaced by CatchWithUnthrownExceptionRule
(phpstan/phpstan-src@4dba60b)VariableCertaintyInIssetRule
, replaced by IssetRule
(phpstan/phpstan-src@2e858de)MissingClosureNativeReturnTypehintRule
, no longer needed thanks to type inference (phpstan/phpstan-src@1c34d8d)CompoundTypeHelper
(phpstan/phpstan-src@145c4e3)CommentHelper
(phpstan/phpstan-src@ebad6f6)DependencyDumper
(phpstan/phpstan-src@9c7017c)PHPStan\Reflection\Generic\ResolvedFunctionVariant
, replaced by PHPStan\Reflection\ResolvedFunctionVariant
(phpstan/phpstan-src@1cc6c81)ClassReflection::getNativeMethods()
, use getNativeReflection()
instead (phpstan/phpstan-src@d2c1446)PhpPropertyReflection::hasPhpDoc()
, replaced by hasPhpDocType()
(phpstan/phpstan-src@bedd5be)NodeDependencies
no longer iterable (phpstan/phpstan-src@f76875a)TestCase
to PHPStanTestCase
(#634), thanks @frankdejonge!StaticType
and ThisType
- require ClassReflection
in constructor (phpstan/phpstan-src@7aabc84)PHPStanTestCase
- extensions can no longer be provided by overriding methods from PHPStanTestCase
. Use getAdditionalConfigFiles()
instead. (phpstan/phpstan-src@65efd93, phpstan/phpstan-src@239291a)|false
to |null
(phpstan/phpstan-src@629ccf6)BrokerAwareExtension
(phpstan/phpstan-src@db2f7fb)PHPStanTestCase::createBroker()
. Use createReflectionProvider()
instead. (phpstan/phpstan-src@1e5cf58)PHPStan\Broker\Broker
. Use PHPStan\Reflection\ReflectionProvider
instead. (phpstan/phpstan-src@c775594)PHPStan\Broker\Broker::getInstance()
. Use PHPStan\Reflection\ReflectionProviderStaticAccessor
instead. (phpstan/phpstan-src@4e7d60d)This file can be included in phpstan config using stubFiles
directive.
namespace yii\db {
class ActiveRecord {
/**
* @phpstan-return ActiveQuery<static>
*/
public static function find();
}
/**
* @template T of ActiveRecord
*/
class ActiveQuery {
/**
* @phpstan-return T[]
*/
public function all($db = null);
/**
* @phpstan-return T|null
*/
public function one($db = null);
}
}
Is there any planned upgrade for phpstan 0.11.2?
At the moment I am not able to install the extension based on the lack of support:
Problem 1
- Installation request for proget-hq/phpstan-yii2 ^0.4.2 -> satisfiable by proget-hq/phpstan-yii2[0.4.2].
- proget-hq/phpstan-yii2 0.4.2 requires phpstan/phpstan ^0.10.3 -> satisfiable by phpstan/phpstan[0.10.3, 0.10.4, 0.10.5, 0.10.6, 0.10.7, 0.10.8, 0.10.x-dev] but these conflict with your requirements or minimum-stability.
Thanks
Hi!
I use .env variables in my project and see these warnings when running phpstan:
I created a bootstrap file with the following code:
$dotenv = new \Symfony\Component\Dotenv\Dotenv();
$dotenv->load(__DIR__.'/.env.test');
There are lines like this:
'dsn' =>$_ENV['DB_TEST_DSN']
in config/test_db.php, and I require this file ./config/test.php
This is my phpstan.neon
.
includes:
- vendor/proget-hq/phpstan-yii2/extension.neon
parameters:
autoload_files:
- %rootDir%/../../../common/helpers.php
yii2:
config_path: %rootDir%/../../../config/web.php
I use functions defined in %rootDir%/../../../common/helpers.php
in my config file, however phpstan-yii2
's services seem to be executed before that file is included and it fails with a message that no such function exists.
I installed PhpStan and this extension using Composer in my Yii2 project, created the phpstan.neon
config file with the following content:
includes:
- vendor/proget-hq/phpstan-yii2/extension.neon
parameters:
yii2:
config_path: %rootDir%/../../../config/test.php
After running it the first time, I run into issue #27, but fixed it by require_once
tip mentioned on the same issue.
After running it again, the only output I get is this: Note: Using configuration file /var/www/proteus/phpstan.neon.
It doesn't give me anything else. It is a huge project, I'm sure there are tons of issues it should list, but I only get an empty output. What am I doing wrong?
PHP 7.3.26
"yiisoft/yii2" : "2.0.30",
"phpstan/phpstan": "0.12.69",
"proget-hq/phpstan-yii2": "^0.7",
Internal error: Internal error: Unexpected type PHPStan\Type\ObjectType during method call andFilterWhere at line 139 in file /var/www/promo-api/readModels/goods/TagIndexSearchModel.php
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new
Internal error: Internal error: Unexpected type PHPStan\Type\ObjectType during method call from at line 251 in file /var/www/promo-api/readModels/promotion/PromotionFilterModel.php
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new
Internal error: Internal error: Unexpected type PHPStan\Type\ObjectType during method call asArray at line 122 in file /var/www/promo-api/readModels/promotion/PromotionSearchModel.php
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new
Internal error: Internal error: Unexpected type PHPStan\Type\ObjectType during method call cache at line 93 in file /var/www/promo-api/readModels/promotion/PromotionGoodsSearchModel.php
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new
Child process error (exit code 1):
Child process error (exit code 1):
with --debug option just show
....
/var/www/promo-api/readModels/goods/TagIndexSearchModel.php
An internal server error occurred.
This might just be an awkward bug of phpstan itself, but I thought I'd mention it here first.
$file = Files::find()
->select('name')
->where('id = :id', [':id' => $fileId])
->one();
Here it complains that the where
method wants an array
and never a string
. This is because the original \yii\db\Query
class includes {@inheritdoc}
for the where
method, and the original \yii\db\QueryInterface
interface only allows for array
.
That the \yii\db\Query
class "overrided" the parameter (to allow also string
and ExpressionInterface
) does not matter to phpstan.
Should this be worked around in phpstan-yii2
or should this thing be fixed in phpstan
itself?
phpstan 0.11.15
level 5
When running phpstan analyse api --level
the following error is thrown. Seems like a relatively "simple" backwards incompatible type-change by the phpstan project.
2/41 [▓░░░░░░░░░░░░░░░░░░░░░░░░░░░] 4%PHP Fatal error: Declaration of Proget\PHPStan\Yii2\Type\ActiveRecordObjectType::setOffsetValueType(?PHPStan\Type\Type $offsetType, PHPStan\Type\Type $valueType): PHPStan\Type\Type must be compatible with PHPStan\Type\ObjectType::setOffsetValueType(?PHPStan\Type\Type $offsetType, PHPStan\Type\Type $valueType, bool $unionValues = true): PHPStan\Type\Type in /home/etiennebruines/workspaces/mossaino/mossaino/vendor/proget-hq/phpstan-yii2/src/Type/ActiveRecordObjectType.php on line 28
<pre>PHP Compile Error 'yii\base\ErrorException' with message 'Declaration of Proget\PHPStan\Yii2\Type\ActiveRecordObjectType::setOffsetValueType(?PHPStan\Type\Type $offsetType, PHPStan\Type\Type $valueType): PHPStan\Type\Type must be compatible with PHPStan\Type\ObjectType::setOffsetValueType(?PHPStan\Type\Type $offsetType, PHPStan\Type\Type $valueType, bool $unionValues = true): PHPStan\Type\Type'
in /home/etiennebruines/workspaces/mossaino/mossaino/vendor/proget-hq/phpstan-yii2/src/Type/ActiveRecordObjectType.php:28
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}</pre>Script ./vendor/bin/phpstan analyse api --level max --memory-limit=1G handling the test/phpstan event returned with error code 1
phpstan/phpstan 0.12.91
proget-hq/phpstan-yii2 0.7.4
Pinning phpstan to 0.12.90
seems to alleviate the issue.
When I run analyze my Yii2 project with phpstan v 0.12.34 and proget-hq/phpstan-yii2 v 0.7.3 I get next warning:
PHP Warning: Use of undefined constant YII_DEBUG - assumed 'YII_DEBUG' (this will throw an Error in a future version of PHP) in /config/web.php on line 54
Warning: Use of undefined constant YII_DEBUG - assumed 'YII_DEBUG' (this will throw an Error in a future version of PHP) in /config/web.php on line 54
It appears, because in class ServiceMap
there aren't defined this constant. If add to this class constant \defined('YII_DEBUG') or define('YII_DEBUG', true);
it is all right. Please, fix this bug in your future release.
Code in the controller:
/**
* @var Transfer|null $transfer
*/
$transfer = Transfer::find()->one();
if (!$transfer) {
return;
}
$paymentsTransfers = $transfer->getPaymentTransfer()->all();
Model:
class Transfer extends \yii\db\ActiveRecord
{
/**
* @return \yii\db\ActiveQuery
*/
public function getPaymentTransfer()
{
return $this->hasMany(PaymentTransfer::class, ['transfer_id' => 'id']);
}
}
getPaymentTransfer()
method return type provided in PhpDoc or using native return type set to ActiveQuery
leads to extension exception: Internal error: Unexpected type PHPStan\Type\ObjectType during method call all at line 142
(line 142 is $transfer->getPaymentTransfer()->all()
call). That error comes from \Proget\PHPStan\Yii2\Type\ActiveQueryDynamicMethodReturnTypeExtension::getTypeFromMethodCall
. Here is what's in the $calledOnType
:
object(PHPStan\Type\ObjectType)#9382 (3) {
["className":"PHPStan\Type\ObjectType":private]=>
string(18) "yii\db\ActiveQuery"
["subtractedType":"PHPStan\Type\ObjectType":private]=>
NULL
["genericObjectType":"PHPStan\Type\ObjectType":private]=>
NULL
}
If I remove return type from getPaymentTransfer()
everything works fine. But that looks odd and that's easy to break if someone adds return type.
PHPStan crashing when I use static type in relation, for example: recursive category with same parent type:
class` Category extends ActiveRecord
{
public function getParent(): ActiveQuery
{
return $this->hasOne(static::class, ['id' => 'parent_id']);
}
}
And I got error:
Line common/components/category/models/Category.php
------ --------------------------------------------------------------
Internal error: Invalid argument provided to method hasOne
Hint: You should use ::class instead of ::className()
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new
-- -------------------------------------------------------------------------------------------------
Error
-- -------------------------------------------------------------------------------------------------
Error message "Internal error: Invalid argument provided to method hasOne
Hint: You should use ::class instead of ::className()
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new" cannot be ignored, use excludes_analyse instead.
-- -------------------------------------------------------------------------------------------------
[ERROR] Found 1 errors
I use last version of proget-hq/phpstan-yii2 on current date.
For entry
[
'singletons' => [
CacheInterface::class => FileCache::class
]
]
in container configurations I get
In ServiceMap.php line 87:
Function yii\caching\FileCache() does not exist
because this service definition is considered function.
Probably adding
if (\is_string($service) && class_exists($service)) {
$this->services[$id] = $service;
return;
}
at the top of addServiceDefinition()
is enough to resolve this problem.
➜ MMR git:(PHP-Static-Code-Analysis) ✗ vendor/bin/phpstan analyse frontend
Note: Using configuration file /vagrant/MMR/phpstan.neon.
PHP Fatal error: Uncaught Error: Class 'Yii' not found in /vagrant/MMR/frontend/config/web.php:9
Stack trace:
#0 /vagrant/MMR/vendor/proget-hq/phpstan-yii2/src/ServiceMap.php(31): require()
#1 /tmp/phpstan/cache/nette.configurator/Container_36e5b17f91.php(3264): Proget\PHPStan\Yii2\ServiceMap->__construct('/vagrant/MMR/ve...')
#2 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(146): Container_36e5b17f91->createService0169()
#3 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(88): _HumbugBoxa35debbd0202\Nette\DI\Container->createService('0169')
#4 /tmp/phpstan/cache/nette.configurator/Container_36e5b17f91.php(3197): _HumbugBoxa35debbd0202\Nette\DI\Container->getService('0169')
#5 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(146): Container_36e5b17f91->createService0158()
#6 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(88): _HumbugBoxa35debbd0202\Nette\DI\Container- in /vagrant/MMR/frontend/config/web.php on line 9
Fatal error: Uncaught Error: Class 'Yii' not found in /vagrant/MMR/frontend/config/web.php:9
Stack trace:
#0 /vagrant/MMR/vendor/proget-hq/phpstan-yii2/src/ServiceMap.php(31): require()
#1 /tmp/phpstan/cache/nette.configurator/Container_36e5b17f91.php(3264): Proget\PHPStan\Yii2\ServiceMap->__construct('/vagrant/MMR/ve...')
#2 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(146): Container_36e5b17f91->createService0169()
#3 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(88): _HumbugBoxa35debbd0202\Nette\DI\Container->createService('0169')
#4 /tmp/phpstan/cache/nette.configurator/Container_36e5b17f91.php(3197): _HumbugBoxa35debbd0202\Nette\DI\Container->getService('0169')
#5 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(146): Container_36e5b17f91->createService0158()
#6 phar:///vagrant/MMR/vendor/phpstan/phpstan/phpstan/vendor/nette/di/src/DI/Container.php(88): _HumbugBoxa35debbd0202\Nette\DI\Container- in /vagrant/MMR/frontend/config/web.php on line 9
➜ MMR git:(PHP-Static-Code-Analysis) ✗
Hello, I have next error on latest version phpstan:
Internal error: Argument 1 passed to PHPStan\Analyser\MutatingScope::resolveName() must be an instance of PhpParser\Node\Name, instance of PhpParser\Node\Expr\PropertyFetch given, called in \vendor\proget-hq\phpstan-yii2\src\Type\ActiveRecordDynamicStaticMethodReturnTypeExtension.php on line 51
I have next error
------ ---------------------------------------------------------------------------------------------
Line TestModel.php
------ ---------------------------------------------------------------------------------------------
14 Method common\models\TestModel::getAll() should return array<static(common\models\TestModel)> but returns array<int, common\models\TestModel>.
------ ----------------------------------------------------------------------------------------------
This is my example code
class TestModel extends ActiveRecord
{
/**
* @return static[]
*/
public function getAll() : array
{
return static::find()->all();
}
}
Version phpstan is latest (1.5.4)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.