webmozarts / assert

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use allKeyExists assertion?

jhaoda opened this issue · comments

Trying this

$data = ['one' => 1, 'two' => 2];

Assert::allKeyExists($data, ['one', 'two']);

//array_key_exists() expects parameter 2 to be array, integer given in Assert.php on line 891
//[internal function]: Webmozart\Assert\Assert::keyExists(1, Array)

and this

$data = ['one' => 1, 'two' => 2];

Assert::allKeyExists(['one', 'two'], $data);

//array_key_exists() expects parameter 2 to be array, string given in Assert.php on line 891
//[internal function]: Webmozart\Assert\Assert::keyExists('one', Array)

I'm one of dumbest man on Earth or this method has a bug?

allKeyExists works a bit different than you expect. The All in this case doesn't mean that all the keys you provide exists, it means that the key you provide exists on all the arrays.
e.g. this would pass
Webmozart\Assert\Assert::allKeyExists([['one '=> 1], [ 'one' => 2] ] ,'one');

and this would fail.
Webmozart\Assert\Assert::allKeyExists([['one '=> 1], [ 'two' => 2] ] ,'one');

@BackEndTea oh, i'm read the description (Assert that key exists in an array for all values.) for this method in beberlei/assert and have no question any more. Thanks!

Honestly, I had the same problem 😅 For those who want determine if all required keys exist, here's how to do it:

Assertion::allChoicesNotEmpty([$yourData], ['key1', 'key2']);

(and yeah, looks like I'm using different assertion library too 😂 but the allKeyExists method name is the same and it works the same)