Giter VIP home page Giter VIP logo

phpstan-yii2's People

Contributors

akondas avatar danieljonderko avatar dawidrylko avatar etiennebruines avatar khartir avatar marmichalski avatar particleflux avatar przepompownia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

phpstan-yii2's Issues

Internal error: Unexpected type PHPStan\Type\ObjectType

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.

Can't use phpstan-yii2 if there are helper functions in config

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.

container -> singletons

При анализе появляется ошибка вида:
image

Немного покопавшись в коде наткнулся на:
image
Что мы должны добавлять в этот массив в файле конфигурации?

Problem with relations

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.

error with annotation `@return static[]`

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)

.env variables warnings

Hi!
I use .env variables in my project and see these warnings when running phpstan:
image

I created a bootstrap file with the following code:

$dotenv = new \Symfony\Component\Dotenv\Dotenv();
$dotenv->load(__DIR__.'/.env.test');

and add it to config
Screenshot from 2022-12-08 13-14-10

There are lines like this:
'dsn' =>$_ENV['DB_TEST_DSN']

in config/test_db.php, and I require this file ./config/test.php

Empty output

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 Fatal error: Uncaught Error: Class 'Yii' not found when running the analysis

➜ 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) ✗

image

Incompatibility with latest PHPStan

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 &#039;yii\base\ErrorException&#039; with message &#039;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&#039; 

in /home/etiennebruines/workspaces/mossaino/mossaino/vendor/proget-hq/phpstan-yii2/src/Type/ActiveRecordObjectType.php:28

Stack trace:
#0 [internal function]: yii\base\ErrorHandler-&gt;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

Versions

phpstan/phpstan 0.12.91
proget-hq/phpstan-yii2 0.7.4

Workaround

Pinning phpstan to 0.12.90 seems to alleviate the issue.

Parameter #1 $condition of method yii\db\Query::where() expects array, string given.

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

Lack of support for phpstan 0.11.2

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

Incorrect error with static::class

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.

Use generics to simplify extension

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);
    }
}

String service definitions are considered function

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.

Use of undefined constant YII_DEBUG

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.

Prepare for PHPStan 1.0

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:

  1. Create a branch 🌴
  2. Update your composer.json to "phpstan/phpstan": "^1.0", add "minimum-stability": "dev" and "prefer-stable": true if necessary.
  3. Update your code with the BC breaks below in mind. 🔧
  4. Fix the code so that it passes PHPStan's analysis 🤓
  5. Wait for PHPStan 1.0 release on November 1st, merge your branch and tag the next major version 👍

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!

BC breaks for end-users

The following are interesting only if you create a custom ruleset in your configuration file:

BC breaks for extension developers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.