consistence/consistence

Better type check for arrays

Closed this issue · 2 comments

Currently when you check for types of values in array you use something like:

Type::checkType($cars, Car::class . '[]');

I dislike that the check is dependent on the appended string. I propose to add new method Type::checkTypeOfAll($traversable, MyClass::class);. This will first ensure that the variable is traversable. And if so, that all the values of it are of correct type.

If it's OK, I'd be happy to send PR.

I agree, that I don't like writing this either, but I don't have much problems with readability of this. With this proposed solution I think this cosmetic issue could be solved, but I am afraid there would emerge some confusions:

  1. You can check deeper arrays, such as string[][], ofc you could do that with this method as well, just remove one "level" of [], but that is what I think might be more confusing. When you combine it with the class example, you get to the same problem as before:
Type::checkTypeOfAll($traversable, MyClass::class . '[]');
// which would then be the same as
Type::checkType($traversable, MyClass::class . '[][]');

and you might get very easily confused about the depth of the field.

  1. You can use union types with defining the check, so you might use something like string[]|integer[] which cannot be translated in any way (currently) to the proposed method, because checking all values for integer|value would be something different.

So I get the motivation, but as I showed above in the examples I don't think this will improve the overall situation. After all this syntax is string based, so there will always be usecases needing some sort of string manipulation.

I understand your points and agree.