Просмотр файла vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php

Размер файла: 1.73Kb
  1. <?php
  2.  
  3. namespace Illuminate\Http\Resources;
  4.  
  5. use Illuminate\Pagination\AbstractCursorPaginator;
  6. use Illuminate\Pagination\AbstractPaginator;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Str;
  9.  
  10. trait CollectsResources
  11. {
  12. /**
  13. * Map the given collection resource into its individual resources.
  14. *
  15. * @param mixed $resource
  16. * @return mixed
  17. */
  18. protected function collectResource($resource)
  19. {
  20. if ($resource instanceof MissingValue) {
  21. return $resource;
  22. }
  23.  
  24. if (is_array($resource)) {
  25. $resource = new Collection($resource);
  26. }
  27.  
  28. $collects = $this->collects();
  29.  
  30. $this->collection = $collects && ! $resource->first() instanceof $collects
  31. ? $resource->mapInto($collects)
  32. : $resource->toBase();
  33.  
  34. return ($resource instanceof AbstractPaginator || $resource instanceof AbstractCursorPaginator)
  35. ? $resource->setCollection($this->collection)
  36. : $this->collection;
  37. }
  38.  
  39. /**
  40. * Get the resource that this resource collects.
  41. *
  42. * @return string|null
  43. */
  44. protected function collects()
  45. {
  46. if ($this->collects) {
  47. return $this->collects;
  48. }
  49.  
  50. if (Str::endsWith(class_basename($this), 'Collection') &&
  51. (class_exists($class = Str::replaceLast('Collection', '', get_class($this))) ||
  52. class_exists($class = Str::replaceLast('Collection', 'Resource', get_class($this))))) {
  53. return $class;
  54. }
  55. }
  56.  
  57. /**
  58. * Get an iterator for the resource collection.
  59. *
  60. * @return \ArrayIterator
  61. */
  62. public function getIterator()
  63. {
  64. return $this->collection->getIterator();
  65. }
  66. }