Tools for writing state-of-the-art PHP code

With a little help from my friends

Carsten Windler - Plan A

International PHP Conference 2023/10/24

Code

is

beautiful

Carsten Windler

Principal Engineer @

https://www.linkedin.com/in/cwindler

https://carstenwindler.de

https://plana.earth

What will we talk about today?

  • Coding standards
  • Static code analysis
  • Local pipeline
  • Automated refactoring
  • Dealing with legacy code

Coding standards

  • Standards for formatting code
  • Lower cognitive frictions
  • Fewer code changes
  • Focus on the important stuff

https://www.pexels.com/photo/white-ruled-paper-99562/

Which standard to chose?

  • Doesn't matter so much
  • Checked by tools
  • PSR-12

Which tool to use?

  • Automation is key
  • Force coding standards
  • Fixer

PHP-CS-Fixer

Why use an extra tool for it?

PHP-CS-Fixer

  • Analyse code without executing it
  • Identify issues
    • Bugs
    • Security vulnerabilities
    • Maintainability problems
    • Performance issues
  • Easier code reviews
  • Early in the process
    • i.e. local environment

Static code analysis

Costs of fixing a bug

PHPStan

PHPStan

PHPStan

class Vat
{
    private float $vat = 0.19;

    public function getVat(): int
    {
        return $this->vat;
    }
}

class OrderPosition
{
    public function getGrossPrice(float $netPrice): float
    {
        $vatModel = new Vat();
        $vat = $vatModel->getVat();

        return $netPrice * (1 + $vat);
    }
}

$orderPosition = new OrderPosition();
echo $orderPosition->getGrossPrice(100);
  • Prevent code messing up
  • Rulesets, e.g.
    • Clean code
    • Code size
    • Naming conventions
    • Controversial
  • Baseline feature

PHPMD

PHPMD

phpmd

class ExampleClass
{
    public function loadData(int $id): void
    {
        $user = User::find($id);

        $test = new Order();
        $order = $test->find($id);
        
        // ....
    }
}

Psalm
👉 Automatically fix issues
 

Exakat
👉 Huge rulesets
👉 Great blog
 

Phan
👉 Browser demo
 

Others

IDE extensions

IDE extensions

IDE extensions

  • Manual execution is hard 🤯
  • Typical excuses:
    • Deadlines 🤷🏻‍♂️
    • "Forgot" 🤷🏻‍♂️
    • Doesn't work for me 🤷🏻‍♂️
    • Too slow 🤷🏻‍♂️
    • I don't like it 🤷🏻‍♂️
    • It's useless crap anyway 🤷🏻‍♂️

Local pipeline

👉 Automate!

  • run checks before commit
  • fail commit if violations are detected
  • checks ordered by execution speed:
    • (PHP linter)
    • Code sniffer
      • PHP-CS-Fixer
    • Static code analysis
      • PHPStan
    • Unit tests
    • Other tests

pre-commit hook

Captain Hook

{
    "config": {
        "fail-on-first-error": true
    },
    "pre-commit": {
        "enabled": true,
        "actions": [
            {
                "action": "vendor/bin/php-cs-fixer fix --dry-run"
            },
            {
                "action": "vendor/bin/phpstan"
            }
        ]
    }
}
  • Local pipeline can be skipped
  • Typical excuses:
    • Doesn't work for me 🤷🏻‍♂️
    • I didn't get any errors 🤷🏻‍♂️
    • I don't know why it didn't run 🤷🏻‍♂️
    • Deadlines, crap, etc 🤷🏻‍♂️
  • We have to ensure that code base is kept in good shape
  • Make sure to implement checks on CI as well

Outlook: Continuous Integration

Automated refactoring

Rector

  • Coding standard can be fixed in one go
  • Automated refactoring
    • Psalm
    • Rector
    • apply on small parts of the code first
  • Start low, improve over time
    • PHPStan has rule levels

Legacy code

  • Baseline feature
    • current issues will be ignored
    • only new issues will be reported
    • auto-generate
    • downside: issues don't get fixed

Legacy code

parameters:
  ignoreErrors:
    -
      message: "#^Method Vat\\:\\:getVat\\(\\) should return int but returns float\\.$#"
      count: 1
        path: phpstan/example.php
  • Don't overdo
    • tools sometimes contradict each other
    • issues too hard to fix
  • Tools require time to configure & fine tune
    • Focus on one or two
  • Don't overwhelm the team

How much is too much?

Thank you!

https://www.pexels.com/photo/empty-photo-frame-hanging-above-cabinet-in-light-room-6373506/

This is a great book!

⭐⭐⭐⭐⭐

- Carsten W.

 👉 Buy it on Amazon 👈

Clean Code in PHP

As an AI, I am not allowed

to write fake book reviews

⭐⭐⭐⭐⭐⭐⭐

- Chad Geepety

LinkedIn Learning

Let's connect

Carsten Windler

PhpMetrics

  • Code quality metrics
  • Nice looking reports
  • Quite complex

PhpMetrics

PHP Insights 
👉 somewhere between static code analysis and metrics

PHP Depend
👉 crazy number crunching

Other tools

With a little help from my friends 2nd edition

By Carsten Windler

With a little help from my friends 2nd edition

  • 119