Sorting by

×

A use case for the `value-of` PHPDoc type

Tips

On a recent project, I was building up a configuration object that would be stored in a json field in the database.

Some records would require more configuration options than others, but I wanted to restrict it so that the keys in this json object had to be values from a particular enum.

Let’s say the enum looked like this:

enum Configuration: string {
    case DAILY = 'daily';
    case WEEKLY = 'weekly';
    case MONTHLY = 'monthly';
}

And now let’s say we had a function that allowed you to manipulate keys and values in this configuration object:

/**
* @param value-of<Configuration> $key
*/
function setConfigurationValue(string $key, string $value): void {
    // ...
}

Notice that PHPDoc type above the function. By tightening the type from just any string to a specific value in our Configuration enum, now tooling like PHPStan can catch us if we ever try to pass in a value that doesn’t match one of the enum cases.

PHP doesn’t give us a native type to do this, but these PHPDoc types can be very helpful in getting far more expressive in defining types. And we can do it without writing a bunch of guard clauses inside the function body.

Here to help,

Joel

P.S. Want help setting up PHPStan in your project?

Tags:

Comments are closed

Latest Comments
No comments to show.