数组
格式化字符串
{
$result = Arr::normalize('hello');
$json = <<<'eot'
[
"hello"
]
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
格式化分隔字符串
public function testNormalizeSplitString(): void
{
$result = Arr::normalize('hello,world');
$json = <<<'eot'
[
"hello",
"world"
]
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
格式化数组
public function testNormalizeArr(): void
{
$result = Arr::normalize(['hello', 'world']);
$json = <<<'eot'
[
"hello",
"world"
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
格式化数组不过滤空格
{
$result = Arr::normalize(['hello', 'world', ' ', '0'], ',', true);
$json = <<<'eot'
[
"hello",
"world",
" "
]
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
格式化数据即不是数组也不是字符串
public function testNormalizeNotArrAndNotString(): void
{
$result = Arr::normalize(false);
$this->assertFalse($result);
}
允许特定 Key 通过
public function testOnly(): void
{
$result = Arr::only(['input' => 'test', 'foo' => 'bar', 'hello' => 'world'], ['input', 'hello', 'notfound']);
$json = <<<'eot'
{
"input": "test",
"hello": "world",
"notfound": null
}
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
数据过滤
public function testFilter(): void
{
$sourceData = ['foo' => 'bar', 'hello' => 'world ', 'i' => '5'];
$rule = [];
$result = Arr::filter($sourceData, $rule);
$json = <<<'eot'
{
"hello": "world",
"i": "5"
}
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
数据过滤待规则
public function testFilterWithRule(): void
{
$sourceData = ['foo' => 'bar', 'hello' => 'world ', 'i' => '5'];
$rule = [
'i' => ['intval'],
'foo' => ['md5'],
'bar' => [function ($v) {
return $v.' php';
}],
];
$result = Arr::filter($sourceData, $rule);
$json = <<<'eot'
{
"foo": "37b51d194a7513e45b56f6524f2d51f2",
"hello": "world",
"i": 5
}
eot;
$this->assertSame(
$json,
$this->varJson(
$result
)
);
}
数据过滤待规则必须是数组
public function testFilterRuleIsNotArr(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
'Rule of `i` must be an array.'
);
$sourceData = ['foo' => 'bar', 'hello' => 'world ', 'i' => '5'];
$rule = [
'i' => 'intval',
];
}