Psalm is a static analysis tool that attempts to dig into your program and find as many type-related bugs as possible.
It has a few features that go further than other similar tools:
-
Mixed type warnings
If Psalm cannot infer a type for an expression then it uses amixed
placeholder type.mixed
types can sometimes mask bugs, so keeping track of them helps you avoid a number of common pitfalls. -
Intelligent logic checks
Psalm keeps track of logical assertions made about your code, soif ($a && $a) {}
andif ($a && !$a) {}
are both treated as issues. Psalm also keeps track of logical assertions made in prior code paths, preventing issues likeif ($a) {} elseif ($a) {}
. -
Property initialisation checks
Psalm checks that all properties of a given object have values after the constructor is called. -
Taint analysis
Psalm can detect security vulnerabilities in your code. -
Language Server
Psalm has a Language Server that’s compatible with a range of different IDEs. -
Automatic fixes
Psalm can fix many of the issues it finds automatically. -
Automatic refactoring
Psalm can also perform simple refactors from the command line.
Given a file implode_strings.php
:
<?php
$a = ['foo', 'bar'];
echo implode($a, ' ');
> ./vendor/bin/psalm implode_strings.php
ERROR: InvalidArgument - somefile.php:3:14 - Argument 1 of implode expects `string`, `array` provided (see https://psalm.dev/004)
There are two main inspirations for Psalm:
- Etsy's Phan, which uses nikic's php-ast extension to create an abstract syntax tree
- Facebook's Hack, a PHP-like language that supports many advanced typing features natively, so docblocks aren't necessary.
- Running Psalm:
- Annotating code:
- Manipulating code: