webmozarts / assert

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Assert integer or string - safe array keys

Isinlor opened this issue · comments

Hello,

PHP Documentation says:

The key can either be an integer or a string. The value can be of any type.
Additionally the following key casts will occur: (...)

I want to propose a new assertion that will make sure that a value can be safely used as a key in an array. By safely I mean that there will be no key casts and therefore no unexpected key collisions.

I'm not sure how to name it. Be more indicative of the intention or the implementation?

Assert::safeArrayKey()
Assert::allSafeArrayKey()

vs.

Assert::integerOrString()
Assert::allIntegerOrString()

Any comments? I'm happy to make a pull request.

What about Assert::string((string) $value));. That would be save to use as an array key, right?

The only possible conflict are with boolean and null. true gives 1 as key, false gives 0 and null the empty string.
So the assertion would fail if a pair is present in an array or if one of them is given as tested value?
What would be the use case?

My specific use case that prompted me to propose this feature is as follows.

I have a tool, a fairly complex one, where a programmer can set up constraints on different relationships. It is conceptually easy to make a relationship like that ['entityType' => someId, 'entityType2' => someId2]. But for performance reasons I need to make it programmatically easily searchable like so $hashMap['entityType'][someId]['entityType'][someId2]. Therefore I want to be sure that programmer won't mess up using false for lack of entity of given type and 0 for an actual id etc.

The general use case is this:

Assert::allSafeArrayKey($keys);
array_combine($keys, $values);

BTW - According to the documentation of array_combine:

Array of keys to be used. Illegal values for key will be converted to string.

So it will convert true to string '1' not to integer 1. You can see that it is a minefield.

There is also another posibility of an issue (objects implementing __toString() should not be keys): https://3v4l.org/65sEb

I'd be okay with validArrayKey. It should work together nicely with psalms array-key pseudo type

Fixed By #140