Home > OS >  Laravel - Assert json array ids using wildcard
Laravel - Assert json array ids using wildcard

Time:08-20

In my application I have a response like this:

{
  "items": [
    {
      "id": 10,
      "field": "foo"
    },
    {
      "id": 20,
      "field": "bar"
    }
  ]
}

I need to test the content of items and validate each id.

I've tried many solutions but no one works, for example (this is just a kind of pseudo-code):

assertJson(fn (AssertableJson $json) =>
    $json->where('items.*.id', [10, 20])
)

Is there a way to use a wildcard to pick every ID and validate using an array?

CodePudding user response:

You can use array_filter:

$idArray = [10, 20];

$myObj = json_decode($json); // Turn JSON to obj
$items = $myObj["items"]; // Get items from object

// Filter the items for items that aren't in the ID list
$invalidItems = array_filter($items, function ($el) {
    // If the item has an id which isn't in the array, return true
    return !in_array($el["id"], $idArray);
});

// This returns true if we found 0 items with IDs not in the ID list
return $invalidItems == [];

You can similarly use array_map to simplify your array, then compare it to your ID array:

$myObj = json_decode($json); // Turn JSON to obj
$items = $myObj["items"]; // Get items from object

$outIdArray = array_map(function($el) {
    return $el["id"];
}, $items);

// Compare $outIdArray to [10, 20]

CodePudding user response:

Not tested yet but below should work.

We attach an each on each child element under items and add a callback to where on that id key of each child.

<?php

assertJson(fn (AssertableJson $json) =>
    $json->each('items', fn (AssertableJson $childJson) => 
                $childJson->where('id', fn($idVal) => 
                        in_array($idVal, [10,20])
                    )
        )
)
  • Related