10 Popular PHP Libraries for Static Analysis

In today's post we will learn about 10 Popular PHP Libraries for Static Analysis.

What is Static Analysis?

Static analysis is a method of debugging that is done by automatically examining the source code without having to execute the program. This provides developers with an understanding of their code base and helps ensure that it is compliant, safe, and secure.

Table of contents:

  • Exakat - A static analysis engine for PHP.
  • Deptrac - A static code analysis tool that helps to enforce rules for dependencies between software layers.
  • Mondrian - A code analysis tool using Graph Theory.
  • Phan - A static analyzer based on PHP 7+ and the php-ast extension.
  • PHP Architecture Tester - Easy to use architecture testing tool for PHP.
  • PHPCompatibility - A PHP compatibility checker for PHP CodeSniffer.
  • PHPDependencyAnalysis - A tool to create customisable dependency graphs.
  • PHP Metrics - A static metric library.
  • PHP Migration - A static analyzer for PHP version migration.
  • PHPStan - A PHP Static Analysis Tool.
  • Psalm - A static analysis tool for finding errors in PHP applications.

1 - Exakat:

A static analysis engine for PHP.

The Exakat Engine is an automated code reviewing engine for PHP.

Installation

Quick installation

Copy-paste the following code in your terminal. This was tester on OSX and Linux-debian.

mkdir exakat
cd exakat
curl -o exakat.phar https://www.exakat.io/versions/index.php?file=latest
curl -o apache-tinkerpop-gremlin-server-3.4.12-bin.zip https://www.exakat.io/versions/apache-tinkerpop-gremlin-server-3.4.12-bin.zip
unzip apache-tinkerpop-gremlin-server-3.4.12-bin.zip
mv apache-tinkerpop-gremlin-server-3.4.12 tinkergraph
rm -rf apache-tinkerpop-gremlin-server-3.4.12-bin.zip

# Optional : install neo4j engine.
cd tinkergraph
./bin/gremlin-server.sh install org.apache.tinkerpop neo4j-gremlin 3.4.12
cd ..

php exakat.phar doctor

Installation with the phar

Phar is the recommended installation process.

The Exakat engine is distributed as a phar archive. Phar contains all the needed PHP code to run it.

The rest of the installation (Gremlin-server) is detailled in the installation documentation.

The quick installation guide is the following (command line, MacOS. See docs for more options):

mkdir exakat
cd exakat
curl -o exakat.phar https://www.exakat.io/versions/index.php?file=latest
curl -o apache-tinkerpop-gremlin-server-3.4.12-bin.zip https://www.exakat.io/versions/apache-tinkerpop-gremlin-server-3.4.12-bin.zip
unzip apache-tinkerpop-gremlin-server-3.4.12-bin.zip
mv apache-tinkerpop-gremlin-server-3.4.12 tinkergraph
rm -rf apache-tinkerpop-gremlin-server-3.4.12-bin.zip

# Optional : install neo4j engine.
cd tinkergraph
./bin/gremlin-server.sh install org.apache.tinkerpop neo4j-gremlin 3.4.12
cd ..

php exakat.phar doctor

Installation with docker

The docker usage is detailled in the installation documentation.

docker pull exakat/exakat:latest

View on Github

2 - Deptrac:

A static code analysis tool that helps to enforce rules for dependencies between software layers.

Deptrac is a static code analysis tool for PHP that helps you communicate, visualize and enforce architectural decisions in your projects. You can freely define your architectural layers over classes and which rules should apply to them.

For example, you can use Deptrac to ensure that bundles/modules/extensions in your project are truly independent of each other to make them easier to reuse.

Deptrac can be used in a CI pipeline to make sure a pull request does not violate any of the architectural rules you defined. With the optional Graphviz formatter you can visualize your layers, rules and violations.

Getting Started

You can install Deptrac via Composer. We recommend using the deptrac-shim package for this:

composer require --dev qossmic/deptrac-shim

Alternatively, you can also use Phive or download the binary attached to each release on GitHub. We strongly advise against using the deptrac package directly as a composer dependency. We update dependencies regularly, which might cause disruptions in your project.

Once you have downloaded the phar file, you will need to create a configuration file, where you define your layers and communication ruleset. When you have this file, you can analyse your code by running the analyse command:

php deptrac.phar

# which is equivalent to
php deptrac.phar analyse --config-file=deptrac.yaml

In order to run Deptrac you need at least PHP 8.1.

You can analyse projects that require an older PHP version as long as nikic/php-parser can parse it.

Contribute

Deptrac is in active development. We are looking for your suggestions and help to make it better.

Feel free to open an issue if you encounter bugs, have suggestions or would like to add a new feature to Deptrac.

Please feel free to improve this documentation, fix bugs, or work on a suggested feature by making a pull request on GitHub. Don't hesitate to ask for support, if you need help at any point.

The Contribution Guide in the documentation contains some advice for making a pull request with code changes.

Code of Conduct

If you are professional and polite then everything will be alright.

Please don't be inconsiderate or mean, or anything in between.

View on Github

3 - Mondrian:

A code analysis tool using Graph Theory.

Ok guyz, you have a master degree in Graph Theory, you follow Law of Demeter and you live on S.O.L.I.D principles ?

Let's have some Fun ! (^ω^)

Getting started

Download the PHAR : mondrian.phar

Try to run a simple command with a few files (or a small part of a project)

$ mondrian.phar digraph /home/dev/project

This command produces a DOT file for GraphViz. Other formats are available :

  • html : interactive graph with the d3.js awesome library
  • svg : open standard for vector graphics (requires GraphViz)
  • json : format for d3.js for example

Example with html format

$ php mondrian.php d --ignore=tests --ignore=vendor --format=html ./MyPhpProject/

html-report

Note: The generated html file does not require any dependencies nor a connection.

Ecosystem

Running unit tests with PHPUnit

$ phpunit.phar

Building the documentation with phpDocumentor

$ phpDocumentor.phar

Building mondrian.phar from the sources with box2

$ box.phar b

View on Github

3 - Phan:

A static analyzer based on PHP 7+ and the php-ast extension.

