PostTransformer.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Repositories\Transformers;
  11. use App\Repositories\Enums\PermissionEnum;
  12. use App\Repositories\Models\Post;
  13. use Illuminate\Support\Str;
  14. use League\Fractal\TransformerAbstract;
  15. class PostTransformer extends TransformerAbstract
  16. {
  17. protected $defaultIncludes = [
  18. 'author',
  19. ];
  20. public function transform(Post $post)
  21. {
  22. return [
  23. 'id' => $post->id,
  24. 'title' => $post->title,
  25. 'body' => $this->checkColumnPermission() ? $post->body : Str::limit($post->body, 120), // 没有文章详情查看权限时,返回截取的部分内容
  26. 'published' => $post->published,
  27. ];
  28. }
  29. protected function checkColumnPermission()
  30. {
  31. return auth('api')->user()->can(PermissionEnum::ROUTE_POSTS_VIEW()->name);
  32. }
  33. public function includeAuthor(Post $post)
  34. {
  35. $author = $post->author;
  36. return $this->item($author, new UserTransformer());
  37. }
  38. }