webmozarts / assert

Assertions to validate method input/output with nice error messages.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return validated value

dbalabka opened this issue · comments

I've faced the fact that it is required to create temporary variables to validate values:

$firstName = getParam('firstName');
$lastName = getParam('lastName');
Assert::notNull($firstName);
Assert::notNull($lastName);

createCustomer(
    $firstName,
    $lastName
);

We can rid of temporary variables if the assertion function returns a valid value:

createCustomer(
    Assert::notNull(getParam('firstName')),
    Assert::notNull(getParam('lastName'))
);

For some of the assertion functions, we can simply return the valid value. The changes should be BC-safe.

Possible implementation: #281
Psalm support demonstration: https://psalm.dev/r/a439359976

References:

  1. Similar Java implementation: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/Validate.html#notNull(T)

I'm looking for this feature as well, and this would be helpful for every method. Your example is precisely my use case. The fluent notation makes it much more cleaner to use. Your current PR is only the notNull method. Is your intention to add this to all methods? Otherwise I could also extend on this PR.

@frankdekker, I will add support for other methods as well if the maintainer accepts that such a feature is required. We should wait for @webmozart's reply.