Phan is a static analyzer for PHP that prefers to minimize false-positives. Phan attempts to prove incorrectness rather than correctness.

Phan looks for common issues and will verify type compatibility on various operations when type information is available or can be deduced. Phan has a good (but not comprehensive) understanding of flow control and can track values in a few use cases (e.g. arrays, integers, and strings).

Getting Started

The easiest way to use Phan is via Composer.

composer require phan/phan

With Phan installed, you'll want to create a .phan/config.php file in your project to tell Phan how to analyze your source code. Once configured, you can run it via ./vendor/bin/phan.

Phan 5 depends on PHP 7.2+ with the php-ast extension (1.0.16+ is preferred) and supports analyzing PHP version 7.0-8.1 syntax. Installation instructions for php-ast can be found here. (Phan can be used without php-ast by using the CLI option --allow-polyfill-parser, but there are slight differences in the parsing of doc comments)

  • Alternative Installation Methods
    See Getting Started for alternative methods of using Phan and details on how to configure Phan for your project.
     
  • Incrementally Strengthening Analysis
    Take a look at Incrementally Strengthening Analysis for some tips on how to slowly ramp up the strictness of the analysis as your code becomes better equipped to be analyzed.
     
  • Installing Dependencies
    Take a look at Installing Phan Dependencies for help getting Phan's dependencies installed on your system.

The Wiki has more information about using Phan.

Features

Phan is able to perform the following kinds of analysis:

  • Check that all methods, functions, classes, traits, interfaces, constants, properties and variables are defined and accessible.
  • Check for type safety and arity issues on method/function/closure calls.
  • Check for PHP8/PHP7/PHP5 backward compatibility.
  • Check for features that weren't supported in older PHP 7.x minor releases (E.g. object, void, iterable, ?T, [$x] = ...;, negative string offsets, multiple exception catches, etc.)
  • Check for sanity with array accesses.
  • Check for type safety on binary operations.
  • Check for valid and type safe return values on methods, functions, and closures.
  • Check for No-Ops on arrays, closures, constants, properties, variables, unary operators, and binary operators.
  • Check for unused/dead/unreachable code. (Pass in --dead-code-detection)
  • Check for unused variables and parameters. (Pass in --unused-variable-detection)
  • Check for redundant or impossible conditions and pointless casts. (Pass in --redundant-condition-detection)
  • Check for unused use statements. These and a few other issue types can be automatically fixed with --automatic-fix.
  • Check for classes, functions and methods being redefined.
  • Check for sanity with class inheritance (e.g. checks method signature compatibility). Phan also checks for final classes/methods being overridden, that abstract methods are implemented, and that the implemented interface is really an interface (and so on).
  • Supports namespaces, traits and variadics.
  • Supports Union Types.
  • Supports Generic Types (i.e. @template).
  • Supports generic arrays such as int[], UserObject[], array<int,UserObject>, etc..
  • Supports array shapes such as array{key:string,otherKey:?stdClass}, etc. (internally and in PHPDoc tags) This also supports indicating that fields of an array shape are optional via array{requiredKey:string,optionalKey?:string} (useful for @param)
  • Supports phpdoc type annotations.
  • Supports inheriting phpdoc type annotations.
  • Supports checking that phpdoc type annotations are a narrowed form (E.g. subclasses/subtypes) of the real type signatures
  • Supports inferring types from assert() statements and conditionals in if elements/loops.
  • Supports @deprecated annotation for deprecating classes, methods and functions
  • Supports @internal annotation for elements (such as a constant, function, class, class constant, property or method) as internal to the package in which it's defined.
  • Supports @suppress <ISSUE_TYPE> annotations for suppressing issues.
  • Supports magic @property annotations (@property <union_type> <variable_name>)
  • Supports magic @method annotations (@method <union_type> <method_name>(<union_type> <param1_name>))
  • Supports class_alias annotations (experimental, off by default)
  • Supports indicating the class to which a closure will be bound, via @phan-closure-scope (example)
  • Supports analysis of closures and return types passed to array_map, array_filter, and other internal array functions.
  • Offers extensive configuration for weakening the analysis to make it useful on large sloppy code bases
  • Can be run on many cores. (requires pcntl)
  • Output is emitted in text, checkstyle, json, pylint, csv, or codeclimate formats.
  • Can run user plugins on source for checks specific to your code. Phan includes various plugins you may wish to enable for your project.

View on Github

4 - PHP Architecture Tester:

Easy to use architecture testing tool for PHP.

Introduction 📜

PHP Architecture Tester is a static analysis tool to verify architectural requirements.

It provides a natural language abstraction to define your own architectural rules and test them against your software. You can also integrate phpat easily into your toolchain.

There are four groups of supported assertions: Dependency, Inheritance, Composition and Mixin.

ℹ️ Check out the section WHAT TO TEST to see some examples of typical use cases.

Installation 💽

Just require phpat with Composer:

composer require --dev phpat/phpat

Manual download
 

If you have dependency conflicts, you can also download the latest PHAR file from Releases.

You will have to use it executing php phpat.phar phpat.yaml and declare your tests in XML or YAML.

Configuration 🔧

You will need to setup a minimum configuration:

# phpat.yaml
src:
  path: src/
tests:
  path: tests/architecture/

Complete list of options
 

NameDescriptionDefault
src pathThe root path of your applicationno default
src includeFiles you want to be tested excluding the restall files
src excludeFiles you want to be excluded in the testsno files
composer $ALIAS jsonPath of your composer.json file (multiple)main json
composer $ALIAS lockPath of your composer.lock file (multiple)main lock
tests pathThe path where your tests areno default
tests baselinePath to a generated baseline fileno default
options verbosityOutput verbosity level (-1/0/1/2)0
options php-versionPHP version of the src code (x.x.x)PHP_VERSION
options ignore-docblocksIgnore relations on docblocks (T/F)false
options ignore-php-extensionsIgnore relations to core and extensions classes (T/F)true
--generate-baselineOption to generate a json baseline file (null/filename)false

View on Github

5 - PHPCompatibility:

A PHP compatibility checker for PHP CodeSniffer.

