Giter Site home page Giter Site logo

phpstan / phpstan-nette Goto Github PK

View Code? Open in Web Editor NEW
99.0 9.0 34.0 235 KB

Nette Framework class reflection extension for PHPStan & framework-specific rules

License: MIT License

PHP 98.94% Makefile 1.06%
php nette-framework phpstan php7 static-analysis static-analyzer static-code-analysis testing

phpstan-nette's Introduction

PHPStan - PHP Static Analysis Tool

PHPStan

Build Status Latest Stable Version Total Downloads License PHPStan Enabled


PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even before you write tests for the code. It moves PHP closer to compiled languages in the sense that the correctness of each line of the code can be checked before you run the actual line.

Read more about PHPStan »

Try out PHPStan on the on-line playground! »

Sponsors

TheCodingMachine     Private Packagist
CDN77     Blackfire.io
iO     Amezmo
ShipMonk     Togetter
RightCapital     ContentKing
ZOL     Psyonix
Shopware     Craft CMS
Worksome     campoint AG
Crisp.nl     Inviqa
GetResponse     EdgeNext
Fame Helsinki

You can now sponsor my open-source work on PHPStan through GitHub Sponsors.

Does GitHub already have your 💳? Do you use PHPStan to find 🐛 before they reach production? Send a couple of 💸 a month my way too. Thank you!

One-time donations through PayPal are also accepted. To request an invoice, contact me through e-mail.

Documentation

All the documentation lives on the phpstan.org website:

PHPStan Pro

PHPStan Pro is a paid add-on on top of open-source PHPStan Static Analysis Tool with these premium features:

  • Web UI for browsing found errors, you can click and open your editor of choice on the offending line.
  • Continuous analysis (watch mode): scans changed files in the background, refreshes the UI automatically.

Try it on PHPStan 0.12.45 or later by running it with the --pro option. You can create an account either by following the on-screen instructions, or by visiting account.phpstan.com.

After 30-day free trial period it costs 7 EUR for individuals monthly, 70 EUR for teams (up to 25 members). By paying for PHPStan Pro, you're supporting the development of open-source PHPStan.

You can read more about it on PHPStan's website.

Code of Conduct

This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.

Contributing

Any contributions are welcome. PHPStan's source code open to pull requests lives at phpstan/phpstan-src.

phpstan-nette's People

Contributors

adaamz avatar dakorpar avatar dakur avatar dependabot[bot] avatar enumag avatar herndlm avatar kocal avatar konecnyjakub avatar kukulich avatar localheinz avatar lookyman avatar lulco avatar martenb avatar martinmystikjonas avatar matej21 avatar ondrejmirtes avatar p365labs avatar pepakriz avatar rattuscz avatar renovate-bot avatar renovate[bot] avatar ricco24 avatar ruudk avatar spaze avatar staabm avatar tomasvotruba avatar vhenzl avatar villfa avatar xificurk 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpstan-nette's Issues

Nette 3 redirect error

