Question

I am trying to obtain a key from an array that Codeception is pulling back through it's REST module, more specifically, the 'grabDataFromJsonResponse' method. I would like to pull the first key from that array, as the grabDataFromJsonResponse function lets me select in far enough to only return the data I need. However, Codeception seems to convert it to an object, and thus, I get the wrong key. Below is a codesample, as well as a sample (top of) an array object that Codeception is returning:

 public function returningArrayKey(WebGuy $I)
{
    $I->sendPOST(mypostdata);
    $I->seeResponseCodeIs(200);
    $I->seeResponseContains("Success");
    $jsonListingObj = $I->grabDataFromJsonResponse("tree.traversing.traversed");
    $I->checkAgainstKey("123456789", key($jsonListingObj));

}

The function checkAgainstKey simply does an AssertEquals:

function compareListingId($listingId, $oJsonObjectData)
{
    $this->assertEquals($listingId, $oJsonObjectData);
}

However, the assertEquals will always fail, because the first key is as follows:

  Codeception\Maybe Object
  (
  [position:protected] => 0
  [val:protected] => Array
      (
          [123456] => Array
              (    etc.

Using key() as above returns 'position:protected'. How can I dig into the array and return 123456? The array key represented by 123456 will be dynamic based on the REST response.

Thanks!

Was it helpful?

Solution

The final solution was to cast the object as an array, slice the array (because Codeception's Maybe object converted to an array adds public properties and such that we want to strip), and pull the key desired:

$jsonListingObj = $I->grabDataFromJsonResponse("tree.traversing.traversed");
$jsonListingArray = (array)$jsonListingObj;
$JSONParsed = key(current(array_slice($jsonListingArray, 1,1)));

$JSONParsed then returns '123456' in the example above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top