Completed
Push — master ( f6f56f...eba03f )
by Ricardo
03:57
created

PaginatedResource   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A toArray() 0 27 3
1
<?php
2
/**
3
 * @todo 
4
 */
5
6
namespace Finder\Http\Resources\Entities;
7
8
use Illuminate\Http\Resources\Json\ResourceCollection;
9
10
/**
11
 * Class PaginatedResource.
12
 *
13
 * @package Finder\Http\Resources\Entities
14
 */
15
class PaginatedResource extends ResourceCollection
16
{
17
    /**
18
     * @var string|callable
19
     */
20
    private $wrapper;
21
22
    /**
23
     * PaginatedResource constructor.
24
     *
25
     * @param mixed           $resource
26
     * @param string|callable $wrapper
27
     */
28
    public function __construct($resource, $wrapper)
29
    {
30
        parent::__construct($resource);
31
32
        $this->wrapper = $wrapper;
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function toArray($request)
39
    {
40
        $wrapper = $this->wrapper;
41
        if (is_callable($wrapper)) {
42
            $data = $wrapper($this->collection);
43
        } elseif (class_exists($wrapper)) {
44
            $data = $this->collection->map(
45
                function ($item) use ($wrapper) {
46
                    return new $wrapper($item);
47
                }
48
            );
49
        }
50
51
        return [
52
            'data' => $data ?? [],
53
            'first_page_url' => $this->resource->url(1),
54
            'last_page_url' => $this->resource->url($this->resource->lastPage()),
55
            'next_page_url' => $this->resource->nextPageUrl(),
56
            'prev_page_url' => $this->resource->previousPageUrl(),
57
            'current_page' => $this->resource->currentPage(),
58
            'last_page' => $this->resource->lastPage(),
59
            'per_page' => $this->resource->perPage(),
60
            'from' => $this->resource->firstItem(),
61
            'to' => $this->resource->lastItem(),
62
            'total' => $this->resource->total(),
63
        ];
64
    }
65
}
66