PhpMetrics

Documentation

Five minutes from here to your first report.

Install

Pick whichever fits the way you work. They all give you the same phpmetrics command.

Add it to your project as a development dependency:

composer require --dev phpmetrics/phpmetrics

The command is then vendor/bin/phpmetrics. To install it once for every project, use composer global require phpmetrics/phpmetrics and make sure Composer's global bin directory is in your $PATH.

A single file with PHP built in. Nothing else to install, not even PHP.

# Linux x86_64. Also available: linux-arm, macos-arm64, macos-x86_64, windows-x86_64.exe
curl -fsSL -o phpmetrics https://github.com/phpmetrics/PhpMetrics/releases/latest/download/phpmetrics-linux-x86_64
chmod +x phpmetrics && sudo mv phpmetrics /usr/local/bin/

Every binary is attached to the latest release.

Needs PHP 7.4 or later. The phar bundles its own dependencies, so it never conflicts with your project's.

curl -fsSL -o phpmetrics https://github.com/phpmetrics/PhpMetrics/releases/latest/download/phpmetrics.phar
chmod +x phpmetrics && sudo mv phpmetrics /usr/local/bin/

PhpMetrics ships through its own tap, on macOS and Linux:

brew tap phpmetrics/phpmetrics
brew trust --tap phpmetrics/phpmetrics
brew install phpmetrics

Recent Homebrew versions refuse formulae from a tap they do not know, hence brew trust. On older versions that command does not exist and you can skip it. Homebrew pulls in PHP if you do not have it.

curl -fsSL -o phpmetrics.deb https://github.com/phpmetrics/PhpMetrics/releases/latest/download/phpmetrics.deb
sudo dpkg -i phpmetrics.deb

Your first report

Point PhpMetrics at your source folder and tell it where to write the report:

phpmetrics --report-html=report src

The terminal prints a summary. The full report is in report/index.html: open it in your browser.

Start with the circles on the overview page. Each one is a class, sized by cyclomatic complexity and coloured by maintainability index. The large red ones are where your next bug is most likely to come from.

Several folders? Separate them with a comma or a space: phpmetrics --report-html=report src,lib. Folders such as vendor, tests and node_modules are skipped by default.

Options

OptionWhat it does
--report-html=<dir>Writes the HTML report into this folder.
--report-json=<file>Every metric of every class, as JSON.
--report-summary-json=<file>Project-wide averages and totals only, as JSON.
--report-csv=<file>One line per class, as CSV.
--report-violations=<file>Violations as XML, in the PMD format most CI tools read.
--config=<file>Reads options from a YAML, JSON or INI file. See Configuration.
--exclude=<dirs>Folders to skip, comma separated. Replaces the default list instead of adding to it.
--extensions=<list>File extensions to analyse. Default: php,inc.
--composer[=<path|false>]Checks your Composer dependencies against Packagist. false disables it and keeps the analysis fully offline. A path points to a composer.json outside the analysed folders.
--git[=<binary>]Adds metrics from the Git history.
--junit[=<file>]Reads a JUnit report to see which classes your tests reach.
--metricsLists every metric PhpMetrics computes.
--quietPrints nothing.
--versionPrints the version.

Configuration

Once you pass more than three options, put them in a file at the root of your project and run phpmetrics --config=phpmetrics.yml. Paths are relative to the file.

includes:                 # folders and files to analyse
  - src
excludes:                 # regular expressions of paths to skip
  - tests
extensions: [php, inc]
composer: true            # false keeps the analysis offline

report:
  html: build/phpmetrics/
  json: build/phpmetrics.json
  csv: build/phpmetrics.csv
  violations: build/violations.xml

plugins:
  git:
    binary: git
  junit:
    file: build/junit.xml

JSON and INI files take the same keys.

Continuous integration

A report tells you where the code is today. A search makes sure it does not get worse. Describe a pattern you never want to see again, set failIfFound, and PhpMetrics exits with an error the day someone writes it.

