Skip to content

Commit 6b285bd

Browse files
author
chen.mingjiang
committed
add withGroups api
1 parent e5526a3 commit 6b285bd

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

docs/zh/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,27 @@ $defaultArray = $user1->toArray();
639639
// 'noGroupInfo' => '默认分组信息'
640640
// ]
641641

642+
// 指定分组内容输入
643+
$defaultArray = $user1->withGroups('create')->toArray();
644+
// 输出内容
645+
// [
646+
// 'name' => '李四',
647+
// 'username' => 'username',
648+
// 'email' => 'zhangsan@example.com',
649+
// ]
650+
651+
$defaultArray = $user1->withGroups(['detail','other'])->toArray();
652+
// 输出内容
653+
// [
654+
// 'id' => '1',
655+
// 'name' => '李四',
656+
// 'username' => 'username',
657+
// 'score' => 100,
658+
// 'email' => 'zhangsan@example.com',
659+
// 'sensitiveData' => '机密信息',
660+
// ]
661+
662+
642663
// 使用 create 分组创建用户 只会接受group为create的数据信息
643664
$user2 = User::setGroups(['create'])->from(
644665
id:1,

src/Serialize.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ public static function setGroups(array|string $groups): SerializeContext
2727
return $serializeContext->setGroups((array)$groups);
2828
}
2929

30+
public function withGroups(array|string $groups): static
31+
{
32+
$this->getContext()->setGroups((array)$groups);
33+
return $this;
34+
}
35+
3036
public function toArray(): array
3137
{
3238
if ($this->getContext() === null) {

src/Support/Context/SerializeContext.php

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,7 @@ public function faker()
218218
*/
219219
public function toArray(object $object): array
220220
{
221-
if (!$this->getGroups()) {
222-
$this->chooseSerializeContext->setGroups($this->getGroups());
223-
}
224-
221+
$this->chooseSerializeContext->setGroups($this->getGroups());
225222
return $this->propertyToArrayResolver->resolve($this->chooseSerializeContext, $this->getGroupCollection(), $object);
226223
}
227224
}

0 commit comments

Comments
 (0)