|
1
|
|
|
<?php |
|
2
|
|
|
namespace Solvire\API\Serializers\DataFields; |
|
3
|
|
|
|
|
4
|
|
|
use Solvire\Utilities\OptionsChecker as Ch; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* |
|
8
|
|
|
* I think some fields are not easily mappable. I have a feeling this kind of thing will be needed a lot. |
|
9
|
|
|
* My first example was changing a columnar data set into a row based set with mappings |
|
10
|
|
|
* |
|
11
|
|
|
* @see /examples for the transformer |
|
12
|
|
|
* @author solvire <[email protected]> |
|
13
|
|
|
* @package DataFields |
|
14
|
|
|
* @namespace Solvire\API\Serializers\DataFields |
|
15
|
|
|
*/ |
|
16
|
|
|
class TransformerField extends DataField |
|
17
|
|
|
{ |
|
18
|
|
|
|
|
19
|
|
|
protected $requiredFields = [ |
|
20
|
|
|
'transformer', |
|
21
|
|
|
'callback' |
|
22
|
|
|
]; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var \League\Fractal\TransformerAbstract $transformer |
|
26
|
|
|
*/ |
|
27
|
|
|
protected $transformer = null; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* |
|
31
|
|
|
* @var closure |
|
32
|
|
|
*/ |
|
33
|
|
|
protected $callback = null; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* |
|
37
|
|
|
* |
|
38
|
|
|
* @param array $options |
|
39
|
|
|
*/ |
|
40
|
1 |
|
public function __construct($options) |
|
41
|
|
|
{ |
|
42
|
1 |
|
Ch::ek($options, $this->requiredFields); |
|
43
|
1 |
|
$this->transformer = $options['transformer']; |
|
44
|
1 |
|
$this->callback = $options['callback']; |
|
45
|
|
|
|
|
46
|
|
|
// make sure that the transformer is set up properly |
|
47
|
1 |
|
if(! $this->transformer instanceof \League\Fractal\TransformerAbstract) |
|
48
|
1 |
|
{ |
|
49
|
|
|
throw new \RuntimeException("Your transformer must be of type League\Fractal\TransformerAbstract on " . $this->name ); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
if(!method_exists($this->transformer, 'transform')) |
|
53
|
1 |
|
{ |
|
54
|
|
|
throw new \RuntimeException("Your transformer must implement the transform function "); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
1 |
|
parent::__construct($options); |
|
58
|
1 |
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* |
|
62
|
|
|
* @return object \League\Fractal\TransformerAbstract |
|
63
|
|
|
*/ |
|
64
|
|
|
public function getTransformer() |
|
65
|
|
|
{ |
|
66
|
|
|
return $this->transformer; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* (non-PHPdoc) |
|
71
|
|
|
* @see \Solvire\API\Serializers\DataFields\DataField::getData() |
|
72
|
|
|
*/ |
|
73
|
1 |
|
public function getData() |
|
74
|
|
|
{ |
|
75
|
1 |
|
return $this->transformer->transform($this->data); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* |
|
81
|
|
|
* @param Model $model |
|
82
|
|
|
*/ |
|
83
|
1 |
|
public function setData($model) |
|
84
|
|
|
{ |
|
85
|
1 |
|
$cb = $this->callback; |
|
86
|
1 |
|
$this->data = $cb($model); |
|
87
|
1 |
|
return $this; |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
|
|
91
|
|
|
} |
|
92
|
|
|
|