searches:
  Repository calling a service:
    type: class               # class or interface
    nameMatches: ".*Repository.*"
    usesClasses:
      - ".*Service"
    failIfFound: true

  Class too complex:
    type: class
    ccn: ">=10"
    failIfFound: true

  Class with too many responsibilities:
    type: class
    lcom: ">=3"
    failIfFound: true

  Controller talking to the database:
    type: class
    nameMatches: ".*Controller.*"
    usesClasses:
      - ".*Connection.*"
    failIfFound: true

A search combines a name (nameMatches), a parent (instanceOf), dependencies (usesClasses) and thresholds on any class metric listed under Metrics, written as ">=10" or "<50". Every condition must hold for a class to match.

For your CI dashboard, add --report-violations=build/violations.xml. Besides your searches, the file lists what PhpMetrics flags on its own: blob classes, classes or methods too complex, classes too long, probably bugged, too dependent, and packages breaking the stable dependencies or stable abstractions principles.

Groups

Large projects are made of layers. Groups give each layer its own report, so the controllers are not drowned out by the domain:

groups:
  - name: Controller
    match: "!controller!i"   # regular expression on the class name
  - name: Component
    match: "!component!i"

Metrics

Each metric below has a key, the name used in the JSON and CSV reports and in searches. Run phpmetrics --metrics to list them from your terminal.

Cyclomatic complexity

ccn ccnMethodMax wmc

The number of paths through a piece of code. Every if, loop, case or boolean operator adds one. Each path is a case to test, and a place for a bug. ccnMethodMax is the most complex method of the class; wmc (weighted method count) is the sum over all methods. Getters and setters are left out.

Maintainability index

mi mIwoC commentWeight

A score that blends size, complexity and Halstead volume into one number. The report paints a class green above 85, amber down to 69, red below: past that point, every change costs more than it should.

MIwoC = 171 − 5.2 × ln(average volume) − 0.23 × average CCN − 16.2 × ln(average LOC)
commentWeight = 50 × sin(√(2.4 × comment ratio))
mi = MIwoC + commentWeight

Lack of cohesion of methods

lcom

The number of groups of methods that share no property and never call each other. At 1, the class does one thing. At 3, it is probably three classes in one coat. Getters and setters are left out.

Coupling

afferentCoupling efferentCoupling instability

Afferent coupling counts the classes that depend on this one: its responsibility. Efferent coupling counts the classes it depends on: its exposure to change. Instability is the ratio of the two, from 0 (everyone relies on it, so it must not move) to 1 (nothing relies on it, change it freely).

instability = Ce / (Ce + Ca)

Halstead

length vocabulary volume difficulty effort level bugs time intelligentContent

Maurice Halstead counted operators (+, =, function calls) and operands (variables, constants) to estimate how much a program says and how hard it is to read. With n1 and n2 the distinct operators and operands, N1 and N2 their total occurrences:

vocabulary n = n1 + n2
length N = N1 + N2
volume V = N × log2(n)
difficulty D = (n1 / 2) × (N2 / n2)
effort E = D × V
time T = E / 18 seconds
bugs B = V / 3000

Card and Agresti

relativeStructuralComplexity relativeDataComplexity relativeSystemComplexity and their total variants

How hard a class is to understand from the outside. Structural complexity grows with the square of the number of methods it calls (fan-out). Data complexity grows with the values passed in and out. System complexity is their sum.

structural = fan-out²
data = input/output variables / (fan-out + 1)

Kan's defects

kanDefect

An estimate of defects from the control structures in use.

kanDefect = 0.15 + 0.23 × do-while + 0.22 × switch + 0.07 × if

Size

loc cloc lloc nbMethods nbMethodsPublic nbMethodsPrivate nbMethodsGetter nbMethodsSetters

loc counts every line, cloc the comment lines, lloc the logical lines of code. nbMethods leaves getters and setters out, nbMethodsIncludingGettersSetters keeps them.

Inheritance depth

depthOfInheritanceTree

How many parents a class has before reaching the root. Every level is behaviour you inherit without seeing it.

ClassRank

pageRank

Google's PageRank, applied to the dependencies between your classes. A high rank marks a class that many important classes rely on. It is neither good nor bad, but a bug there travels far.