|
1
|
|
|
<?php namespace Arcanedev\LaravelApiHelper\Support; |
|
2
|
|
|
|
|
3
|
|
|
use Arcanedev\LaravelApiHelper\Contracts\Transformable; |
|
4
|
|
|
use Illuminate\Contracts\Pagination\Paginator; |
|
5
|
|
|
use Illuminate\Support\Fluent; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class Transformer |
|
9
|
|
|
* |
|
10
|
|
|
* @package Arcanedev\LaravelApiHelper\Support |
|
11
|
|
|
* @author ARCANEDEV <[email protected]> |
|
12
|
|
|
*/ |
|
13
|
|
|
abstract class Transformer |
|
14
|
|
|
{ |
|
15
|
|
|
/* ----------------------------------------------------------------- |
|
16
|
|
|
| Main Methods |
|
17
|
|
|
| ----------------------------------------------------------------- |
|
18
|
|
|
*/ |
|
19
|
|
|
/** |
|
20
|
|
|
* Make the transformation. |
|
21
|
|
|
* |
|
22
|
|
|
* @param mixed $resource |
|
23
|
|
|
* |
|
24
|
|
|
* @return mixed |
|
25
|
|
|
*/ |
|
26
|
10 |
|
public static function make($resource) |
|
27
|
4 |
|
{ |
|
28
|
9 |
|
return (new static)->handle($resource); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Handle the transformation. |
|
33
|
|
|
* |
|
34
|
|
|
* @param mixed $resource |
|
35
|
|
|
* |
|
36
|
|
|
* @return mixed |
|
37
|
|
|
*/ |
|
38
|
18 |
|
public function handle($resource) |
|
39
|
|
|
{ |
|
40
|
18 |
|
$this->checkTransformMethod(); |
|
41
|
|
|
|
|
42
|
15 |
|
if ($resource instanceof Paginator) |
|
43
|
7 |
|
$resource = $resource->getCollection(); |
|
|
|
|
|
|
44
|
|
|
|
|
45
|
|
|
if ( |
|
46
|
15 |
|
$resource instanceof Transformable || |
|
47
|
10 |
|
$resource instanceof Fluent |
|
48
|
2 |
|
) |
|
49
|
15 |
|
return $this->transform($resource); |
|
|
|
|
|
|
50
|
|
|
|
|
51
|
3 |
|
return $resource->transform($this); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Invoke the transformer. |
|
56
|
|
|
* |
|
57
|
|
|
* @param mixed $resource |
|
58
|
|
|
* |
|
59
|
|
|
* @return mixed |
|
60
|
|
|
*/ |
|
61
|
12 |
|
public function __invoke($resource) |
|
62
|
|
|
{ |
|
63
|
12 |
|
return $this->handle($resource); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/* ----------------------------------------------------------------- |
|
67
|
|
|
| Other Methods |
|
68
|
|
|
| ----------------------------------------------------------------- |
|
69
|
|
|
*/ |
|
70
|
|
|
/** |
|
71
|
|
|
* Check if the `transform` method exists. |
|
72
|
|
|
*/ |
|
73
|
18 |
|
protected function checkTransformMethod() |
|
74
|
|
|
{ |
|
75
|
18 |
|
if ( ! method_exists($this, 'transform')) { |
|
76
|
3 |
|
$class = get_class($this); |
|
77
|
|
|
|
|
78
|
3 |
|
throw new \BadMethodCallException("Missing [transform] method in {$class}."); |
|
79
|
|
|
} |
|
80
|
15 |
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.