Running static analysis tools for PHP

We all write bug free code but analyzing your code is still important part of software development if for some reason there could've been some mishap with typing. Here's a short introduction how to run static analysis for PHP code.

Static analysis tools for PHP

The curated list of static analysis tools for PHP show you many options for doing analysis. Too much you say? Yes but fortunately you can start with some tools and continue with the specific needs you have.

You can run different analysis tools by installing them with composer or you can use the Toolbox which helps to discover and install tools. You can use it as a Docker container.

First, fetch the docker image with static analysis tools for PHP:

$ docker pull jakzal/phpqa:<your php version>
e.g.
$ docker pull jakzal/phpqa:php7.4-alpine

PHPMD: PHP Mess Detector

One of the tools provided in the image is PHPMD which aims to be a PHP equivalent of the well known Java tool PMD. PHPMD can be seen as an user friendly and easy to configure frontend for the raw metrics measured by PHP Depend.

It looks for several potential problems within that source like:

  • Possible bugs
  • Suboptimal code
  • Overcomplicated expressions
  • Unused parameters, methods, properties

You can install the phpmd with composer: composer require phpmd/phpmd. Then run it with e.g. ./vendor/bin/phpmd src html unusedcode --reportfile phpmd.html

Or run the command below which runs phpmd in a docker container and mounts the current working directory as a /project.

docker run -it --rm -v $(pwd):/project -w /project jakzal/phpqa:php7.4-alpine \
    phpmd src html cleancode,codesize,controversial,design,naming,unusedcode --reportfile phpmd.html

You can also make your custom rules to reduce false positives: phpmd.test.xml

<?xml version="1.0"?>
<ruleset name="VV PHPMD rule set"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
                     http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="
                     http://pmd.sf.net/ruleset_xml_schema.xsd">
    <description>
        Custom rule set that checks my code.
    </description>
<rule ref="rulesets/codesize.xml">
    <exclude name="CyclomaticComplexity"/>
    <exclude name="ExcessiveMethodLength"/>
    <exclude name="NPathComplexity"/>
    <exclude name="TooManyMethods"/>
    <exclude name="ExcessiveClassComplexity"/>
    <exclude name="ExcessivePublicCount"/>
    <exclude name="TooManyPublicMethods"/>
    <exclude name="TooManyFields"/>
</rule>
<rule ref="rulesets/codesize.xml/TooManyFields">
    <properties>
        <property name="maxfields" value="21"/>
    </properties>
</rule>
<rule ref="rulesets/cleancode.xml">
    <exclude name="StaticAccess"/>
    <exclude name="ElseExpression"/>
    <exclude name="MissingImport" />
</rule>
<rule ref="rulesets/controversial.xml">
    <exclude name="CamelCaseParameterName" />
    <exclude name="CamelCaseVariableName" />
    <exclude name="Superglobals" />
</rule>
<rule ref="rulesets/design.xml">
    <exclude name="CouplingBetweenObjects" />
    <exclude name="NumberOfChildren" />
</rule>
<rule ref="rulesets/design.xml/NumberOfChildren">
    <properties>
        <property name="minimum" value="20"/>
    </properties>
</rule>
<rule ref="rulesets/naming.xml">
    <exclude name="ShortVariable"/>
    <exclude name="LongVariable"/>
</rule>
<rule ref="rulesets/unusedcode.xml">
    <exclude name="UnusedFormalParameter"/>
</rule>
<rule ref="rulesets/codesize.xml/ExcessiveClassLength">
    <properties>
        <property name="minimum" value="1500"/>
    </properties>
</rule>
</ruleset>

Then run your analysis with:

docker run -it --rm -v $(pwd):/project -w /project jakzal/phpqa:php7.4-alpine phpmd src html phpmd.test.xml unusedcode --reportfile phpmd.html

You get a list of found issues formatted to a HTML file

PHPMD Report

PHPStan - 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."

Installing with composer: composer require --dev phpstan/phpstan

Or run on Docker container:

docker run -it --rm -v $(pwd):/project -w /project jakzal/phpqa:php7.4-alpine phpstan analyse --level 1 src

By default you will get a report to console formatted to a table and grouped errors by file, colorized. For human consumption.

PHPStan report

By default PHPStan is performing only the most basic checks and you can pass a higher rule level through the --level option (0 is the loosest and 8 is the strictest) to analyse code more thoroughly. Start with 0 and increase the level as you go fixing possible issues.

PHPStan found some more issues which PHPMD didn't find but the output of the PHPStan could be better. There's a Web UI for browsing found errors and you can click and open your editor of choice on the offending line but you've to pay for it. PHPStan Pro costs 7 EUR for individuals monthly, 70 EUR for teams.

VS Code extension for PHP

If you're using Visual Studio Code for PHP programming there are some extensions to help you.

PHP Intelephense
PHP code intelligence for Visual Studio Code provides better intellisense then VS Code builtin and also does some signature checking etc. The extension has also premium version for some additional features.

Short notes on tech 4/2021

It's already week 4 of 2021 😱 This week the short notes is a bit bigger edition recapping the three first weeks of 2021.

Week 4, 2021

Web-End

Progressive Web Apps in 2021
So far it's been a slow start for PWA. The thing is, they're pretty hard to deploy or retrofit into existing websites. But I expect new stacks will ship with PWA support and at some point they'll become the default choice, the tide will turn (from Weekend Reading)

User stories that should never exist
Twitter account with 😂 user stories.

Choosing a stack of low-code solutions by Jason Lengstorf
"This is a really good thread about choosing a stack of low-code solutions" (from Weekend Reading)