Installation in a Composer project (method 1)

  • Add the following lines to the require-dev section of your composer.json file.
"require-dev": {
    "phpcompatibility/php-compatibility": "*"
},
"prefer-stable" : true
  • Next, PHP CodeSniffer has to be informed of the location of the standard.

If PHPCompatibility is the only external PHP CodeSniffer standard you use, you can add the following to your composer.json file to automatically run the necessary command:

"scripts": {
    "post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility",
    "post-update-cmd" : "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility"
}

Alternatively - and strongly recommended if you use more than one external PHP CodeSniffer standard - you can use any of the following Composer plugins to handle this for you.

Just add the Composer plugin you prefer to the require-dev section of your composer.json file.

As a last alternative in case you use a custom ruleset, and only if you use PHP CodeSniffer version 2.6.0 or higher, you can tell PHP CodeSniffer the path to the PHPCompatibility standard by adding the following snippet to your custom ruleset:

<config name="installed_paths" value="vendor/phpcompatibility/php-compatibility" />
  • Run composer update --lock to install both PHP CodeSniffer, the PHPCompatibility coding standard and - optionally - the Composer plugin.
  • Verify that the PHPCompatibility standard is registered correctly by running ./vendor/bin/phpcs -i on the command line. PHPCompatibility should be listed as one of the available standards.
  • Now you can use the following command to inspect your code:
./vendor/bin/phpcs -p . --standard=PHPCompatibility

Installation via a git check-out to an arbitrary directory (method 2)

Install PHP CodeSniffer via your preferred method.

PHP CodeSniffer offers a variety of installation methods to suit your work-flow: Composer, PEAR, a Phar file, zipped/tarred release archives or checking the repository out using Git.

Pro-tip: Register the path to PHPCS in your system $PATH environment variable to make the phpcs command available from anywhere in your file system.

Download the latest PHPCompatibility release and unzip/untar it into an arbitrary directory.

You can also choose to clone the repository using git to easily update your install regularly.

Add the path to the directory in which you placed your copy of the PHPCompatibility repo to the PHP CodeSniffer configuration using the below command from the command line:

phpcs --config-set installed_paths /path/to/PHPCompatibility

I.e. if you placed the PHPCompatibility repository in the /my/custom/standards/PHPCompatibility directory, you will need to add that directory to the PHP CodeSniffer installed_paths configuration variable.

Warning: ⚠️ The installed_paths command overwrites any previously set installed_paths. If you have previously set installed_paths for other external standards, run phpcs --config-show first and then run the installed_paths command with all the paths you need separated by commas, i.e.:

phpcs --config-set installed_paths /path/1,/path/2,/path/3

Pro-tip: Alternatively, in case you use a custom ruleset and only if you use PHP CodeSniffer version 2.6.0 or higher, you can tell PHP CodeSniffer the path to the PHPCompatibility standard(s) by adding the following snippet to your custom ruleset:

<config name="installed_paths" value="/path/to/PHPCompatibility" />

Verify that the PHPCompatibility standard is registered correctly by running phpcs -i on the command line. PHPCompatibility should be listed as one of the available standards.

Now you can use the following command to inspect your code:

phpcs -p . --standard=PHPCompatibility

Using a custom ruleset

Like with any PHP CodeSniffer standard, you can add PHPCompatibility to a custom PHP CodeSniffer ruleset.

<?xml version="1.0"?>
<ruleset name="Custom ruleset">
    <description>My rules for PHP CodeSniffer</description>

    <!-- Run against the PHPCompatibility ruleset -->
    <rule ref="PHPCompatibility"/>

    <!-- Run against a second ruleset -->
    <rule ref="PSR2"/>

</ruleset>

You can also set the testVersion from within the ruleset:

    <!-- Check for cross-version support for PHP 5.6 and higher. -->
    <config name="testVersion" value="5.6-"/>

Other advanced options, such as changing the message type or severity of select sniffs, as described in the PHPCS Annotated ruleset wiki page are, of course, also supported.

testVersion in the ruleset versus command-line

In PHPCS 3.2.0 and lower, once you set the testVersion in the ruleset, you could not overrule it from the command-line anymore. Starting with PHPCS 3.3.0, a testVersion set via the command-line will overrule the testVersion in the ruleset.

This allows for more flexibility when, for instance, your project needs to comply with PHP 5.5-, but you have a bootstrap file which needs to be compatible with PHP 5.2-.

View on Github

6 - PHPDependencyAnalysis:

A tool to create customisable dependency graphs.

PhpDependencyAnalysis is an extendable static code analysis for object-oriented PHP-Projects to generate dependency graphs from abstract datatypes (Classes, Interfaces and Traits) based on namespaces. Dependencies can be aggregated to build graphs for several levels, like Package-Level or Layer-Level. Each dependency can be verified to a defined architecture.

Installation

As a Docker Image (recommend way)

docker pull mamuz/phpda

As a Composer Dependency

NOTE: For graph creation GraphViz is required on your machine, which is an open source graph visualization software and available for the most platforms.

$ composer require --dev mamuz/php-dependency-analysis

As a Phar

Since version 2.0.0 not supported anymore.

Features

  • High customizing level
  • Graph creation on customized levels respectively different scopes and layers
  • Supports Usage-Graph, Call-Graph and Inheritance-Graph
  • Dependencies can be aggregated such as to a package, a module or a layer
  • Detecting cycles and violations between layers in a tiered architecture
  • Verifiying dependency graph against a user-defined reference architecture
  • Collected namespaces of dependencies are modifiable to meet custom use cases
  • Printing graphs in several formats (HTML, SVG, DOT, JSON)
  • Extandable by adding user-defined plugins for collecting and displaying
  • Compatible to PHP7 Features, like Return Type Declarations and Anonymous Classes

Usage

Phpda can run out of the box by using a prepared configuration. As you can see configuration is defined by a YAML file.

To provide your own configuration create a yml file, e.g. located in ./phpda.yml:

