webmozarts / assert

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implements interface throws an exception if used on `null` value

mamazu opened this issue · comments

If you want to check if a variable $value implements an interface you need to do two checks:

Assert::notNull($value);
Assert::implementsInterface($value, $className);

Wouldn't it be better if the implementsInterface also checks for null values? Currently I am using the isInstanceOf with an interface class.

I think there are use cases for both scenarios, requiring an interface and allowing null or disallowing it. In modern PHP you'd typehint anway, making only Assert::notNull() necessary.

Anyway, it could be implemented similar to what is already available:

@method static void nullOrIsInstanceOf($value, $class, $message = '')

Implemented as part of __callStatic() methods could look like this:

@method static void notNullAndIsInstanceOf($value, $class, $message = '')

The case I am using it in is when inheriting from a base class that doesn't have any hinting so I have to make assertions to check the type.

But your suggestion looks good. I'd be interested in implementing it or do you want to do it?

It is quite straight forward to implement, only test cases are some effort. But the question is if it gets merged anyway as the project doesn't seem to be all that well maintained at the moment.

Indeed, this method should (in my opinion), throw and \InvalidArgumentException if provided with something that is not an object, or a string.

This could be done by adding a check that the value provided is either of those here: https://github.com/webmozart/assert/blob/2bff8aa9dbb0c91f15e58ac50e72a87c9769b18a/src/Assert.php#L933

A test for this was added in #137 , but it looks like we cant reproduce an error here.
The check produces an InvalidArgumentException when null is passed.

Does the issue still exist for you?

Should this be closed?

Yes, looks like there are tests for it now.