Boost PHP Code Quality with Psalm: Complete Static Analysis Guide

This guide explains how Psalm, a PHP static analysis tool, improves code quality by detecting type errors, logical bugs, and security issues, and covers its key features, installation steps, configuration options, IDE integration, automated fixes, and reasons to choose it over alternatives.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Boost PHP Code Quality with Psalm: Complete Static Analysis Guide

Overview

Psalm is a static analysis tool for PHP that inspects the abstract syntax tree (AST) without executing code. It detects type mismatches, logical contradictions, uninitialized properties, and security‑relevant taint flows, helping developers catch bugs early.

Installation

Require the package with Composer composer require --dev vimeo/psalm Generate a default configuration ./vendor/bin/psalm --init Run an analysis of the whole project ./vendor/bin/psalm --no-cache Optional: use the official Docker image

docker run -v $PWD:/app --rm -it ghcr.io/danog/psalm:latest /composer/vendor/bin/psalm --no-cache

Core Features

Strong type checking

Psalm reads native type hints and PHPDoc annotations (@var, @param, @return). When a type cannot be inferred it is reported as mixed. Mismatched calls are flagged, for example:

<?php
$a = ['foo', 'bar'];
// Incorrect order: implode expects the separator first.
echo implode($a, ' ');
// Psalm error: Argument 1 of implode expects string, array given

Template (generic) types

Using the @template annotation, developers can describe generic containers. Psalm then infers concrete return types from the supplied template arguments.

<?php
/** @template T */
class MyContainer {
    /** @var T */
    private $value;
    /** @param T $value */
    public function __construct($value) { $this->value = $value; }
    /** @return T */
    public function getValue() { return $this->value; }
}

/** @return MyContainer<int> */
function makeIntContainer(): MyContainer {
    return new MyContainer(42);
}
// Psalm infers that getValue() returns int

IDE integration

Psalm ships with a Language Server Protocol (LSP) server. When configured in VS Code, PhpStorm, Emacs, or other LSP‑compatible editors, it provides real‑time diagnostics, go‑to‑definition, and hover information without leaving the editor.

Automated fixes & refactoring

Many issue types can be corrected automatically. For instance, type‑mismatch warnings can be fixed with:

./vendor/bin/psalm --alter --issues=InvalidArgument

Configuration

Psalm reads an XML file named psalm.xml. A minimal configuration that scans the src directory looks like:

<?xml version="1.0"?>
<psalm>
    <projectFiles>
        <directory name="src" />
    </projectFiles>
    <errorLevel>1</errorLevel> <!-- 1 = most strict, 8 = most lenient -->
    <reportMixedIssues>true</reportMixedIssues>
    <useDocblockTypes>true</useDocblockTypes>
</psalm>

Key options:

errorLevel : numeric strictness (1‑most strict, 8‑most lenient).

reportMixedIssues : whether to emit warnings for mixed types.

useDocblockTypes : enable reading of PHPDoc type annotations (default: true).

Why choose Psalm?

More precise logical analysis than many alternatives (e.g., detection of contradictory conditions such as if ($a && !$a)).

Extensible via Composer plugins that add framework‑specific type information.

Supports SARIF output for integration with CI pipelines and other analysis tools.

Conclusion

Psalm provides comprehensive static analysis for PHP projects of any size. Its combination of strict type checking, generic type support, IDE integration, and automated fixing makes it a practical choice for improving code reliability and reducing runtime defects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerIDE integrationcode qualityPHPstatic analysistype checkingPsalm
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.