mode: 'usage'
source: './src'
filePattern: '*.php'
ignore: 'tests'
formatter: 'PhpDA\Writer\Strategy\Svg'
target: './phpda.svg'
groupLength: 1
visitor:
  - PhpDA\Parser\Visitor\TagCollector
  - PhpDA\Parser\Visitor\SuperglobalCollector
visitorOptions:
  PhpDA\Parser\Visitor\Required\DeclaredNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\Required\MetaNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\Required\UsedNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\TagCollector: {minDepth: 2, sliceLength: 2}

Perform an analysis with that configuration:

$ docker run --rm -v $PWD:/app mamuz/phpda

Read the Configuration-Chapter to get knowledge about all available options.

View on Github

7 - PHP Metrics:

A static metric library.

PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

Quick start

Follow the quick start guide to get started. composer require phpmetrics/phpmetrics --dev php ./vendor/bin/phpmetrics --report-html=myreport

Then open the generated ./myreport/index.html file in your browser.

You can use a configuration file to customize the report, add options, configure rules for Continuous Integration, etc.

Metrics

You'll find detailed list of metrics in documentation, or running php ./vendor/bin/phpmetrics --metrics

View on Github

8 - PHP Migration:

A static analyzer for PHP version migration.

This is a static analyzer for PHP version migration and compatibility checking.

It can suppose your current code running under the new version of PHP then do checking, and provide advice and treatment.

And it can simplify the process of upgrading PHP. Its goal is instead of manual checking.

Features:

  • Wide coverage, checks most of the changes which introduced in PHP 5.3 - 7.0.
  • Strict, without missing any risk.
  • Zero configuration, run directly after download.
  • Simply add custom checks.

Compare to the similar project PHP Compatibility PHP Compatibility is a set of sniffs for PHP_CodeSniffer, therefore it lacks flexibility and can not checks more changes. just objective comparison

Notice: this project is in beta stage, feel free to report any issues.

Install / Usage

You can download a executable Phar file

wget https://github.com/monque/PHP-Migration/releases/download/v0.2.2/phpmig.phar

Use the following command to check PHP file

php phpmig.phar sample.php

Suppose these code stored in sample.php

<?php
// Fatal error: Only variables can be passed by reference
array_shift(array(1, 2));
sort(array(1, 2, 3));

// __DIR__ is pre-defined
define('__DIR__', dirname(__FILE__));

// Fatal error: Cannot redeclare class_alias()
function class_alias() {}

// This is fine
if (!function_exists('class_alias')) {
    function class_alias() {}
}

// Fatal error: Call-time pass-by-reference has been removed
array_map('trim', &$_SERVER);

// Fatal error: 'break' operator with non-constant operand is no longer supported
while (true) {
    break $a;
}

// Fatal error: Cannot re-assign auto-global variable _GET
function ohno($_GET) {}

// Array keys won't be overwritten when defining an array as a property of a class via an array literal
class C {
    const ONE = 1;
    public $array = [
        self::ONE => 'foo',
        'bar',
        'quux',
    ];
}

// set_exception_handler() is no longer guaranteed to receive Exception objects
set_exception_handler(function (Exception $e) { });

// Changes to the handling of indirect variables, properties, and methods
echo $$foo['bar']['baz'];

// foreach no longer changes the internal array pointer
foreach ($list as &$row) {
    current($list);
}

Output report Each columns means: Line Number, Level, Identified, Version, Message

File: sample.php
--------------------------------------------------------------------------------
Found 11 spot(s), 10 identified
--------------------------------------------------------------------------------
    3 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
    4 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
    7 | WARNING    | * | 5.3.0 | Constant "__DIR__" already defined
   10 | FATAL      | * | 5.3.0 | Cannot redeclare class_alias()
   18 | FATAL      | * | 5.4.0 | Call-time pass-by-reference has been removed
   22 | FATAL      | * | 5.4.0 | break operator with non-constant operand is no longer supported
   26 | FATAL      | * | 5.4.0 | Cannot re-assign auto-global variable
   31 | WARNING    |   | 5.6.0 | Array key may be overwritten when defining as a property and using constants
   39 | WARNING    | * | 7.0.0 | set_exception_handler() is no longer guaranteed to receive Exception objects
   42 | WARNING    | * | 7.0.0 | Different behavior between PHP 5/7
   46 | NOTICE     | * | 7.0.0 | foreach no longer changes the internal array pointer
--------------------------------------------------------------------------------

The third field Identified will be explained at bottom.

View on Github

9 - PHPStan:

A PHP Static Analysis Tool.

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.

Getting Started

PHPStan requires PHP >= 7.2. 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.

You can also download the latest PHAR and just use that. But without Composer, you won’t be able to install and use PHPStan extensions.

Documentation

All the documentation lives on the phpstan.org website:

View on Github

10 - Psalm:

A static analysis tool for finding errors in PHP applications.

Installation

To get started, check out the installation guide.

Live Demo

You can play around with Psalm on its website.

Documentation

Documentation is available on Psalm’s website, generated from the docs folder.

Interested in contributing?

Have a look at CONTRIBUTING.md.

View on Github

Thank you for following this article.

Related videos:

PHPLoc Lines of code static analysis to find PHP code smells

#php #static #analysis 

What is GEEK

Buddha Community

10 Popular PHP Libraries for Static Analysis
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

10 Popular PHP Libraries for Static Analysis

In today's post we will learn about 10 Popular PHP Libraries for Static Analysis.

What is Static Analysis?

Static analysis is a method of debugging that is done by automatically examining the source code without having to execute the program. This provides developers with an understanding of their code base and helps ensure that it is compliant, safe, and secure.

Table of contents:

  • Exakat - A static analysis engine for PHP.
  • Deptrac - A static code analysis tool that helps to enforce rules for dependencies between software layers.
  • Mondrian - A code analysis tool using Graph Theory.
  • Phan - A static analyzer based on PHP 7+ and the php-ast extension.
  • PHP Architecture Tester - Easy to use architecture testing tool for PHP.
  • PHPCompatibility - A PHP compatibility checker for PHP CodeSniffer.
  • PHPDependencyAnalysis - A tool to create customisable dependency graphs.
  • PHP Metrics - A static metric library.
  • PHP Migration - A static analyzer for PHP version migration.
  • PHPStan - A PHP Static Analysis Tool.
  • Psalm - A static analysis tool for finding errors in PHP applications.

