CollectsResources.php 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Illuminate\Http\Resources;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Pagination\AbstractPaginator;
  5. trait CollectsResources
  6. {
  7. /**
  8. * Map the given collection resource into its individual resources.
  9. *
  10. * @param mixed $resource
  11. * @return mixed
  12. */
  13. protected function collectResource($resource)
  14. {
  15. if ($resource instanceof MissingValue) {
  16. return $resource;
  17. }
  18. $collects = $this->collects();
  19. $this->collection = $collects && ! $resource->first() instanceof $collects
  20. ? $resource->mapInto($collects)
  21. : $resource->toBase();
  22. return $resource instanceof AbstractPaginator
  23. ? $resource->setCollection($this->collection)
  24. : $this->collection;
  25. }
  26. /**
  27. * Get the resource that this resource collects.
  28. *
  29. * @return string|null
  30. */
  31. protected function collects()
  32. {
  33. if ($this->collects) {
  34. return $this->collects;
  35. }
  36. if (Str::endsWith(class_basename($this), 'Collection') &&
  37. class_exists($class = Str::replaceLast('Collection', '', get_class($this)))) {
  38. return $class;
  39. }
  40. }
  41. /**
  42. * Get an iterator for the resource collection.
  43. *
  44. * @return \ArrayIterator
  45. */
  46. public function getIterator()
  47. {
  48. return $this->collection->getIterator();
  49. }
  50. }