1665741120
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 depends on PHP 7.2+ with the php-ast extension (1.0.10+ is preferred) and supports analyzing PHP version 7.0-7.4 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
)See Phan Issue Types for descriptions and examples of all issues that can be detected by Phan. Take a look at the \Phan\Issue to see the definition of each error type.
Take a look at the Tutorial for Analyzing a Large Sloppy Code Base to get a sense of what the process of doing ongoing analysis might look like for you.
Phan can be used from various editors and IDEs for its error checking, "go to definition" support, etc. via the Language Server Protocol. Editors and tools can also request analysis of individual files in a project using the simpler Daemon Mode.
See the tests directory for some examples of the various checks.
Phan is imperfect and shouldn't be used to prove that your PHP-based rocket guidance system is free of defects.
Additional analysis features have been provided by plugins.
{ throw new Exception("Message"); return $value; }
)*printf()
format strings against the provided arguments (as well as checking for common errors)preg_*()
are valid@suppress
annotations that are no longer needed.Example: Phan's plugins for self-analysis.
Usage
After installing Phan, Phan needs to be configured with details on where to find code to analyze and how to analyze it. The easiest way to tell Phan where to find source code is to create a .phan/config.php
file. A simple .phan/config.php
file might look something like the following.
<?php
/**
* This configuration will be read and overlaid on top of the
* default configuration. Command line arguments will be applied
* after this file is read.
*/
return [
// Supported values: `'5.6'`, `'7.0'`, `'7.1'`, `'7.2'`, `'7.3'`, `'7.4'`, `null`.
// If this is set to `null`,
// then Phan assumes the PHP version which is closest to the minor version
// of the php executable used to execute Phan.
"target_php_version" => null,
// A list of directories that should be parsed for class and
// method information. After excluding the directories
// defined in exclude_analysis_directory_list, the remaining
// files will be statically analyzed for errors.
//
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
'src',
'vendor/symfony/console',
],
// A directory list that defines files that will be excluded
// from static analysis, but whose class and method
// information should be included.
//
// Generally, you'll want to include the directories for
// third-party code (such as "vendor/") in this list.
//
// n.b.: If you'd like to parse but not analyze 3rd
// party code, directories containing that code
// should be added to the `directory_list` as
// to `exclude_analysis_directory_list`.
"exclude_analysis_directory_list" => [
'vendor/'
],
// A list of plugin files to execute.
// Plugins which are bundled with Phan can be added here by providing their name
// (e.g. 'AlwaysReturnPlugin')
//
// Documentation about available bundled plugins can be found
// at https://github.com/phan/phan/tree/master/.phan/plugins
//
// Alternately, you can pass in the full path to a PHP file
// with the plugin's implementation (e.g. 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php')
'plugins' => [
// checks if a function, closure or method unconditionally returns.
// can also be written as 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php'
'AlwaysReturnPlugin',
'DollarDollarPlugin',
'DuplicateArrayKeyPlugin',
'DuplicateExpressionPlugin',
'PregRegexCheckerPlugin',
'PrintfCheckerPlugin',
'SleepCheckerPlugin',
// Checks for syntactically unreachable statements in
// the global scope or function bodies.
'UnreachableCodePlugin',
'UseReturnValuePlugin',
'EmptyStatementListPlugin',
'LoopVariableReusePlugin',
],
];
Take a look at Creating a Config File and Incrementally Strengthening Analysis for more details.
Running phan --help
will show usage information and command-line options.
Phan reads and understands most PHPDoc type annotations including Union Types (like int|MyClass|string|null
) and generic array types (like int[]
or string[]|MyClass[]
or array<int,MyClass>
).
Take a look at Annotating Your Source Code and About Union Types for some help getting started with defining types in your code.
Phan supports (int|string)[]
style annotations, and represents them internally as int[]|string[]
(Both annotations are treated like array which may have integers and/or strings). When you have arrays of mixed types, just use array
.
The following code shows off the various annotations that are supported.
/**
* @return void
*/
function f() {}
/** @deprecated */
class C {
/** @var int */
const C = 42;
/** @var string[]|null */
public $p = null;
/**
* @param int|null $p
* @return string[]|null
*/
public static function f($p) {
if (is_null($p)) {
return null;
}
return array_map(
/** @param int $i */
function($i) {
return "thing $i";
},
range(0, $p)
);
}
}
Just like in PHP, any type can be nulled in the function declaration which also means a null is allowed to be passed in for that parameter.
Phan checks the type of every single element of arrays (Including keys and values). In practical terms, this means that [$int1=>$int2,$int3=>$int4,$int5=>$str6]
is seen as array<int,int|string>
, which Phan represents as array<int,int>|array<int,string>
. [$strKey => new MyClass(), $strKey2 => $unknown]
will be represented as array<string,MyClass>|array<string,mixed>
.
[12,'myString']
will be represented internally as array shapes such as array{0:12,1:'myString'}
Generating a file list
This static analyzer does not track includes or try to figure out autoloader magic. It treats all the files you throw at it as one big application. For code encapsulated in classes this works well. For code running in the global scope it gets a bit tricky because order matters. If you have an index.php
including a file that sets a bunch of global variables and you then try to access those after the include(...)
in index.php
the static analyzer won't know anything about these.
In practical terms this simply means that you should put your entry points and any files setting things in the global scope at the top of your file list. If you have a config.php
that sets global variables that everything else needs, then you should put that first in the list followed by your various entry points, then all your library files containing your classes.
Development
Take a look at Developer's Guide to Phan for help getting started hacking on Phan.
When you find an issue, please take the time to create a tiny reproducing code snippet that illustrates the bug. And once you have done that, fix it. Then turn your code snippet into a test and add it to tests then ./test
and send a PR with your fix and test. Alternatively, you can open an Issue with details.
To run Phan's unit tests, just run ./test
.
To run all of Phan's unit tests and integration tests, run ./tests/run_all_tests.sh
Code of Conduct
We are committed to fostering a welcoming community. Any participant and contributor is required to adhere to our Code of Conduct.
Online Demo
This requires an up to date version of Firefox/Chrome and at least 4 GB of free RAM. (this is a 10 MB download)
Run Phan entirely in your browser.
Author: Phan
Source Code: https://github.com/phan/phan
License: Unknown and 3 other licenses found
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
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
1613990718
ValueCoders is a leading PHP app development company that focuses on building robust, secure & scalable web applications for start-ups, enterprises, and entrepreneurs.
We have 16+ years of experience and have delivered custom PHP web development solutions to 2500+ global clients catering industry verticals, including healthcare, adtech, eLearning, data analysis, Fintech, eCommerce, etc
#hire php developer #hire a php developer in india #hire dedicated php programmers #hire php coders #php developer in india #php developers for hire
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