Hello
Trying to clean phpstan lvl5 errors after upgrade to Nette 3. I am still getting these errors and really dont know what to do (i tried to ignore it, but problem is #2 in error for me)

Parameter #2 $destination of method Nette\Application\UI\Component::redirect() expects string|null, array<string, int> given.
Parameter #2 $destination of method Nette\Application\UI\Component::redirect() expects string|null, array<string, mixed> given.

Any idea how to 'fix' this error or how to add it to exceptions?

Access to an uninitialized property which is @inject-ed

This code is correct and working. With phpstan >= 1.10.23 it reports error Access to an uninitialized property App\AdminModule\Presenters\AdminPresenter::$user.

class AdminPresenter extends Presenter
{
    /** @inject */
    public User $user;

    public function startup()
    {
        parent::startup();

        if (!$this->user->isLoggedIn()) {
            // do something
        }
    }
}

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ^7.2 || ^8.0
  • phpstan/phpstan ^1.10
  • nette/application ^3.0
  • nette/forms ^3.0
  • nette/utils ^2.3.0 || ^3.0.0
  • nikic/php-parser ^4.13.2
  • php-parallel-lint/php-parallel-lint ^1.2
  • phpstan/phpstan-phpunit ^1.0
  • phpstan/phpstan-strict-rules ^1.0
  • phpunit/phpunit ^9.5
github-actions
.github/workflows/build.yml
  • actions/checkout v4
  • shivammathur/setup-php v2
  • actions/checkout v4
  • actions/checkout v4
  • shivammathur/setup-php v2
  • actions/checkout v4
  • shivammathur/setup-php v2
  • actions/checkout v4
  • shivammathur/setup-php v2
.github/workflows/create-tag.yml
  • actions/checkout v4
  • WyriHaximus/github-action-get-previous-tag v1
  • WyriHaximus/github-action-next-semvers v1
  • rickstaa/action-create-tag v1
  • rickstaa/action-create-tag v1
.github/workflows/lock-closed-issues.yml
  • dessant/lock-threads v5
.github/workflows/release-toot.yml
  • cbrgm/mastodon-github-action v2
.github/workflows/release-tweet.yml
  • Eomm/why-don-t-you-tweet v1
.github/workflows/release.yml
  • actions/checkout v4
  • metcalfc/changelog-generator v4.3.1
  • actions/create-release v1

  • Check this box to trigger a request for Renovate to run again on this repository

Nette web-project and autoloading error

I try it but I have big trable. It is some bug?

Step by step:

  • composer create-project nette/web-project
  • change PHP to 7.2 in composer
  • composer require --dev phpstan/phpstan-nette
  • create file phpstan.neon with:
    `
    includes:
    • vendor/phpstan/phpstan-nette/extension.neon
      `
  • vendor/bin/phpstan analyse -l 3 -c phpstan.neon app

And get return as:
Line presenters/HomepagePresenter.php


     Class App\Presenters\HomepagePresenter was not found while trying to analyse it - autoloading is probably not configured properly.

I try add to composer without effect:
"autoload": { "psr-4": { "App\\": "app/" } },

Strings::match() should be checked for invalid regex

I recently added a rule to force using Strings::match() instead of preg_match() in my project for better API and error handling. However it seems that while PHPStan checks preg_match for invalid regular expression (https://github.com/phpstan/phpstan-src/blob/1.9.x/src/Rules/Regexp/RegularExpressionPatternRule.php) the same isn't done for Strings::match().

This is actually very problematic because Strings::match() has the regex and haystack arguments swapped which can be easily missed when switching from preg_match and I already noticed two cases where one of my developers made that mistake.

How should this be solved? Should we copy the rule from PHPStan here and adjust it? Or should the rule in PHPStan be configurable somehow to allow checking other functions and methods? Or maybe a new regex-string type should be added?

RouteList does not accept Route

Hi,

I have a problem with PhpStan + PhpStan-Nette:
Nette\Application\Routers\RouteList does not accept Nette\Application\Routers\Route

Code producing this error:

use Nette\Application\Routers\RouteList;
use Nette\Application\Routers\Route;

$router = new RouteList('v1');
$router[] = new Route('/v1/status', 'Status:default');

Workaround for this situation is this:

$router = new RouteList('v1');
$router->offsetSet(null, new Route('/v1/status', 'Status:default'));

and it works fine, on one project but on the next one there si different error message:
Nette\Application\Routers\RouteList::offsetSet() expects Nette\Routing\Router, Nette\Application\Routers\Route given.

Not sure if it is bug or there is something what I'm doing wrong.

Thank you.

PHP: 7.3
Nette Application: 2.4.13
PhpStan: 0.12.52
Phpstan-Nette: 0.12.9

v0.10 offsetGet in conflict with getComponent

Hello,

thank you very much for v0.10.
I tried it right away in my project and found a lot of these errors.

 ------ ------------------------------------------------------------------------------
  Line   src/....php
 ------ ------------------------------------------------------------------------------
  43     Cannot access offset 'form' on Nette\ComponentModel\IComponent.
  59     Cannot access offset 'form' on Nette\ComponentModel\IComponent.
  86     Cannot access offset 'price' on Nette\ComponentModel\IComponent.
  87     Access to an undefined property Nette\ComponentModel\IComponent::$onSuccess.
 ------ ------------------------------------------------------------------------------

These were not shown in 0.9 and I think that conflict is between new handling of offsetGet and current dynamicReturnType for getComponent().

https://github.com/phpstan/phpstan-nette/blob/master/src/Type/Nette/ComponentModelDynamicReturnTypeExtension.php

https://github.com/nette/application/blob/v2.4.12/src/Application/UI/Component.php#L377-L386

If I change arrayAccess to get components to ->getComponent() method calls, errors go away.

Call to undefined method Nette\Forms\Control

Since version 1.2.2 it reports these errors:

Call to an undefined method Nette\Forms\Control::getOption().
Call to an undefined method Nette\Forms\Control::getControlPrototype().
Call to an undefined method Nette\Forms\Control::getContainerPrototype().
Call to an undefined method Nette\Forms\Control::getItemLabelPrototype().

Weird PHPStan errors for renamed interfaces

In one of our legacy projects we upgraded to Nette 3. After upgrade PHPStan reports many weird errors about incompatible types in places where types should be compatible.

For example:

... expects Nette\Caching\IStorage, Nette\Caching\Storage given
... expects Nette\Database\Row, Nette\Database\Table\ActiveRow given

It seems that it reports places where signature uses old name with I prefix (probably left in Nette code for backward compatibility)? And also places where implementation of renamed Nette interfaces are used agains these interfaces.

It seems that PHPStan do not know that IRow and Row are equivalents. But I do not know why and I do not know how to debug it, Any hints? I already checked and we have latest versions of Nette packages and PHPStan with phpstan-nette extension.

PHPStan: Call to an undefined method Slince\Shopify\Client::methodName()

Hello, in several classes as part of the project, after testing (PHPStan level 2), I'm encountering errors of the type Slince\Shopify\Client::methodName(). Could you please advise me on how to resolve these issues? Thank you.

<?php

namespace App\Providers\Shopify;

use Slince\Shopify\Exception\ClientException;

class BlogProvider extends ShopifyProvider
{
    public function __construct(...)
    {
        ...
        parent::__construct();
    }

    /**
     * @param int $id
     * @return array
     */
    public function push(int $id): array
    {
        try {
            // getArticleManager() declared in Client.php (https://github.com/slince/shopify-api-php/blob/3.x/src/Client.php)
	    $this->getClient($id)->getArticleManager()->update(); // PHPStan throws error here: Call to an undefined method Slince\Shopify\Client::getArticleManager().
            return ['result' => true];

        } catch (ClientException $exception) {
            ...
        }
    }
}

?>
<?php

namespace App\Providers\Shopify;

...
use Slince\Shopify\Client;
use Slince\Shopify\PublicAppCredential;

class ShopifyProvider
{

	public function __construct(...)
	{
		...
	}

    /**
     * @param int $clientId
     * @return \Slince\Shopify\Client
     */
    public function getClient(int $clientId): Client {
        ...

        return new Client($baseUrl, $credential, [
            'meta_cache_dir' => __DIR__,
            'api_version' => '2023-04',
        ]);
    }
}

?>

Call to undefined method when using Nette Events

I am trying to use phpstan with nette and I have a problem with not recognizing Nette Events (even if this should be supported according to README).

My code looks like this:

trait CommonTrait
{
	use SmartObject;

	/** @var array  */
	public $onUpdate = [];
...
        public function insert($data) {
                ...
                $this->onUpdate($data);
        }

But after running PHP stan with Nette extension I am getting these errors:
Call to an undefined method App\Model\Db\Languages::onUpdate()
And it is the same with other classes using this trait.

I am using Nette 2.4 and the latest PHPStan shim and I have tried that the Nette extension loads correctly.

PresenterGetSessionReturnTypeExtension vs automatic Nette presenter registration

Setup:

  • phpstan/phpstan-shim 0.10
  • phpstan/phpstan-nette 0.10
  • Run composer install with --optimize-autoloader flag
  • In application configuration enable Nette\Bridges\ApplicationDI\ApplicationExtension with (default) settings:
application:
  scanComposer: TRUE
  scanFilter: 'Presenter'

Result:
Application crashes during container compilation.

Why:
ApplicationExtension scans all classes from composer autoloader. One of them is PresenterGetSessionReturnTypeExtension, which passes the default filter because it contains Presenter in its name. Nette then tries to load it in order to run additional checks via reflection, but that this ends with fatal error: Interface 'PHPStan\Type\DynamicMethodReturnTypeExtension' not found.

The error is a result of a combination of multiple factors...

  • If you don't use --optimize-autoloader flag the error goes away, because PresenterGetSessionReturnTypeExtension is not registered in the classmap that Nette uses. So, your app may run locally just fine, but fails in CI (or production) with a very obscure fatal error.
  • If you use normal phpstan core package instead of phstan-shim, you're fine -DynamicMethodReturnTypeExtension interface is loadable via composer autoloading, becuase it's not hidden inside phar like in phpstan-shim.

The fatal error is not solvable in Nette. You might argue that this phpstan setup is done incorrectly (it should be installed as 3rd party tool outside of application vendor)... Well, yes... unfortunately this setup is quite common in the wild because of the easy setup.

Possible solution:
Rename the extension to not contain Presenter? It's ugly, but I don't have a better suggestion.

PHP 7.2 support

Running phpstan-nette on php 7.2 fails with the following error:

Fatal error: Cannot use Nette\Object as Object because 'Object' is a special class name in /home/travis/build/nepada/security-annotations/vendor/phpstan/phpstan-nette/src/Reflection/Nette/NetteObjectClassReflectionExtension.php on line 5

I think the workaround is to use either FQN, or alias.

Presenter#sendResponse() is not taken as early terminating method call even it is stated in config file

I have following code placed in action method of a presenter.

try {
	$identity = $this->accountFacade->authenticate($params);

} catch (AccountNotFound $e) {
	$this->error('', IResponse::S404_NOT_FOUND);

} catch (AccountExpired $e) {
	$template->setFile(__DIR__ . '/...');
	$this->sendTemplate();
}

$this->getUser()->login($identity);

Unfortunately phpstan reports Variable $identity might not be defined. for the AccountExpired catch block. When I added throw new \Nette\Application\AbortException() after $this->sendTemplate(), it stopped reporting the error.

sendTemplate() has @throw Nette\Application\AbortException annotated and sendResponse() is listed in early terminated method calls so I don't know where the problem is.

Nette forms callbacks

Hello,
currently I have encountered problems in testing applications because PHPStan started throwing exceptions for Nette Forms Form. He doesn't like callbacks.

Array (array<callable(Nette\Forms\Form, mixed): void>) does not accept Closure(Nette\Application\UI\Form, Nette\Utils\ArrayHash): void.

for

$form->onSuccess[] = function (Nette\Application\UI\Form $form, ArrayHash $values): void {
	...
}

Array (array<callable(Nette\Forms\Form, mixed): void>) does not accept array($this(App\Modules\Section\Presenters\Forum\ForumPresenter), 'onSuccess').

for

$form->onSuccess[] = [$this, 'onSuccess'];

Is there a solution via phpstan-nette extension to fix it?

Resolving BaseControl in presenter

Hi,

(first of all great work with the tool; kudos)

I'm trying to meet level 2 requirements on our Nette project. In presenter we're working with Nette Form components.

The issue I'm facing is, that PHPstan doesn't recognize my form elements as BaseControl even when I think it already should.

I read #27 (comment) and I got an impression, that @ondrejmirtes wanted form elements to always be a BaseControl. I can also see https://github.com/phpstan/phpstan-nette/blob/1.1.x/src/Type/Nette/FormsBaseControlDynamicReturnTypeExtension.php which seems like the thing that should handle it.

Am I just wrong here and the assumption is incorrect?

This is what I execute:

php vendor/bin/phpstan analyse --level=2 --memory-limit=1G app tests extensions
 368/368 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ -------------------------------------------------------------------------- 
  Line   extensions/mailer-module/src/Presenters/GeneratorPresenter.php            
 ------ -------------------------------------------------------------------------- 
  134    Call to an undefined method Nette\ComponentModel\IComponent::setValue().  
 ------ -------------------------------------------------------------------------- 

 ------ -------------------------------------------------------------------------- 
  Line   extensions/mailer-module/src/Presenters/ListPresenter.php                 
 ------ -------------------------------------------------------------------------- 
  419    Call to an undefined method Nette\ComponentModel\IComponent::setValue().  
  422    Call to an undefined method Nette\ComponentModel\IComponent::getValue().  
  424    Call to an undefined method Nette\ComponentModel\IComponent::getValue().  
  429    Call to an undefined method Nette\ComponentModel\IComponent::setItems().  
 ------ -------------------------------------------------------------------------- 

This is the simplified GeneratorPresenter:

<?php
declare(strict_types=1);

use Nette\Application\UI\Form;
use Remp\MailerModule\Forms\SourceTemplateFormFactory;

final class GeneratorPresenter extends BasePresenter
{
    public function createComponentMailSourceTemplateForm(): Form
    {
        $form = $this->sourceTemplateFormFactory->create(isset($this->params['id']) ? (int)$this->params['id'] : null);
        return $form;
    }

    public function handleRenderSorting($sorting): void
    {
        /** @var Form $form */
        $form = $this['mailSourceTemplateForm'];
        $form['sorting']->setValue($sorting); // <<<-------- THIS IS WHAT PHPSTAN COMPLAINS ABOUT
        //...
    }
}

Am I wrong thinking, that if PHPstan knows that the $form is of type Form, and the sorting is a form element, that it is not just IComponent, but a BaseControl?

Thanks a lot for the clarification.

Add support for Nette 2.4?

I cannot make the phpstan-nette work with nette 2.4 and php 7.2. As I can see from composer.json only 2.3 and 3.0 is supported?

Call to an undefined method Nette\ComponentModel\IComponent::addError()

When I am using code $form['password']->addError('Error'); what is valid nette error on form component, I am getting Call to an undefined method Nette\ComponentModel\IComponent::addError() that is right. There is no addError defined in IComponent.
Can I add custom rule to skip this validation?

Checking links

I am planning to write rules to check validity of links (link, redirect, ...) creation.

  • validate that presenter/action used in target exists (based on configured mapping or using PresenterFactory)
  • validate that mandatory parameters (based on action/render method signature) are passed
  • validate types of parameters

We already do this in our phpstan-latte extension (in hacky way) but I would like to write universal solution.

Should I make it as PR to this package or would you preffer it as separate package?

Nette Tester Asserts

I'm trying to run PhpStan on my test cases. Currently PHPStan doesn't understand any type assertions. For the beginning, it would be great to have just few basic:

  • Assert::type()
  • Assert::notNull()

[Security] Workflow release.yml is using vulnerable action metcalfc/changelog-generator

The workflow release.yml is referencing action metcalfc/changelog-generator using references v1.0.0. However this reference is missing the commit 14b159ac83976a0eb274f0a9a6c278c3f1b08e87 which may contain fix to the some vulnerability.
The vulnerability fix that is missing by actions version could be related to:
(1) CVE fix
(2) upgrade of vulnerable dependency
(3) fix to secret leak and others.
Please consider to update the reference to the action.

Form events errors

Hi, i have problems with latest nette/forms and phpstan 1.0.. i will describe it on presenter, but same errors are in control...

<?php declare(strict_types = 1);

namespace App\Presenters;

use Nette\Application\UI\Form;
use Nette\Application\UI\Presenter;
use Nette\Utils\ArrayHash;

final class HomepagePresenter extends Presenter
{

	protected function createCompomentForm(): Form
	{
		$form = new Form();
		$form->onSuccess[] = function (Form $form, ArrayHash $values): void {

		};
		$form->onSuccess[] = [$this, 'formOnSuccess'];

		return $form;
	}

	public function formOnSuccess(Form $form, ArrayHash $values): void
	{

	}

}
 ------ ---------------------------------------------------------------------------------
  Line   Presenters/HomepagePresenter.php
 ------ ---------------------------------------------------------------------------------
  15     Array (array<callable(Nette\Application\UI\Form, mixed): void>) does not accept
         Closure(Nette\Application\UI\Form, Nette\Utils\ArrayHash): void.
  18     Array (array<callable(Nette\Application\UI\Form, mixed): void>) does not accept
         array{$this(App\Presenters\HomepagePresenter), 'formOnSuccess'}.
 ------ ---------------------------------------------------------------------------------

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.