JsonApiBookTransformer.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php namespace League\Fractal\Test\Stub\Transformer;
  2. use League\Fractal\TransformerAbstract;
  3. class JsonApiBookTransformer extends TransformerAbstract
  4. {
  5. protected $availableIncludes = [
  6. 'author',
  7. 'co-author',
  8. 'author-with-meta',
  9. ];
  10. public function transform(array $book)
  11. {
  12. $book['year'] = (int) $book['year'];
  13. unset($book['_author']);
  14. unset($book['_co_author']);
  15. return $book;
  16. }
  17. public function includeAuthor(array $book)
  18. {
  19. if (!array_key_exists('_author', $book)) {
  20. return;
  21. }
  22. if ($book['_author'] === null) {
  23. return $this->null();
  24. }
  25. return $this->item($book['_author'], new JsonApiAuthorTransformer(), 'people');
  26. }
  27. public function includeAuthorWithMeta(array $book)
  28. {
  29. if (!array_key_exists('_author', $book)) {
  30. return;
  31. }
  32. if ($book['_author'] === null) {
  33. return $this->null();
  34. }
  35. return $this->item($book['_author'], new JsonApiAuthorTransformer(), 'people')
  36. ->setMeta(['foo' => 'bar']);
  37. }
  38. public function includeCoAuthor(array $book)
  39. {
  40. if (!array_key_exists('_co_author', $book)) {
  41. return;
  42. }
  43. if ($book['_co_author'] === null) {
  44. return $this->null();
  45. }
  46. return $this->item($book['_co_author'], new JsonApiAuthorTransformer(), 'people');
  47. }
  48. }