Repository navigation
Expand file tree
/
Copy pathJsonResponseFormat.php
More file actions
121 lines (104 loc) · 2.36 KB
/
Copy pathJsonResponseFormat.php
File metadata and controls
121 lines (104 loc) · 2.36 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php namespace Dingo\Api\Http\ResponseFormat;
use Illuminate\Support\Contracts\ArrayableInterface;
class JsonResponseFormat implements ResponseFormatInterface {
/**
* Format an Eloquent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return string
*/
public function formatEloquentModel($model)
{
$key = str_singular($model->getTable());
return $this->encode([$key => $model->toArray()]);
}
/**
* Format an Eloquent collection.
*
* @param \Illuminate\Database\Eloquent\Collection $collection
* @return string
*/
public function formatEloquentCollection($collection)
{
if ($collection->isEmpty())
{
return $this->encode([]);
}
$key = str_plural($collection->first()->getTable());
return $this->encode([$key => $collection->toArray()]);
}
/**
* Format a string.
*
* @param string $string
* @return string
*/
public function formatString($string)
{
return $this->encode(['message' => $string]);
}
/**
* Format an array or instance implementing ArrayableInterface.
*
* @param \Illuminate\Support\Contracts\ArrayableInterface $response
* @return string
*/
public function formatArrayableInterface($response)
{
$response = $this->morphToArray($response);
array_walk_recursive($response, function(&$value)
{
$value = $this->morphToArray($value);
});
return $this->encode($response);
}
/**
* Format an instance implementing JsonableInterface.
*
* @param \Illuminate\Support\Contracts\JsonableInterface $response
* @return string
*/
public function formatJsonableInterface($response)
{
return $response->toJson();
}
/**
* Format an unknown type.
*
* @param mixed $response
* @return string
*/
public function formatUnknown($response)
{
return $this->encode($response);
}
/**
* Get the response content type.
*
* @return string
*/
public function getContentType()
{
return 'application/json';
}
/**
* Morph a value to an array.
*
* @param array|\Illuminate\Support\Contracts\ArrayableInterface
* @return array
*/
protected function morphToArray($value)
{
return $value instanceof ArrayableInterface ? $value->toArray() : $value;
}
/**
* Encode the content to its JSON representation.
*
* @param string $content
* @return string
*/
protected function encode($content)
{
return json_encode($content);
}
}