1663737660
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:
A static analysis engine for PHP.
The Exakat Engine is an automated code reviewing engine for PHP.
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
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
The docker usage is detailled in the installation documentation.
docker pull exakat/exakat:latest
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.
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.
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.
If you are professional and polite then everything will be alright.
Please don't be inconsiderate or mean, or anything in between.
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 ! (^ω^)
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 :
$ php mondrian.php d --ignore=tests --ignore=vendor --format=html ./MyPhpProject/
Note: The generated html file does not require any dependencies nor a connection.
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
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)
The Wiki has more information about using Phan.
Features
Phan is able to perform the following kinds of analysis:
object
, void
, iterable
, ?T
, [$x] = ...;
, negative string offsets, multiple exception catches, etc.)--dead-code-detection
)--unused-variable-detection
)--redundant-condition-detection
)use
statements. These and a few other issue types can be automatically fixed with --automatic-fix
.@template
).int[]
, UserObject[]
, array<int,UserObject>
, etc..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
)@deprecated
annotation for deprecating classes, methods and functions@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.@suppress <ISSUE_TYPE>
annotations for suppressing issues.@property <union_type> <variable_name>
)@method <union_type> <method_name>(<union_type> <param1_name>)
)class_alias
annotations (experimental, off by default)@phan-closure-scope
(example)array_map
, array_filter
, and other internal array functions.pcntl
)Easy to use architecture testing tool for PHP.
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.
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.
You will need to setup a minimum configuration:
# phpat.yaml
src:
path: src/
tests:
path: tests/architecture/
Complete list of options
Name | Description | Default |
---|---|---|
src path | The root path of your application | no default |
src include | Files you want to be tested excluding the rest | all files |
src exclude | Files you want to be excluded in the tests | no files |
composer $ALIAS json | Path of your composer.json file (multiple) | main json |
composer $ALIAS lock | Path of your composer.lock file (multiple) | main lock |
tests path | The path where your tests are | no default |
tests baseline | Path to a generated baseline file | no default |
options verbosity | Output verbosity level (-1/0/1/2) | 0 |
options php-version | PHP version of the src code (x.x.x) | PHP_VERSION |
options ignore-docblocks | Ignore relations on docblocks (T/F) | false |
options ignore-php-extensions | Ignore relations to core and extensions classes (T/F) | true |
--generate-baseline | Option to generate a json baseline file (null/filename) | false |
A PHP compatibility checker for PHP CodeSniffer.
require-dev
section of your composer.json
file."require-dev": {
"phpcompatibility/php-compatibility": "*"
},
"prefer-stable" : true
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" />
composer update --lock
to install both PHP CodeSniffer, the PHPCompatibility coding standard and - optionally - the Composer plugin../vendor/bin/phpcs -i
on the command line. PHPCompatibility should be listed as one of the available standards../vendor/bin/phpcs -p . --standard=PHPCompatibility
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
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-lineIn 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-
.
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.
docker pull mamuz/phpda
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
Since version 2.0.0 not supported anymore.
Return Type Declarations
and Anonymous Classes
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.
A static metric library.
PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.
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.
You'll find detailed list of metrics in documentation, or running php ./vendor/bin/phpmetrics --metrics
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:
Compare to the similar project PHP Compatibility
PHP Compatibility
is a set of sniffs forPHP_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.
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.
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.
All the documentation lives on the phpstan.org website:
A static analysis tool for finding errors in PHP applications.
To get started, check out the installation guide.
You can play around with Psalm on its website.
Documentation is available on Psalm’s website, generated from the docs folder.
Have a look at CONTRIBUTING.md.
Thank you for following this article.
PHPLoc Lines of code static analysis to find PHP code smells
1604008800
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.”
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.
Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:
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:
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., 7
, Bob
, 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
1663737660
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:
A static analysis engine for PHP.
The Exakat Engine is an automated code reviewing engine for PHP.
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
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
The docker usage is detailled in the installation documentation.
docker pull exakat/exakat:latest
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.
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.
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.
If you are professional and polite then everything will be alright.
Please don't be inconsiderate or mean, or anything in between.
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 ! (^ω^)
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 :
$ php mondrian.php d --ignore=tests --ignore=vendor --format=html ./MyPhpProject/
Note: The generated html file does not require any dependencies nor a connection.
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
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)
The Wiki has more information about using Phan.
Features
Phan is able to perform the following kinds of analysis:
object
, void
, iterable
, ?T
, [$x] = ...;
, negative string offsets, multiple exception catches, etc.)--dead-code-detection
)--unused-variable-detection
)--redundant-condition-detection
)use
statements. These and a few other issue types can be automatically fixed with --automatic-fix
.@template
).int[]
, UserObject[]
, array<int,UserObject>
, etc..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
)@deprecated
annotation for deprecating classes, methods and functions@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.@suppress <ISSUE_TYPE>
annotations for suppressing issues.@property <union_type> <variable_name>
)@method <union_type> <method_name>(<union_type> <param1_name>)
)class_alias
annotations (experimental, off by default)@phan-closure-scope
(example)array_map
, array_filter
, and other internal array functions.pcntl
)Easy to use architecture testing tool for PHP.
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.
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.
You will need to setup a minimum configuration:
# phpat.yaml
src:
path: src/
tests:
path: tests/architecture/
Complete list of options
Name | Description | Default |
---|---|---|
src path | The root path of your application | no default |
src include | Files you want to be tested excluding the rest | all files |
src exclude | Files you want to be excluded in the tests | no files |
composer $ALIAS json | Path of your composer.json file (multiple) | main json |
composer $ALIAS lock | Path of your composer.lock file (multiple) | main lock |
tests path | The path where your tests are | no default |
tests baseline | Path to a generated baseline file | no default |
options verbosity | Output verbosity level (-1/0/1/2) | 0 |
options php-version | PHP version of the src code (x.x.x) | PHP_VERSION |
options ignore-docblocks | Ignore relations on docblocks (T/F) | false |
options ignore-php-extensions | Ignore relations to core and extensions classes (T/F) | true |
--generate-baseline | Option to generate a json baseline file (null/filename) | false |
A PHP compatibility checker for PHP CodeSniffer.
require-dev
section of your composer.json
file."require-dev": {
"phpcompatibility/php-compatibility": "*"
},
"prefer-stable" : true
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" />
composer update --lock
to install both PHP CodeSniffer, the PHPCompatibility coding standard and - optionally - the Composer plugin../vendor/bin/phpcs -i
on the command line. PHPCompatibility should be listed as one of the available standards../vendor/bin/phpcs -p . --standard=PHPCompatibility
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
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-lineIn 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-
.
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.
docker pull mamuz/phpda
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
Since version 2.0.0 not supported anymore.
Return Type Declarations
and Anonymous Classes
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.
A static metric library.
PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.
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.
You'll find detailed list of metrics in documentation, or running php ./vendor/bin/phpmetrics --metrics
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:
Compare to the similar project PHP Compatibility
PHP Compatibility
is a set of sniffs forPHP_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.
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.
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.
All the documentation lives on the phpstan.org website:
A static analysis tool for finding errors in PHP applications.
To get started, check out the installation guide.
You can play around with Psalm on its website.
Documentation is available on Psalm’s website, generated from the docs folder.
Have a look at CONTRIBUTING.md.
Thank you for following this article.
PHPLoc Lines of code static analysis to find PHP code smells
1597820991
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
1617276472
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
Not sure which framework to use for your PHP web application?
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
1593154878
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