ChannelResource.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Http\Resources\V3;
  3. use App\Http\Resources\Concerns\ResolvesActor;
  4. use App\Models\Channel;
  5. use Illuminate\Http\Request;
  6. /**
  7. * 一个 channel(译文集,界面上叫「版本风格」)。
  8. *
  9. * `owner` 是拥有者:个人(kind=user)或团队(kind=team,团队空间里建的)。
  10. * `abilities` 是**当前查看者**能做什么,前端据此显示按钮。`progress` 只在列表带了 book + para 时出现
  11. * (该章的完成度,没有进度为 null)。**本类不查库**:拥有者来自预加载,abilities / progress 由 Service 挂上。
  12. *
  13. * 字段类型取自 channels 表:type / source_type / source_id 都是 varchar。
  14. *
  15. * @mixin Channel
  16. */
  17. class ChannelResource extends BaseResource
  18. {
  19. use ResolvesActor;
  20. /**
  21. * @param Request $request
  22. * @return array{
  23. * id: string,
  24. * name: string,
  25. * summary: string|null,
  26. * type: string,
  27. * lang: string,
  28. * status: int,
  29. * is_system: bool,
  30. * source_type: string,
  31. * source_id: string|null,
  32. * owner: array{kind: string, id: string, nickName: string, realName: string, avatar: string|null},
  33. * abilities: array{read: bool, write: bool, update: bool, delete: bool},
  34. * progress?: float|null,
  35. * created_at: string,
  36. * updated_at: string
  37. * }
  38. */
  39. public function toArray($request): array
  40. {
  41. return [
  42. 'id' => (string) $this->uid,
  43. 'name' => $this->name,
  44. 'summary' => $this->summary,
  45. 'type' => $this->type,
  46. 'lang' => $this->lang,
  47. 'status' => (int) $this->status,
  48. 'is_system' => (bool) $this->is_system,
  49. 'source_type' => $this->source_type,
  50. 'source_id' => $this->source_id,
  51. 'owner' => $this->ownerSummary(),
  52. 'abilities' => $this->getAttribute('abilities'),
  53. 'progress' => $this->when(
  54. array_key_exists('progress', $this->resource->getAttributes()),
  55. fn () => $this->progress === null ? null : (float) $this->progress,
  56. ),
  57. 'created_at' => $this->created_at,
  58. 'updated_at' => $this->updated_at,
  59. ];
  60. }
  61. /**
  62. * @return array{kind: string, id: string, nickName: string, realName: string, avatar: string|null}
  63. */
  64. private function ownerSummary(): array
  65. {
  66. if ($this->ownerGroup) {
  67. return [
  68. 'kind' => 'team',
  69. 'id' => $this->ownerGroup->uid,
  70. 'nickName' => $this->ownerGroup->name,
  71. 'realName' => $this->ownerGroup->uid,
  72. 'avatar' => null,
  73. ];
  74. }
  75. $user = $this->actor($this->owner);
  76. return [
  77. 'kind' => 'user',
  78. 'id' => (string) ($user['id'] ?? $this->owner_uid),
  79. 'nickName' => (string) ($user['nickName'] ?? ''),
  80. 'realName' => (string) ($user['realName'] ?? ''),
  81. 'avatar' => $user['avatar'] ?? null,
  82. ];
  83. }
  84. }