1 - Exakat:

A static analysis engine for PHP.

The Exakat Engine is an automated code reviewing engine for PHP.

Installation

Quick installation

Copy-paste the following code in your terminal. This was tester on OSX and Linux-debian.

mkdir exakat
cd exakat
curl -o exakat.phar https://www.exakat.io/versions/index.php?file=latest
curl -o apache-tinkerpop-gremlin-server-3.4.12-bin.zip https://www.exakat.io/versions/apache-tinkerpop-gremlin-server-3.4.12-bin.zip
unzip apache-tinkerpop-gremlin-server-3.4.12-bin.zip
mv apache-tinkerpop-gremlin-server-3.4.12 tinkergraph
rm -rf apache-tinkerpop-gremlin-server-3.4.12-bin.zip

# Optional : install neo4j engine.
cd tinkergraph
./bin/gremlin-server.sh install org.apache.tinkerpop neo4j-gremlin 3.4.12
cd ..

php exakat.phar doctor

Installation with the phar

Phar is the recommended installation process.

The Exakat engine is distributed as a phar archive. Phar contains all the needed PHP code to run it.

The rest of the installation (Gremlin-server) is detailled in the installation documentation.

The quick installation guide is the following (command line, MacOS. See docs for more options):

mkdir exakat
cd exakat
curl -o exakat.phar https://www.exakat.io/versions/index.php?file=latest
curl -o apache-tinkerpop-gremlin-server-3.4.12-bin.zip https://www.exakat.io/versions/apache-tinkerpop-gremlin-server-3.4.12-bin.zip
unzip apache-tinkerpop-gremlin-server-3.4.12-bin.zip
mv apache-tinkerpop-gremlin-server-3.4.12 tinkergraph
rm -rf apache-tinkerpop-gremlin-server-3.4.12-bin.zip

# Optional : install neo4j engine.
cd tinkergraph
./bin/gremlin-server.sh install org.apache.tinkerpop neo4j-gremlin 3.4.12
cd ..

php exakat.phar doctor

Installation with docker

The docker usage is detailled in the installation documentation.

docker pull exakat/exakat:latest

View on Github

2 - Deptrac:

A static code analysis tool that helps to enforce rules for dependencies between software layers.

Deptrac is a static code analysis tool for PHP that helps you communicate, visualize and enforce architectural decisions in your projects. You can freely define your architectural layers over classes and which rules should apply to them.

For example, you can use Deptrac to ensure that bundles/modules/extensions in your project are truly independent of each other to make them easier to reuse.

Deptrac can be used in a CI pipeline to make sure a pull request does not violate any of the architectural rules you defined. With the optional Graphviz formatter you can visualize your layers, rules and violations.

Getting Started

You can install Deptrac via Composer. We recommend using the deptrac-shim package for this:

composer require --dev qossmic/deptrac-shim

Alternatively, you can also use Phive or download the binary attached to each release on GitHub. We strongly advise against using the deptrac package directly as a composer dependency. We update dependencies regularly, which might cause disruptions in your project.

Once you have downloaded the phar file, you will need to create a configuration file, where you define your layers and communication ruleset. When you have this file, you can analyse your code by running the analyse command:

php deptrac.phar

# which is equivalent to
php deptrac.phar analyse --config-file=deptrac.yaml

In order to run Deptrac you need at least PHP 8.1.

You can analyse projects that require an older PHP version as long as nikic/php-parser can parse it.

Contribute

Deptrac is in active development. We are looking for your suggestions and help to make it better.

Feel free to open an issue if you encounter bugs, have suggestions or would like to add a new feature to Deptrac.

Please feel free to improve this documentation, fix bugs, or work on a suggested feature by making a pull request on GitHub. Don't hesitate to ask for support, if you need help at any point.

The Contribution Guide in the documentation contains some advice for making a pull request with code changes.

Code of Conduct

If you are professional and polite then everything will be alright.

Please don't be inconsiderate or mean, or anything in between.

View on Github

3 - Mondrian:

A code analysis tool using Graph Theory.

Ok guyz, you have a master degree in Graph Theory, you follow Law of Demeter and you live on S.O.L.I.D principles ?

Let's have some Fun ! (^ω^)

Getting started

Download the PHAR : mondrian.phar

Try to run a simple command with a few files (or a small part of a project)

$ mondrian.phar digraph /home/dev/project

This command produces a DOT file for GraphViz. Other formats are available :

  • html : interactive graph with the d3.js awesome library
  • svg : open standard for vector graphics (requires GraphViz)
  • json : format for d3.js for example

Example with html format

$ php mondrian.php d --ignore=tests --ignore=vendor --format=html ./MyPhpProject/

html-report

Note: The generated html file does not require any dependencies nor a connection.

Ecosystem

Running unit tests with PHPUnit

$ phpunit.phar

Building the documentation with phpDocumentor

$ phpDocumentor.phar

Building mondrian.phar from the sources with box2

$ box.phar b

View on Github

3 - Phan:

A static analyzer based on PHP 7+ and the php-ast extension.

Phan is a static analyzer for PHP that prefers to minimize false-positives. Phan attempts to prove incorrectness rather than correctness.

Phan looks for common issues and will verify type compatibility on various operations when type information is available or can be deduced. Phan has a good (but not comprehensive) understanding of flow control and can track values in a few use cases (e.g. arrays, integers, and strings).

Getting Started

The easiest way to use Phan is via Composer.

composer require phan/phan

With Phan installed, you'll want to create a .phan/config.php file in your project to tell Phan how to analyze your source code. Once configured, you can run it via ./vendor/bin/phan.

