Skip to content

[feat] Make nullable variables optional warnings #411

Description

@DarkGhostHunter

Description

I don't know if it's a limitation of PHPantom or Mago itself, but sometimes inside a context a value that is no longer considered null gets considered as null|mixed (like null|string).

When that variable is used in a function, PHPantom throws:

Argument 1 ($password) expects string, got null|string (null does not satisfy string) (phpantom type_mismatch_argument)

For example:

if ($password !== null && ! is_string($password)) {
    throw new UnexpectedValueException('The configured certificate password must be a string or null.');
}

// At this point, we know `$password` is not null

return DigitalCertificate::fromString($password, $this->openSsl, $rut);
//                                    ^^^^^^^^^  Argument 1 ($password) expects string, got null|string (null does not satisfy string) (phpantom type_mismatch_argument)

Use case

Sometimes variables can be null or have mixed types that PHPantom will scream about it, forcing the user casting the variable unnecessarily.

Imagine code full of (string), (int) and $foo ?: throw...

Proposed solution

It would depend on how PHPantom can detect if a variable is no longer null on the given context. It will depend on implementors:

a) Rework the null analysis of variables on the context so detection can be done dynamically.
b) Demote type_mismatch_argument into a warning that can be toggled on config.
c) Transform that into its own rule (e.g. null_variable) and let it be disabled by default.

Alternatives considered

No response

Code example

/**
 * Resolve the configured single-issuer certificate.
 */
protected function resolveFromConfig(): ?DigitalCertificate
{
    $password = $this->config->get('certificate.password');

    if ($password !== null && ! is_string($password)) {
        throw new UnexpectedValueException('The configured certificate password must be a string or null.');
    }

    return DigitalCertificate::fromString($password, $this->openSsl);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions