Collection 实例上没有这样的功能,您可以做的最接近的是:
- 检查它是否有一个钥匙
has()
- 检查它是否包含一些值
contains()
- 还有其他方法可以检查是否存在,但是
如果你需要灵感,可以通过 Laravel 实现的方式来assertJsonStructure()
获得/Illuminate/Foundation/Testing/TestResponse.php
:
/**
* Assert that the response has a given JSON structure.
*
* @param array|null $structure
* @param array|null $responseData
* @return $this
*/
public function assertJsonStructure(array $structure = null, $responseData = null)
{
if (is_null($structure)) {
return $this->assertJson($this->json());
}
if (is_null($responseData)) {
$responseData = $this->decodeResponseJson();
}
foreach ($structure as $key => $value) {
if (is_array($value) && $key === '*') {
PHPUnit::assertInternalType('array', $responseData);
foreach ($responseData as $responseDataItem) {
$this->assertJsonStructure($structure['*'], $responseDataItem);
}
} elseif (is_array($value)) {
PHPUnit::assertArrayHasKey($key, $responseData);
$this->assertJsonStructure($structure[$key], $responseData[$key]);
} else {
PHPUnit::assertArrayHasKey($value, $responseData);
}
}
return $this;
}
如您所见,如果存在子结构,则会进行递归调用来检查结构。
更新:
作为解决您问题的基本测试,我修改了assertJsonStructure()
to haveassertArrayStructure()
和这个工作测试:
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$collect = collect(['name' => '1', 'detail' => ['age' => 1,'class' => 'abc']]);
$this->assertArrayStructure(['name', 'detail' => ['class', 'age']], $collect->toArray());
}
/**
* Assert the array has a given structure.
*
* @param array $structure
* @param array $arrayData
* @return $this
*/
public function assertArrayStructure(array $structure, array $arrayData)
{
foreach ($structure as $key => $value) {
if (is_array($value) && $key === '*') {
$this->assertInternalType('array', $arrayData);
foreach ($arrayData as $arrayDataItem) {
$this->assertArrayStructure($structure['*'], $arrayDataItem);
}
} elseif (is_array($value)) {
$this->assertArrayHasKey($key, $arrayData);
$this->assertArrayStructure($structure[$key], $arrayData[$key]);
} else {
$this->assertArrayHasKey($value, $arrayData);
}
}
return $this;
}