Prepare your PHP Code for Static Analysis
Tags: php, phpstan
Published: 2021-10-20 07:09:16

---
title: Prepare your PHP Code for Static Analysis
published: true
date: 2020-12-13 01:28:00 UTC
tags: PHP,phpstan
canonical_url: http://suckup.de/2020/12/prepare-your-php-code-for-static-analysis/?pk_campaign=feed&pk_kwd=prepare-your-php-code-for-static-analysis&utm_source=rss&utm_medium=rss&utm_campaign=prepare-your-php-code-for-static-analysis
---

[Prepare your PHP Code for Static Analysis](http://suckup.de/2020/12/prepare-your-php-code-for-static-analysis/?pk_campaign=feed&pk_kwd=prepare-your-php-code-for-static-analysis)

Three years ago I got a new job as PHP developer, before that I called myself web developer because I build ReactJS, jQuery, CSS, HTML, … and PHP  stuff for a web agency. So now I am a full-time PHP developer and I converted a non typed  (no PHPDoc + no native types) project with ~ 10.000 classes into a project with ~ 90% type coverage. Here is what I have learned.

#### 1. Write code with IDE autocompletion support.

If you have autocompletion in the IDE most likely the Static Analysis can understand the code as well. 

_Example:_

bad:

`->get('DB_Connection', true, false);`

still bad:

`->get(DB_Connection::class);`

good:

`getDbConnection(): DB_Connection`

#### 2. Magic in Code is bad for the long run!

Magic methods (\_\_get, \_\_set, …) for example can help to implement new stuff very fast, but the problem is nobody will understand it, you will have no autocompletion, no refactoring options, other developers will need more time to read and navigate in the code and in the end it will cost you much more time than you can save with it.

#### 3. Break the spell on Magic Code …

… by explaining to everyone (Devs > IDE > Tools) what it does.

_Example 1:_

We use a simple Active Record Pattern, but we put all SQL stuff into the Factory classes, so that the Active Record class can be simple. ([Example](https://github.com/voku/phpstorm_issue_53352/tree/master/src/App/modules/Foo/libs)) But because of missing support for Generics we had no autocompletion without adding many dummy methods into the classes. So one of my first steps was to introduce a “[PhpCsFixer](https://gist.github.com/voku/3aba12eb898dfa209a787c398a331f9c)” that automatically adds the missing methods of the parent class with the correct types via “@method”-comments into these classes. 

_Example 2:_

Sometimes you can use more modern [PHPDocs](https://suckup.de/2020/02/modern-phpdoc-annotations/) to explain the function. Take a look at the “array\_first” function in the linked Post.

_Example 3:_

```
/**
 * Return an array which has the Property-Values of the given Objects as Values.
 *
 * @param object[] $ObjArray
 * @param string $PropertyName
 * @param null|string $KeyPropertyName if given uses this Property as key for the returned Array otherwise the keys from the
 * given array are used
 *
 * @throws Exception if no property with the given name was found
 *
 * @return array
 */
function propertyArray($ObjArray, $PropertyName, $KeyPropertyName = null): array {
    // init
    $PropertyArray = [];

    foreach ($ObjArray as $key => $Obj) {
        if (!\property_exists($Obj, $PropertyName)) {
            throw new Exception('No Property with Name ' . $PropertyName . ' in Object Found - Value');
        }

        $usedKey = $key;
        if ($KeyPropertyName) {
            if (!\property_exists($Obj, $KeyPropertyName)) {
                throw new Exception('No Property with Name ' . $PropertyName . ' in Object Found - Key');
            }
            $usedKey = $Obj->{$KeyPropertyName};
        }

        $PropertyArray[$usedKey] = $Obj->{$PropertyName};
    }

    return $PropertyArray;
}
```

Sometimes it’s hard to describe the specific output types, so here you need to extend the  functions of your Static Code Analyze Tool, so that it knows what you are doing. ⇾ [for example here you can find a solution for PHPStan](https://gist.github.com/voku/80722c9310c21719fbcfbfeb565cc6f9) ⇽  but there is still no support for the IDE and so maybe it’s not the best idea to use magic like that at all. And I am sure it’s more simple to use specific and simple methods instead:  e.g. `BillCollection->getBillDates()`

#### 4. Try to not use strings for the code.

Strings are simple and flexible, but they are also bad for the long run. Mostly strings are used because it looks like a simple solution, but often they are redundant, you will have typos everywhere and the IDE and/or Static Analysis can’t analyze them because it’s just text.

_Example:_

bad: 

```
AjaxEditDate::generator($bill->bill_id, $bill->date, 'Bill', 'date');
```

- “Bill” ⇾ is not needed here, we can call e.g. `get_class($bill)` in the “generator” method
- “date” ⇾ is not needed here, we can [fetch the property](https://github.com/voku/phpstorm_issue_53352/blob/master/src/Framework/ActiveRecord/ActiveRow.php#L37) name from the class
- “$bill->bill\_id” ⇾ is not needed here, we can get the primary id value from the class

good:

```
AjaxEditDate::generator($bill, $bill->m()->date);
```

#### 5. Automate stuff via git hook and check it via CI server.

Fixing bad code is only done if you disallow the same bad code for the future. With a pre-commit hook for git it’s simple to run these checks, but you need to check it again in the CI server because the developers can simply skip these checks.

_Example:_

I introduced a check for disallowing global variables (global $foo && $GLOBALS[‘foo’]) via “[PHP\_CodeSniffer](https://gist.github.com/voku/d7d530ce2c072f5b4bdaafb040d1eb55)”. 

_Links:_

- [git-scm.com: git hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)
- [CaptainHook: git hook library for php](https://github.com/captainhookphp/captainhook)

#### 6. Use array shapes (or collections) if you need to return an array, please.

[Array shapes](https://phpstan.org/writing-php-code/phpdoc-types#array-shapes) are like arrays but with fixed keys, so that you can define the types of each key in the PHPDocs.

You will have [autocompletion for the IDE](https://plugins.jetbrains.com/plugin/9927-deep-assoc-completion) + all other devs can see what the method will return + you will notice if you’re better retuning an object because it will be very hard to describe the output for complex data structures and Static Analysis can use and check the types. 

_Example:_

```
/**
 * @return array{
 * missing: array<ShoppingCartLib::TAB_*,string>,
 * disabled: array<ShoppingCartLib::TAB_*,string>
 * }
 */
private static function getShoppingCartTabStatus(): array {
 ...
}
```
 ![](https://suckup.de/piwik/piwik.php?idsite=1&rec=1&url=http%3A%2F%2Fsuckup.de%2F2020%2F12%2Fprepare-your-php-code-for-static-analysis%2F%3Fpk_campaign%3Dfeed%26pk_kwd%3Dprepare-your-php-code-for-static-analysis&action_name=Prepare+your+PHP+Code+for+Static+Analysis&urlref=http%3A%2F%2Fsuckup.de%2Ffeed%2F)
[![](http://feeds.feedburner.com/~ff/suckup?i=iewEVUala9E:f9FxkRJv-IQ:NOtau7UU-s0)](http://feeds.feedburner.com/~ff/suckup?a=iewEVUala9E:f9FxkRJv-IQ:NOtau7UU-s0) [![](http://feeds.feedburner.com/~ff/suckup?d=yIl2AUoC8zA)](http://feeds.feedburner.com/~ff/suckup?a=iewEVUala9E:f9FxkRJv-IQ:yIl2AUoC8zA) [![](http://feeds.feedburner.com/~ff/suckup?d=qj6IDK7rITs)](http://feeds.feedburner.com/~ff/suckup?a=iewEVUala9E:f9FxkRJv-IQ:qj6IDK7rITs) [![](http://feeds.feedburner.com/~ff/suckup?d=I9og5sOYxJI)](http://feeds.feedburner.com/~ff/suckup?a=iewEVUala9E:f9FxkRJv-IQ:I9og5sOYxJI) [![](http://feeds.feedburner.com/~ff/suckup?i=iewEVUala9E:f9FxkRJv-IQ:-BTjWOF_DHI)](http://feeds.feedburner.com/~ff/suckup?a=iewEVUala9E:f9FxkRJv-IQ:-BTjWOF_DHI)
 ![](http://feeds.feedburner.com/~r/suckup/~4/iewEVUala9E)