This repository was archived by the owner on Apr 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTransformableCollection.php
108 lines (95 loc) · 2.74 KB
/
TransformableCollection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Spinen\Transformers;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Input;
use Spinen\Transformers\Exceptions\TransformerNotFoundException;
/**
* Class TransformableCollection
*
* @package App\Support\Transformation
*/
class TransformableCollection extends Collection
{
/**
* Fully Qualified Namespace to the Transformers
*
* @var string
*/
protected $namespace = 'Spinen\Transformers';
/**
* Build out the namespace to the transformers
*
* @return string
*/
public function getNamespace()
{
return trim($this->namespace, '\\');
}
/**
* Make a transformer
*
* Allow the full path to the transformer class be specified or just the short name where it is concatenated to the
* getNamespace method.
*
* @param string $class
*
* @return \Illuminate\Foundation\Application|mixed
*/
public function getTransformer($class)
{
// If a full path to a class was passed in, use it, otherwise a
$class = (class_exists($class)) ? $class : $this->getTransformerClass($class);
return app($class);
}
public function getTransformerClass($class)
{
$class = $this->getNamespace() . '\\' . $class;
if (class_exists($class)) {
return $class;
}
throw new TransformerNotFoundException(sprintf('Could not locate Transformer [%s]', $class));
}
/**
* Transform the data
*
* @param string $class
*
* @return array
*/
protected function runTransformation($class)
{
return $this->getTransformer($class)
->transformCollection($this)
->toArray();
}
/**
* Transform the collection
*
* You pass in a class name that is assume that the classes are located in app/Transformers/
*
* @param string $class
*
* @return array
*/
public function transformTo($class)
{
return ['data' => $this->runTransformation($class)];
}
/**
* Transform the collection to a paginated collection
*
* @param string $class
*
* @return LengthAwarePaginator
*/
public function transformToWithPagination($class)
{
$page = Input::get('page', 1);
$perPage = Input::get('limit', 5);
$offset = ($page * $perPage) - $perPage;
// TODO: Is there a way to slice before transforming, so that we don't waste time transforming unwanted data?
$arraySlice = array_slice($this->runTransformation($class), $offset, $perPage, true);
return new LengthAwarePaginator($arraySlice, $this->count(), $perPage);
}
}