Phan 5 depends on PHP 7.2+ with the php-ast extension (1.0.16+ is preferred) and supports analyzing PHP version 7.0-8.1 syntax. Installation instructions for php-ast can be found here. (Phan can be used without php-ast by using the CLI option --allow-polyfill-parser, but there are slight differences in the parsing of doc comments)

  • Alternative Installation Methods
    See Getting Started for alternative methods of using Phan and details on how to configure Phan for your project.
     
  • Incrementally Strengthening Analysis
    Take a look at Incrementally Strengthening Analysis for some tips on how to slowly ramp up the strictness of the analysis as your code becomes better equipped to be analyzed.
     
  • Installing Dependencies
    Take a look at Installing Phan Dependencies for help getting Phan's dependencies installed on your system.

The Wiki has more information about using Phan.

Features

Phan is able to perform the following kinds of analysis:

  • Check that all methods, functions, classes, traits, interfaces, constants, properties and variables are defined and accessible.
  • Check for type safety and arity issues on method/function/closure calls.
  • Check for PHP8/PHP7/PHP5 backward compatibility.
  • Check for features that weren't supported in older PHP 7.x minor releases (E.g. object, void, iterable, ?T, [$x] = ...;, negative string offsets, multiple exception catches, etc.)
  • Check for sanity with array accesses.
  • Check for type safety on binary operations.
  • Check for valid and type safe return values on methods, functions, and closures.
  • Check for No-Ops on arrays, closures, constants, properties, variables, unary operators, and binary operators.
  • Check for unused/dead/unreachable code. (Pass in --dead-code-detection)
  • Check for unused variables and parameters. (Pass in --unused-variable-detection)
  • Check for redundant or impossible conditions and pointless casts. (Pass in --redundant-condition-detection)
  • Check for unused use statements. These and a few other issue types can be automatically fixed with --automatic-fix.
  • Check for classes, functions and methods being redefined.
  • Check for sanity with class inheritance (e.g. checks method signature compatibility). Phan also checks for final classes/methods being overridden, that abstract methods are implemented, and that the implemented interface is really an interface (and so on).
  • Supports namespaces, traits and variadics.
  • Supports Union Types.
  • Supports Generic Types (i.e. @template).
  • Supports generic arrays such as int[], UserObject[], array<int,UserObject>, etc..
  • Supports array shapes such as array{key:string,otherKey:?stdClass}, etc. (internally and in PHPDoc tags) This also supports indicating that fields of an array shape are optional via array{requiredKey:string,optionalKey?:string} (useful for @param)
  • Supports phpdoc type annotations.
  • Supports inheriting phpdoc type annotations.
  • Supports checking that phpdoc type annotations are a narrowed form (E.g. subclasses/subtypes) of the real type signatures
  • Supports inferring types from assert() statements and conditionals in if elements/loops.
  • Supports @deprecated annotation for deprecating classes, methods and functions
  • Supports @internal annotation for elements (such as a constant, function, class, class constant, property or method) as internal to the package in which it's defined.
  • Supports @suppress <ISSUE_TYPE> annotations for suppressing issues.
  • Supports magic @property annotations (@property <union_type> <variable_name>)
  • Supports magic @method annotations (@method <union_type> <method_name>(<union_type> <param1_name>))
  • Supports class_alias annotations (experimental, off by default)
  • Supports indicating the class to which a closure will be bound, via @phan-closure-scope (example)
  • Supports analysis of closures and return types passed to array_map, array_filter, and other internal array functions.
  • Offers extensive configuration for weakening the analysis to make it useful on large sloppy code bases
  • Can be run on many cores. (requires pcntl)
  • Output is emitted in text, checkstyle, json, pylint, csv, or codeclimate formats.
  • Can run user plugins on source for checks specific to your code. Phan includes various plugins you may wish to enable for your project.

View on Github

4 - PHP Architecture Tester:

Easy to use architecture testing tool for PHP.

Introduction 📜

PHP Architecture Tester is a static analysis tool to verify architectural requirements.

It provides a natural language abstraction to define your own architectural rules and test them against your software. You can also integrate phpat easily into your toolchain.

There are four groups of supported assertions: Dependency, Inheritance, Composition and Mixin.

ℹ️ Check out the section WHAT TO TEST to see some examples of typical use cases.

Installation 💽

Just require phpat with Composer:

composer require --dev phpat/phpat

Manual download
 

If you have dependency conflicts, you can also download the latest PHAR file from Releases.

You will have to use it executing php phpat.phar phpat.yaml and declare your tests in XML or YAML.

Configuration 🔧

You will need to setup a minimum configuration:

# phpat.yaml
src:
  path: src/
tests:
  path: tests/architecture/

Complete list of options
 

NameDescriptionDefault
src pathThe root path of your applicationno default
src includeFiles you want to be tested excluding the restall files
src excludeFiles you want to be excluded in the testsno files
composer $ALIAS jsonPath of your composer.json file (multiple)main json
composer $ALIAS lockPath of your composer.lock file (multiple)main lock
tests pathThe path where your tests areno default
tests baselinePath to a generated baseline fileno default
options verbosityOutput verbosity level (-1/0/1/2)0
options php-versionPHP version of the src code (x.x.x)PHP_VERSION
options ignore-docblocksIgnore relations on docblocks (T/F)false
options ignore-php-extensionsIgnore relations to core and extensions classes (T/F)true
--generate-baselineOption to generate a json baseline file (null/filename)false

View on Github

5 - PHPCompatibility:

A PHP compatibility checker for PHP CodeSniffer.

Installation in a Composer project (method 1)

  • Add the following lines to the require-dev section of your composer.json file.
"require-dev": {
    "phpcompatibility/php-compatibility": "*"
},
"prefer-stable" : true
  • Next, PHP CodeSniffer has to be informed of the location of the standard.

If PHPCompatibility is the only external PHP CodeSniffer standard you use, you can add the following to your composer.json file to automatically run the necessary command:

"scripts": {
    "post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility",
    "post-update-cmd" : "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility"
}

Alternatively - and strongly recommended if you use more than one external PHP CodeSniffer standard - you can use any of the following Composer plugins to handle this for you.

Just add the Composer plugin you prefer to the require-dev section of your composer.json file.

As a last alternative in case you use a custom ruleset, and only if you use PHP CodeSniffer version 2.6.0 or higher, you can tell PHP CodeSniffer the path to the PHPCompatibility standard by adding the following snippet to your custom ruleset:

