This blog talks about Computer, Security, Information technology, SEO, Video, etc. Now you can find all free things, Information Technology and Tips and Trick in this blog. JOIN ME KANG ASU

Breaking

Saturday, 7 September 2019

PHPStan

Kang Asu

PHPStan

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 on Medium.com
Try out PHPStan on the on-line playground!


Prerequisites
PHPStan requires PHP >= 7.1. You have to run it in environment with PHP 7.x but the actual code does not have to use PHP 7.x features. (Code written for PHP 5.6 and earlier can run on 7.x mostly unmodified.)
PHPStan works best with modern object-oriented code. The more strongly-typed your code is, the more information you give PHPStan to work with.
Properly annotated and typehinted code (class properties, function and method arguments, return types) helps not only static analysis tools but also other people that work with the code to understand it.

Installation
To start performing analysis on your code, require PHPStan in Composer:
composer require --dev phpstan/phpstan
Composer will install PHPStan's executable in its bin-dir which defaults to vendor/bin.
If you have conflicting dependencies or you want to install PHPStan globally, the best way is via a PHAR archive. You will always find the latest stable PHAR archive below the release notes. You can also use the phpstan/phpstan-shim package to install PHPStan via Composer without the risk of conflicting dependencies.
You can also use PHPStan via Docker.

First run
To let PHPStan analyse your codebase, you have to use the analyse command and point it to the right directories.
So, for example if you have your classes in directories src and tests, you can run PHPStan like this:
vendor/bin/phpstan analyse src tests
PHPStan will probably find some errors, but don't worry, your code might be just fine. Errors found on the first run tend to be:
  • Extra arguments passed to functions (e. g. function requires two arguments, the code passes three)
  • Extra arguments passed to print/sprintf functions (e. g. format string contains one placeholder, the code passes two values to replace)
  • Obvious errors in dead code
  • Magic behaviour that needs to be defined. See Extensibility.
After fixing the obvious mistakes in the code, look to the following section for all the configuration options that will bring the number of reported errors to zero making PHPStan suitable to run as part of your continuous integration script.

Rule levels
If you want to use PHPStan but your codebase isn't up to speed with strong typing and PHPStan's strict checks, you can choose from currently 8 levels (0 is the loosest and 7 is the strictest) by passing --level to analyse command. Default level is 0.
This feature enables incremental adoption of PHPStan checks. You can start using PHPStan with a lower rule level and increase it when you feel like it.

You can also use --level max as an alias for the highest level. This will ensure that you will always use the highest level when upgrading to new versions of PHPStan. Please note that this can create a significant obstacle when upgrading to a newer version because you might have to fix a lot of code to bring the number of errors down to zero.

Extensibility
Unique feature of PHPStan is the ability to define and statically check "magic" behaviour of classes - accessing properties that are not defined in the class but are created in __get and __set and invoking methods using __call.
See Class reflection extensionsDynamic return type extensions and Type-specifying extensions.
You can also install official framework-specific extensions:
Unofficial extensions for other frameworks and libraries are also available:
Unofficial extensions with third-party rules:
New extensions are becoming available on a regular basis!

Configuration
Config file is passed to the phpstan executable with -c option:
vendor/bin/phpstan analyse -l 4 -c phpstan.neon src tests
When using a custom project config file, you have to pass the --level (-l) option to analyse command (default value does not apply here).
If you do not provide config file explicitly, PHPStan will look for files named phpstan.neon or phpstan.neon.dist in current directory.
The resolution priority is as such:
  1. If config file is provided on command line, it is used.
  2. If config file phpstan.neon exists in current directory, it will be used.
  3. If config file phpstan.neon.dist exists in current directory, it will be used.
  4. If none of the above is true, no config will be used.
NEON file format is very similar to YAML. All the following options are part of the parameters section.

Configuration variables
  • %rootDir% - root directory where PHPStan resides (i.e. vendor/phpstan/phpstan in Composer installation)
  • %currentWorkingDirectory% - current working directory where PHPStan was executed

Configuration options
  • tmpDir - specifies the temporary directory used by PHPStan cache (defaults to sys_get_temp_dir() . '/phpstan')
  • level - specifies analysis level - if specified, -l option is not required
  • paths - specifies analysed paths - if specified, paths are not required to be passed as arguments

Autoloading
PHPStan uses Composer autoloader so the easiest way how to autoload classes is through the autoload/autoload-dev sections in composer.json.

Specify paths to scan
If PHPStan complains about some non-existent classes and you're sure the classes exist in the codebase AND you don't want to use Composer autoloader for some reason, you can specify directories to scan and concrete files to include usingautoload_directories and autoload_files array parameters:
parameters:
 autoload_directories:
  - %rootDir%/../../../build
 autoload_files:
  - %rootDir%/../../../generated/routes/GeneratedRouteList.php
%rootDir% is expanded to the root directory where PHPStan resides.

Autoloading for global installation
PHPStan supports global installation using composer global or via a PHAR archive. In this case, it's not part of the project autoloader, but it supports autodiscovery of the Composer autoloader from current working directory residing in vendor/:
cd /path/to/project
phpstan analyse src tests # looks for autoloader at /path/to/project/vendor/autoload.php
If you have your dependencies installed at a different path or you're running PHPStan from a different directory, you can specify the path to the autoloader with the --autoload-file|-a option:
phpstan analyse --autoload-file=/path/to/autoload.php src tests

Exclude files from analysis
If your codebase contains some files that are broken on purpose (e. g. to test behaviour of your application on files with invalid PHP code), you can exclude them using the excludes_analyse array parameter. String at each line is used as a pattern for the fnmatchfunction.
parameters:
 excludes_analyse:
  - %rootDir%/../../../tests/*/data/*

Include custom extensions
If your codebase contains php files with extensions other than the standard .php extension then you can add them to the fileExtensions array parameter:
parameters:
 fileExtensions:
  - php
  - module
  - inc

Universal object crates
Classes without predefined structure are common in PHP applications. They are used as universal holders of data - any property can be set and read on them. Notable examples include stdClassSimpleXMLElement (these are enabled by default), objects with results of database queries etc. Use universalObjectCratesClasses array parameter to let PHPStan know which classes with these characteristics are used in your codebase:
parameters:
 universalObjectCratesClasses:
  - Dibi\Row
  - Ratchet\ConnectionInterface

Add non-obviously assigned variables to scope
If you use some variables from a try block in your catch blocks, set polluteCatchScopeWithTryAssignments boolean parameter to true.

Regards
Blog Dokter Sobri

No comments:

Post a Comment

# Silahkan berkomentar, bertanya dan kritik dengan sopan
# Disini anda boleh menyisipkan Link di kolom komentar
# Tetapi akan saya moderasi atau Review terlebih dahulu tiap komentar
# Jangan sampai komentar anda mengandung SPAM.

# Terima Kasih - Regards Muhammad Sobri Maulana