Repository navigation
Expand file tree
/
Copy pathJsonResponseFormat.php
More file actions
101 lines (86 loc) · 2.22 KB
/
Copy pathJsonResponseFormat.php
File metadata and controls
101 lines (86 loc) · 2.22 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
<?php
namespace Dingo\Api\Http\ResponseFormat;
use Illuminate\Support\Contracts\ArrayableInterface;
class JsonResponseFormat extends ResponseFormat
{
/**
* Format an Eloquent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return string
*/
public function formatEloquentModel($model)
{
$key = str_singular($model->getTable());
if (! $model::$snakeAttributes) {
$key = camel_case($key);
}
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([]);
}
$model = $collection->first();
$key = str_plural($model->getTable());
if (! $model::$snakeAttributes) {
$key = camel_case($key);
}
return $this->encode([$key => $collection->toArray()]);
}
/**
* Format an array or instance implementing ArrayableInterface.
*
* @param array|\Illuminate\Support\Contracts\ArrayableInterface $content
*
* @return string
*/
public function formatArray($content)
{
$content = $this->morphToArray($content);
array_walk_recursive($content, function (&$value) {
$value = $this->morphToArray($value);
});
return $this->encode($content);
}
/**
* 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 $value
*
* @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);
}
}