<config name="installed_paths" value="vendor/phpcompatibility/php-compatibility" />
  • Run composer update --lock to install both PHP CodeSniffer, the PHPCompatibility coding standard and - optionally - the Composer plugin.
  • Verify that the PHPCompatibility standard is registered correctly by running ./vendor/bin/phpcs -i on the command line. PHPCompatibility should be listed as one of the available standards.
  • Now you can use the following command to inspect your code:
./vendor/bin/phpcs -p . --standard=PHPCompatibility

Installation via a git check-out to an arbitrary directory (method 2)

Install PHP CodeSniffer via your preferred method.

PHP CodeSniffer offers a variety of installation methods to suit your work-flow: Composer, PEAR, a Phar file, zipped/tarred release archives or checking the repository out using Git.

Pro-tip: Register the path to PHPCS in your system $PATH environment variable to make the phpcs command available from anywhere in your file system.

Download the latest PHPCompatibility release and unzip/untar it into an arbitrary directory.

You can also choose to clone the repository using git to easily update your install regularly.

Add the path to the directory in which you placed your copy of the PHPCompatibility repo to the PHP CodeSniffer configuration using the below command from the command line:

phpcs --config-set installed_paths /path/to/PHPCompatibility

I.e. if you placed the PHPCompatibility repository in the /my/custom/standards/PHPCompatibility directory, you will need to add that directory to the PHP CodeSniffer installed_paths configuration variable.

Warning: ⚠️ The installed_paths command overwrites any previously set installed_paths. If you have previously set installed_paths for other external standards, run phpcs --config-show first and then run the installed_paths command with all the paths you need separated by commas, i.e.:

phpcs --config-set installed_paths /path/1,/path/2,/path/3

Pro-tip: Alternatively, in case you use a custom ruleset and only if you use PHP CodeSniffer version 2.6.0 or higher, you can tell PHP CodeSniffer the path to the PHPCompatibility standard(s) by adding the following snippet to your custom ruleset:

<config name="installed_paths" value="/path/to/PHPCompatibility" />

Verify that the PHPCompatibility standard is registered correctly by running phpcs -i on the command line. PHPCompatibility should be listed as one of the available standards.

Now you can use the following command to inspect your code:

phpcs -p . --standard=PHPCompatibility

Using a custom ruleset

Like with any PHP CodeSniffer standard, you can add PHPCompatibility to a custom PHP CodeSniffer ruleset.

<?xml version="1.0"?>
<ruleset name="Custom ruleset">
    <description>My rules for PHP CodeSniffer</description>

    <!-- Run against the PHPCompatibility ruleset -->
    <rule ref="PHPCompatibility"/>

    <!-- Run against a second ruleset -->
    <rule ref="PSR2"/>

</ruleset>

You can also set the testVersion from within the ruleset:

    <!-- Check for cross-version support for PHP 5.6 and higher. -->
    <config name="testVersion" value="5.6-"/>

Other advanced options, such as changing the message type or severity of select sniffs, as described in the PHPCS Annotated ruleset wiki page are, of course, also supported.

testVersion in the ruleset versus command-line

In PHPCS 3.2.0 and lower, once you set the testVersion in the ruleset, you could not overrule it from the command-line anymore. Starting with PHPCS 3.3.0, a testVersion set via the command-line will overrule the testVersion in the ruleset.

This allows for more flexibility when, for instance, your project needs to comply with PHP 5.5-, but you have a bootstrap file which needs to be compatible with PHP 5.2-.

View on Github

6 - PHPDependencyAnalysis:

A tool to create customisable dependency graphs.

PhpDependencyAnalysis is an extendable static code analysis for object-oriented PHP-Projects to generate dependency graphs from abstract datatypes (Classes, Interfaces and Traits) based on namespaces. Dependencies can be aggregated to build graphs for several levels, like Package-Level or Layer-Level. Each dependency can be verified to a defined architecture.

Installation

As a Docker Image (recommend way)

docker pull mamuz/phpda

As a Composer Dependency

NOTE: For graph creation GraphViz is required on your machine, which is an open source graph visualization software and available for the most platforms.

$ composer require --dev mamuz/php-dependency-analysis

As a Phar

Since version 2.0.0 not supported anymore.

Features

  • High customizing level
  • Graph creation on customized levels respectively different scopes and layers
  • Supports Usage-Graph, Call-Graph and Inheritance-Graph
  • Dependencies can be aggregated such as to a package, a module or a layer
  • Detecting cycles and violations between layers in a tiered architecture
  • Verifiying dependency graph against a user-defined reference architecture
  • Collected namespaces of dependencies are modifiable to meet custom use cases
  • Printing graphs in several formats (HTML, SVG, DOT, JSON)
  • Extandable by adding user-defined plugins for collecting and displaying
  • Compatible to PHP7 Features, like Return Type Declarations and Anonymous Classes

Usage

Phpda can run out of the box by using a prepared configuration. As you can see configuration is defined by a YAML file.

To provide your own configuration create a yml file, e.g. located in ./phpda.yml:

mode: 'usage'
source: './src'
filePattern: '*.php'
ignore: 'tests'
formatter: 'PhpDA\Writer\Strategy\Svg'
target: './phpda.svg'
groupLength: 1
visitor:
  - PhpDA\Parser\Visitor\TagCollector
  - PhpDA\Parser\Visitor\SuperglobalCollector
visitorOptions:
  PhpDA\Parser\Visitor\Required\DeclaredNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\Required\MetaNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\Required\UsedNamespaceCollector: {minDepth: 2, sliceLength: 2}
  PhpDA\Parser\Visitor\TagCollector: {minDepth: 2, sliceLength: 2}

Perform an analysis with that configuration:

$ docker run --rm -v $PWD:/app mamuz/phpda

Read the Configuration-Chapter to get knowledge about all available options.

View on Github

7 - PHP Metrics:

A static metric library.

PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

Quick start

Follow the quick start guide to get started. composer require phpmetrics/phpmetrics --dev php ./vendor/bin/phpmetrics --report-html=myreport

