PHPStan rules for detecting usage of deprecated classes, methods, properties, constants and traits.

Overview

Rules for detecting usage of deprecated classes, methods, properties, constants and traits.

Build Latest Stable Version License

Installation

To use this extension, require it in Composer:

composer require --dev phpstan/phpstan-deprecation-rules

If you also install phpstan/extension-installer then you're all set!

Manual installation

If you don't want to use phpstan/extension-installer, include rules.neon in your project's PHPStan config:

includes:
    - vendor/phpstan/phpstan-deprecation-rules/rules.neon

Deprecating code you don't own

This extension emits deprecation warnings on code, which uses properties/functions/methods/classes which are annotated as @deprecated.

In case you don't own the code which you want to be considered deprecated, use PHPStan Stub Files to declare deprecations for vendor files like:

/** @deprecated */
class ThirdPartyClass {}
Comments
  • Show deprecation text in the error message

    Show deprecation text in the error message

    When we deprecate a function or method, we also document the replacement to use. For example,

    /**
     * @deprecated Use bar instead
     */
    function foo() {}
    

    Currently when foo is used in the code, this rule only says foo is deprecated.

    Call to deprecated function foo()
    

    It would be very useful if it shows the deprecation text Use bar instead in the message as well.

    Call to deprecated function foo(). Use bar instead.
    
    opened by wenzhengjiang 16
  • Casting reflection type to string is not found

    Casting reflection type to string is not found

    This may be because it is an internal type, but in the jetbrains stubs it looks like this:

    class ReflectionType
    {
    	/* Methods */
    	/**
    	 * Checks if null is allowed
    	 * @link https://php.net/manual/en/reflectiontype.allowsnull.php
    	 * @return bool TRUE if NULL is allowed, otherwise FALSE
    	 * @since 7.0
    	 */
    	public function allowsNull()
    	{
    	}
    
    	/**
    	 * Checks if it is a built-in type
    	 * @link https://php.net/manual/en/reflectiontype.isbuiltin.php
    	 * @return bool TRUE if it's a built-in type, otherwise FALSE
    	 * @since 7.0
    	 */
    	public function isBuiltin()
    	{
    	}
    
    	/**
    	 * To string
    	 * @link https://php.net/manual/en/reflectiontype.tostring.php
    	 * @return string Returns the type of the parameter.
    	 * @since 7.0
    	 * @deprecated 7.1 Please use getName()
    	 * @see \ReflectionType::getName()
    	 */
    	public function __toString()
    	{
    	}
    
        private final function __clone() {}
    
    }
    
    opened by BackEndTea 13
  •  Add deprecations errors for functions typehints

    Add deprecations errors for functions typehints

    • Add deprecations errors for functions typehints ‒ InFunctionNode
    • Also make errors prettier for anonymous class in deprecations for class method typehints
    opened by paxal 5
  • Test failures with PHPStan dev-master

    Test failures with PHPStan dev-master

    Hi @eiriksm, after your latest changes in phpstan-src, there are now failures in this repo:

    1) PHPStan\Rules\Deprecations\CallToDeprecatedMethodRuleTest::testDeprecatedMethodCall
    Failed asserting that two strings are identical.
    --- Expected
    +++ Actual
    @@ @@
     '07: Call to deprecated method deprecatedFoo() of class CheckDeprecatedMethodCall\Foo.
    +10: Call to deprecated method deprecatedFoo() of class CheckDeprecatedMethodCall\Bar.
     11: Call to deprecated method deprecatedFoo2() of class CheckDeprecatedMethodCall\Foo.
     14: Call to deprecated method deprecatedFooFromTrait() of class CheckDeprecatedMethodCall\Foo.
     15: Call to deprecated method deprecatedWithDescription() of class CheckDeprecatedMethodCall\Foo:
     Call a different method instead.
     '
    
    phar:///home/runner/work/phpstan/phpstan/extension/vendor/phpstan/phpstan/phpstan.phar/src/Testing/RuleTestCase.php:84
    /home/runner/work/phpstan/phpstan/extension/tests/Rules/Deprecations/CallToDeprecatedMethodRuleTest.php:23
    
    2) PHPStan\Rules\Deprecations\CallToDeprecatedStaticMethodRuleTest::testDeprecatedStaticMethodCall
    Failed asserting that two strings are identical.
    --- Expected
    +++ Actual
    @@ @@
     '06: Call to deprecated method deprecatedFoo() of class CheckDeprecatedStaticMethodCall\Foo.
    +08: Call to deprecated method deprecatedFoo() of class CheckDeprecatedStaticMethodCall\Bar.
     09: Call to deprecated method deprecatedFoo2() of class CheckDeprecatedStaticMethodCall\Foo.
     11: Call to method foo() of deprecated class CheckDeprecatedStaticMethodCall\Foo.
     12: Call to method deprecatedFoo() of deprecated class CheckDeprecatedStaticMethodCall\Foo.
    @@ @@
     Do not touch this at all.
     16: Call to deprecated method deprecatedWithDescription() of class CheckDeprecatedStaticMethodCall\Foo:
     This is probably a singleton.
    -24: Call to deprecated method deprecatedFoo() of class CheckDeprecatedStaticMethodCall\Foo.
     '
    

    Can you please look into it so we know what needs fixing? If the tests asserts here are reasonable then phpstan-src needs fixing, or these asserts need to be edited.

    opened by ondrejmirtes 4
  • Failing test case - Usage of deprecated constant via subclass is not marked as deprecation call

    Failing test case - Usage of deprecated constant via subclass is not marked as deprecation call

    The same problem is with deprecated constant defined in interface and used via subclass.

    See e.g. https://github.com/nette/application/blob/v2.4/src/Application/IRouter.php#L22 used with SimpleRouter:

    Code \Nette\Application\Routers\SimpleRouter::SECURED throws no error

    opened by lulco 4
  • support deprecation of external classes/a vendor package

    support deprecation of external classes/a vendor package

    this rules - as is - support phasing out deprecated functinality which was marked as @deprecated beforehand (which implies that I rather own the code and can mark it deprecated, or I agree with the deprecations of a external person and follow their judgment).

    it would be great if phpstan-deprecation-rules could support more advanced use-cases like phasing out a dependency/package.

    lets say we want to soft-migrate a existing codebase with a legacy http client to a more modern http client. that means we want to make sure, new code which gets implemented should use the new client. existing code-sites should be reported by phpstan as usage of deprecated functionality.

    both - the new and the old http client - are 3rd party libraries and therefore we don't have control over annotating the sources.

    I guess this could work with some kind of composer-package-name based deprecation rules, or mabye php namespace based ones.

    opened by staabm 4
  • Enhancement: Use ergebnis/composer-normalize instead of localheinz/composer-normalize

    Enhancement: Use ergebnis/composer-normalize instead of localheinz/composer-normalize

    This PR

    • [x] uses ergebnis/composer-normalize instead of localheinz/composer-normalize

    Related to https://github.com/ergebnis/composer-normalize/issues/266.

    💁‍♂ For reference, see https://localheinz.com/blog/2019/12/10/from-localheinz-to-ergebnis/.

    opened by localheinz 4
  • deprecated constructor argument types

    deprecated constructor argument types

    looks like currently deprecated constructor argument types are not detected by phpstan's deprecation rules.

    not entirely sure whether this could be tested at all as it would require quite some juggling and assumptions on non-typehinted arguments?

    so this is more or less a question of whether or not you want this to be part of the ruleset and whether you have any ideas on how to tackle these instances.

    willing to put in some time to if necesary...

    opened by wickedOne 4
  • Report deprecations as warnings instead of errors

    Report deprecations as warnings instead of errors

    I think using a deprecated class/method/property/whatever (let's name those as entity) shouldn't be reported as an error but as a warning. The key differences I see here are:

    • The code using a deprecated entity will run, it just might break one day, but PHPStan will then trigger an error about the entity being unknown.
    • Reporting a warning instead of an error should not make the CLI exit with a status code different than 0, but it should still output the deprecation message.

    Sometimes I deprecate some classes/methods in my code until I'm sure I don't use them anymore, however PHPStan will then complain about them, so I must ignore the errors, which defeats the purpose of using those deprecation rules.

    What do you think about this?

    opened by nesk 4
  • Deprecation of methods on vendor is not being shown

    Deprecation of methods on vendor is not being shown

    The merge method on Doctrine\ORM\EntityManager is marked as deprecated directly on the code (link).

    But no error/waring is being prompted by the extension.

    If I create the stub below with the annotation than it works as expected.

    <?php
    
    namespace Doctrine\ORM;
    
    class EntityManager
    {
        /** @deprecated */
        public function merge(object $entity): void;
    }
    

    This extension will only read deprecations that I add on my code or in stubs? Or is this a bug on the extension?

    It is not that clear on the README which is the right behavior

    opened by lucassabreu 3
  • Question: Is it possible to have this check excluded for e.g. tests?

    Question: Is it possible to have this check excluded for e.g. tests?

    Hi,

    I really like this option to test for usage of deprecated functions. I have quite some tests that runs the deprecated code and would prefer to keep it like that till the deprecated code is removed.

    Is it possible to exclude the deprecation rules for some files/folders, without excluding it completely from PHPStan check?

    opened by tomasnorre 3
  • Add detection of overridden deprecated properties

    Add detection of overridden deprecated properties

    Feature request: When overriding a class property in a child class, that is marked as deprecated in the parent class, a warning should be given. Currently only accessing such properties within methods of the child class triggers this warning.

    This would be particularly useful for cases where an upstream package marks a property as deprecated, and where the intended method of setting the property is through overriding it with a new (default) value within the child class, without explicitly accessing it in any method on the child class.

    A real world example of such a case is the planned removal of the dates property in Laravel, which won't be detected as a deprecated property currently when overriding it. A code example that currently does not yield any warning:

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Foo extends Model
    {
        protected $dates = ['foo'];
    }
    
    opened by jnoordsij 0
  •  Support for #[Deprecated()]  annotation

    Support for #[Deprecated()] annotation

    phpstorm-stubs use JetBrains\PhpStorm\Deprecated annotation to mark method's, class e.t.c This annotation allows for more detailed description of the problem and suggested changes.

    Other projects use this annotation as well

    Can deprecation-rules show it in the same way like @deprecated ?

    opened by DeyV 0
  • Add a config option to ignore self-deprecations

    Add a config option to ignore self-deprecations

    When exposing a library, you need to respect semantic versioning and avoid BC-break.

    Let's say you have some code

    class Foo
    {
         /** @deprecated */
         protected $foo;
    
         private $newFoo;
    
         public getFoo():
         {
              return $this->foo ?? $this->newFoo;
         }
    }
    

    An error is reported because $this->foo; is used but changing this/removing it would be a BC break.

    But the phpstan-deprecation-rules would still be useful to detect when I use a deprecated method from another library.

    Is it possible to add an option in order to

    • Turn off errors if the deprecated Method/Interface/Property/Class/... is from my project
    • Keep the erros if the deprecated Method/Interface/Property/Class/... is coming from a vendor

    ?

    opened by VincentLanglet 3
  • PHPStan reports wrongly a method as deprecated, because the overwriting method from a trait is not detected

    PHPStan reports wrongly a method as deprecated, because the overwriting method from a trait is not detected

    Bug report

    I am using phpstan in combination with phpstan-deprecation-rules and getting false-positives in my test classes since a deprecation annotation has been added to PHPUnit.

    The code detecting deprecations in phpstan-deprecation-rules looks good:

    $classReflection = $this->reflectionProvider->getClass($referencedClass);
    $methodReflection = $classReflection->getMethod($methodName, $scope);
    
    if (!$methodReflection->isDeprecated()->yes()) {
        continue;
    }
    

    But the $methodReflection is pointing to the method defined in the (TestCase) base class instead of the overwriting method in the ProphecyTrait.

    To reproduce this issue easily, I have created a minimal setup.

    source file to check

    <?php
    
    declare(strict_types=1);
    
    trait MyTrait
    {
        protected function prophesize(): void
        {
            echo 'Trait';
        }
    }
    
    abstract class MyBaseClass
    {
        /** @deprecated Use MyTrait::prophesize() */
        protected function prophesize(): void
        {
            echo 'Base';
        }
    }
    
    final class MyClass extends MyBaseClass
    {
        use MyTrait;
    
        public function callProphesize(): void
        {
            $this->prophesize(); // wrongly detected deprecation
        }
    }
    
    

    phpstan.neon

    parameters:
        level: max
        paths:
            - src
    
    includes:
        - %rootDir%/../../phpstan/phpstan-deprecation-rules/rules.neon
    

    Expected output

    I am expectiong that the $methodReflection variable is pointing to MyTrait::prophesize() so that $methodReflection->isDeprecated()->yes() returns false and no deprecation is detected by phpstan-deprecation-rules.

    Did PHPStan help you today? Did it make you happy in any way?

    phpstan is a great tool that helps a lot in daily work.

    opened by pl-github 5
  • AnonymousClass6a85eed1b3aeaa3b7eaea1eb536990ed

    AnonymousClass6a85eed1b3aeaa3b7eaea1eb536990ed

    for https://github.com/doctrine/dbal/blob/3.5.1/src/Platforms/AbstractPlatform.php#L225 this lib currently emit:

    Call to deprecated method getVarcharTypeDeclarationSQL() of class AnonymousClass6a85eed1b3aeaa3b7eaea1eb536990ed:
    Use {@link getStringTypeDeclarationSQL()} instead.
    

    from AnonymousClass6a85eed1b3aeaa3b7eaea1eb536990ed it is very hard to tell which class and also I double the name is stable for error ignore.

    I would expect anonymous name like from native phpstan https://phpstan.org/r/7f7ac916-f7fe-4c4d-8035-337e837344ae, ie. class@anonymous/tmp.php:7 istead of AnonymousClass6a85eed1b3aeaa3b7eaea1eb536990ed.

    opened by mvorisek 1
  • Strange behavior

    Strange behavior

    Hi, I have problem with depracation rules in GitLab CI. I have following code

    <?php declare(strict_types = 1);
    
    namespace App\Core\Controls\Base\Grid;
    
    use Nette\ComponentModel\IContainer;
    use Nette\Localization\Translator;
    
    class GridFactory
    {
    
    	protected Translator $translator;
    
    	public function __construct(Translator $translator)
    	{
    		$this->translator = $translator;
    	}
    
    	public function create(?IContainer $parent = null, ?string $name = null): Grid
    	{
    		$grid = new Grid($parent, $name);
    		$grid->setTranslator($this->translator); // problematic line
    
    <?php declare(strict_types = 1);
    
    namespace App\Core\Controls\Base\Grid;
    
    use Ublaboo\DataGrid\DataGrid;
    
    class Grid extends DataGrid
    {
    }
    

    DataGrid is external library, in setTranslator, it accepts depracated ITranslator. So i added it to ignore. On local is everthing ok, but in GitLab CI, i am getting following error.

     Ignored error pattern #^Parameter \#1 \$translator of method           
             Ublaboo\\DataGrid\\DataGrid\:\:setTranslator\(\) expects               
             Nette\\Localization\\ITranslator, Nette\\Localization\\Translator      
             given\.$#
    

    On local and CI i have same PHP version. Any suggestioins???

    opened by martenb 0
Releases(1.1.0)
Owner
PHPStan
PHP Static Analysis Tool - discover bugs in your code without running it!
PHPStan
Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8

Laravel Encrypt Database Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8. I'm yet building the tests. Important Note th

Wellington Barbosa 2 Dec 15, 2021
Laravel Security was created by, and is maintained by Graham Campbell, and is a voku/anti-xss wrapper for Laravel, using graham-campbell/security-core

Laravel Security Laravel Security was created by, and is maintained by Graham Campbell, and is a voku/anti-xss wrapper for Laravel, using graham-campb

Graham Campbell 170 Nov 20, 2022
A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryption, digital signing and message authentication.

PHP Encryption A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryp

null 19 Dec 31, 2022
PHP 5.x support for random_bytes() and random_int()

random_compat PHP 5.x polyfill for random_bytes() and random_int() created and maintained by Paragon Initiative Enterprises. Although this library sho

Paragon Initiative Enterprises 8k Jan 5, 2023
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Jan 6, 2023
PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application

PHPIDS PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web ap

null 752 Jan 3, 2023
A library for generating random numbers and strings

RandomLib A library for generating random numbers and strings of various strengths. This library is useful in security contexts. Install Via Composer

Anthony Ferrara 832 Nov 24, 2022
Fast, general Elliptic Curve Cryptography library. Supports curves used in Bitcoin, Ethereum and other cryptocurrencies (secp256k1, ed25519, ..)

Fast Elliptic Curve Cryptography in PHP Information This library is a PHP port of elliptic, a great JavaScript ECC library. Supported curve types: Sho

Simplito 178 Dec 28, 2022
A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks.

SecurityMultiTool A multitool library offering access to recommended security related libraries, standardised implementations of security defences, an

Pádraic Brady 131 Oct 30, 2022
TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library

About TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library. By default, a cookie will be used as a storage backend. TCrypto h

timoh 57 Dec 2, 2022
Automatic SQL injection and database takeover tool

sqlmap sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of

sqlmapproject 25.7k Jan 5, 2023
Ransomware with automatic Coinbase Commerce integration created in C# (Console) and PHP

AWare — C# Ransomware Ransomware with automatic Coinbase Commerce integration created in C# (Console) and PHP PD: AWare is just a proof of concept, wi

in the space 26 Sep 16, 2022
A simple php (lumen) app for sharing sensitive text (basically like onetimesecret), but with full end-to-end AES-256-GCM encryption so even the server has no access to the data, and developed with very simple deployment in mind.

A simple php (lumen) app for sharing sensitive text (basically like onetimesecret), but with full end-to-end AES-256-GCM encryption so even the server has no access to the data, and developed with very simple deployment in mind.

Alan Woo 51 Nov 21, 2022
A (unofficial) WordPress plugin reporting PHP and JavaScript errors to Sentry.

A (unofficial) WordPress plugin to report PHP and JavaScript errors to Sentry.

Alex Bouma 239 Dec 14, 2022
Quickly and easily secure HTML text.

Larasane Quickly sanitize text into safe-HTML using fluid methods. Requirements PHP 7.4, 8.0 or later. Laravel 7.x, 8.x or later. Installation Just fi

Italo 40 Jul 20, 2021
ChestRandomBP: This plugin generates chests in random places within a specific world. Where you can customize what each one of them contains, the time and the world of spawning.

ChestRandomBP ChestRandomBP: This plugin generates chests, it works PocketMine-MP and random places within a specific world. Where you can customize w

null 5 Sep 19, 2021
Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication.

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication. PGP is used for signing, encrypting, and decrypting texts, e-mails, files, directories, and whole disk partitions and to increase the security of e-mail communications. Phil Zimmermann developed PGP in 1991.

[sCRiPTz-TEAM] 3 Dec 31, 2021
On International Talk Like a Pirate Day (September 19th), this filter changes all appropriate English phrases and words into pirate-speak.

Pirate This module is a simple filter that, when enabled, will change your posts to "Pirate talk" on September 19th for Talk like a Pirate Day Install

Backdrop CMS contributed projects 3 Oct 26, 2021