Exploring Rootless Docker
"With the release of Docker 20.10, the rootless containers feature has left experimental status. This post explores setup and usability of rootless Docker." (from Cloud Security Reading List)

Programming

naming-cheatsheet
"A cheetsheet for naming variable and function names. The styling here is JavaScript, but you can adapt these rules to any other language." (from Weekend Reading)

Worklife

No Meetings, No Deadlines, No Full-Time Employees
"What if work was like open source?"

HR is not your friend, and other things I think you should know
"I think people go into HR with the ideal of helping, and in the beginning it's all fun and office parties. By the time they realize that HR is “The Department for Mitigating Legal Risk”, it's too late." (from Weekend Reading) (Hacker News comments)

Cloud

How to Enable Logging on Every AWS Service in Existence (Circa 2021)
"Cloud security best practices, as well as most compliance programs, require that logging be enabled for all in-scope services. However, that simple requirement - enable logging - comes with many follow-up questions. Is CloudTrail enough? How do I turn on logging for all these services? Aren't logs collected by default?" (from Cloud Security Reading List)

What You Need to Know About AWS Security Monitoring, Logging, and Alerting
"Post laying out the different AWS security monitoring and logging sources, how to collect logs from them, and how to select the most appropriate collection technique." (from Cloud Security Reading List)

AWS announces forks of Elasticsearch and Kibana
"Elastic will change their software licensing strategy from the Apache License, Version 2.0 (ALv2) to the Elastic License (which limits how it can be used) or the Server Side Public License (which has requirements that make it unacceptable to many in the open source community). This means that Elasticsearch and Kibana will no longer be open source software. In order to ensure open source versions of both packages remain available and well supported we are announcing that AWS will step up to create and maintain a ALv2-licensed fork of open source Elasticsearch and Kibana."

Tools of the trade

Hush
"Noiseless browsing". This is a tiny app that blocks nags to accept cookies and privacy invasive tracking. Safari only, macOS/iOS, open source, so maybe you can port it to Android/Chrome. Free. (from Weekend Reading)

Scott Hanselman's 2021 Ultimate Developer and Power Users Tool List for Windows

Signal, Telegram, WhatsApp and other apps, what’s the difference?
Ola Bini's Twitter thread of giving an overview about perspective on the security of different applications.

Altair
"GraphQL client app with tons of features."

cloudfour/lighthouse-parade
"Command line tool that crawls a domain and gathers lighthouse performance data for every page." (from Weekend Reading)

OpenScan – open-source document scanner app

Upptime – GitHub-powered uptime monitor and status page

Something different

I logged my activities at 15-minute intervals for the whole year
"Where does the time go?" Log it and find out. (Hacker News comments)

Monthly Notes 55

It's a new year and let's start it with Monthly notes. Something new and something old from the short tech notes. Let this year be good!

Issue 55, 5.1.2021

Tools of the trade

Awesome CI
List of Continuous Integration services. There's a bunch of them to choose, my favorites are: GitHub Actions, Circle CI, Google Cloud Build, Drone CI.

Alternatives to JIRA which is moving to cloud only:
Asana
ClickUp
Linear
Redmine

Ignore node_modules in BackBlaze

PostgREST
"PostgREST serves a fully RESTful API from any existing PostgreSQL database. It provides a cleaner, more standards-compliant, faster API than you are likely to write from scratch." (from hackernewsletter)

alyssaxuu/screenity
"Screenity is a feature-packed screen and camera recorder for Chrome. Annotate your screen to give feedback, emphasize your clicks, edit your recording, and much more." (from Weekend Reading)

Foam
"Foam is a personal knowledge management and sharing system inspired by Roam Research, built on Visual Studio Code and GitHub."

Web Development

Integrate the Web Share API into our websites
"Use the Web Share API instead of these ugly lists of social icons. We should take care that our products support the native frameworks to make the web a better place." (from WDRL 285)

Sass vars, CSS vars, and semantic theme vars
"How we should define semantic variable names in the age of light and dark themes." (from WDRL 285)

Apple now lets us integrate Face ID and Touch ID on the web
"Building it on top of the Web Authentication API. Imagine how this can improve the logging in experience for a good part of your user base."

Work life

A Day in the Life of an Engineering Manager
"Engineering Manager is one of the roles that most people don’t know exactly what it’s about and what these people do. Karl Hughes explains what he does all day and it turns out it’s a role full of soft skills like networking, explaining things or translating between two people, between company departments and to raise awareness around delivery, around process management and recruiting as well as people’s happiness in their jobs." (from WDRL 285)

Development

Collection of tips for note taking by Dr. Sam Ladner
"This is a great collection of tips for note taking. For user research, design reviews, board meetings, whatever". (from Weekend Reading)

How to Make Your Code Reviewer Fall in Love with You
"Value your reviewer’s time". tl;dr; Start with these and read the article for more:

  • Review your own code first
  • Write a clear changelist description
  • Automate the easy stuff
  • Answer questions with the code itself
  • Narrowly scope changes
  • Separate functional and non-functional changes
  • Break up large changelists

Cloud

Monitoring & securing AWS with Microsoft
"Interesting approach, how to setup (advanced) monitoring of AWS with Azure Security Center (CSPM), Azure Defender (CWPP), Cloud App Security (CASB), and Azure Sentinel (SIEM)." (from Cloud Security Reading List)

Learning

How I read books: setting up a new system
"Knowledge is much more valuable when we can act on it, and change our behavior."
tl;dr; Active learning / reading; Processing and reflecting; Repeating; Presenting; Taking action. (from HackerNewsletter)

Things you're allowed to do
"This is a list of things you’re allowed to do that you thought you couldn’t, or didn’t even know you could."