Then open the generated ./myreport/index.html file in your browser.

You can use a configuration file to customize the report, add options, configure rules for Continuous Integration, etc.

Metrics

You'll find detailed list of metrics in documentation, or running php ./vendor/bin/phpmetrics --metrics

View on Github

8 - PHP Migration:

A static analyzer for PHP version migration.

This is a static analyzer for PHP version migration and compatibility checking.

It can suppose your current code running under the new version of PHP then do checking, and provide advice and treatment.

And it can simplify the process of upgrading PHP. Its goal is instead of manual checking.

Features:

  • Wide coverage, checks most of the changes which introduced in PHP 5.3 - 7.0.
  • Strict, without missing any risk.
  • Zero configuration, run directly after download.
  • Simply add custom checks.

Compare to the similar project PHP Compatibility PHP Compatibility is a set of sniffs for PHP_CodeSniffer, therefore it lacks flexibility and can not checks more changes. just objective comparison

Notice: this project is in beta stage, feel free to report any issues.

Install / Usage

You can download a executable Phar file

wget https://github.com/monque/PHP-Migration/releases/download/v0.2.2/phpmig.phar

Use the following command to check PHP file

php phpmig.phar sample.php

Suppose these code stored in sample.php

<?php
// Fatal error: Only variables can be passed by reference
array_shift(array(1, 2));
sort(array(1, 2, 3));

// __DIR__ is pre-defined
define('__DIR__', dirname(__FILE__));

// Fatal error: Cannot redeclare class_alias()
function class_alias() {}

// This is fine
if (!function_exists('class_alias')) {
    function class_alias() {}
}

// Fatal error: Call-time pass-by-reference has been removed
array_map('trim', &$_SERVER);

// Fatal error: 'break' operator with non-constant operand is no longer supported
while (true) {
    break $a;
}

// Fatal error: Cannot re-assign auto-global variable _GET
function ohno($_GET) {}

// Array keys won't be overwritten when defining an array as a property of a class via an array literal
class C {
    const ONE = 1;
    public $array = [
        self::ONE => 'foo',
        'bar',
        'quux',
    ];
}

// set_exception_handler() is no longer guaranteed to receive Exception objects
set_exception_handler(function (Exception $e) { });

// Changes to the handling of indirect variables, properties, and methods
echo $$foo['bar']['baz'];

// foreach no longer changes the internal array pointer
foreach ($list as &$row) {
    current($list);
}

Output report Each columns means: Line Number, Level, Identified, Version, Message

File: sample.php
--------------------------------------------------------------------------------
Found 11 spot(s), 10 identified
--------------------------------------------------------------------------------
    3 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
    4 | FATAL      | * | 5.3.0 | Only variables can be passed by reference
    7 | WARNING    | * | 5.3.0 | Constant "__DIR__" already defined
   10 | FATAL      | * | 5.3.0 | Cannot redeclare class_alias()
   18 | FATAL      | * | 5.4.0 | Call-time pass-by-reference has been removed
   22 | FATAL      | * | 5.4.0 | break operator with non-constant operand is no longer supported
   26 | FATAL      | * | 5.4.0 | Cannot re-assign auto-global variable
   31 | WARNING    |   | 5.6.0 | Array key may be overwritten when defining as a property and using constants
   39 | WARNING    | * | 7.0.0 | set_exception_handler() is no longer guaranteed to receive Exception objects
   42 | WARNING    | * | 7.0.0 | Different behavior between PHP 5/7
   46 | NOTICE     | * | 7.0.0 | foreach no longer changes the internal array pointer
--------------------------------------------------------------------------------

The third field Identified will be explained at bottom.

View on Github

9 - PHPStan:

A PHP Static Analysis Tool.

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.

Getting Started

PHPStan requires PHP >= 7.2. 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.

You can also download the latest PHAR and just use that. But without Composer, you won’t be able to install and use PHPStan extensions.

Documentation

All the documentation lives on the phpstan.org website:

View on Github

10 - Psalm:

A static analysis tool for finding errors in PHP applications.

Installation

To get started, check out the installation guide.

Live Demo

You can play around with Psalm on its website.

Documentation

Documentation is available on Psalm’s website, generated from the docs folder.

Interested in contributing?

Have a look at CONTRIBUTING.md.

View on Github

Thank you for following this article.

Related videos:

PHPLoc Lines of code static analysis to find PHP code smells

#php #static #analysis 

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website?

HourlyDeveloper.io has always been an industry leader for companies and business owners looking to hire PHP web developer. By choosing to Hire PHP Developer from our company, you can always expect the best results. Our PHP services and solutions are always flexible which means that no matter the nature of your project, you can always count on us for getting the best PHP expertise.

Consult with our experts: https://bit.ly/3aEGxPy

#hire php developer #php developer #php development company #php development services #php development #php

Hire PHP Developer - Best PHP Web Frameworks for Web Development

A framework that can drastically cut down the requirement to write original code to develop the web apps as per your requirement is PHP Framework. PHP frameworks offer code libraries for commonly used functions to reduce the development time.

Want to use PHP Web Frameworks for your web applications?

WebClues Infotech offers a service to hire dedicated PHP developers for all of the below-mentioned frameworks

  • Laravel Developer
  • Codeigniter Developer
  • Yii Developer
  • Zend Developer
  • Cake PHP Developer
  • Core PHP Developer

Not sure which framework to use for your PHP web application?

Contact us

Schedule Interview with PHP Developer https://bit.ly/3dsTWf0

Email: sales@webcluesinfotech.com

#hire php developer #hire php web developers #hire php developer in 2021 #hire php developers & dedicated php programmers #hire php developers india #hire and outsource freelance php developers

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers?

Hire Dedicated PHP Developer, who can convert your idea to reality, within the stipulated time frame. HourlyDeveloper.io expertise & experience as the top PHP development company put us above our competitors, in many ways. We have some of the top PHP developers in the industry, which can create anything you can imagine, that too, at the most competitive prices.

Consult with our experts:- https://bit.ly/2NpKnB8

#hire dedicated php developer #php developers #php development company #php development services #php development #php developer