This repository was archived by the owner on Dec 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResourceTrait.php
115 lines (101 loc) · 3.3 KB
/
ResourceTrait.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
109
110
111
112
113
114
115
<?php namespace Impleri\Resource;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Collection;
/**
* Base Resource Trait
*
* Provides some simple actions to map
*/
trait ResourceTrait
{
/**
* The default output format to use.
* @var string
*/
protected $defaultFormat = 'json';
/**
* Get Format
*
* Determines which format to use for output.
*/
protected function getFormat()
{
$format = $this->defaultFormat;
if (!Request::wantsJson()) {
$format = Request::format($format);
}
return $format;
}
/**
* Respond
*
* Generates a response according to the detected format.
* @param mixed $data Data to pass to response
* @param string $view Full name of view
* @param integer $status HTTP status code
* @param array $headers Headers to pass to response
* @return \Illuminate\Http\Response Laravel response
*/
protected function respond($data, $view = '', $status = 200, $headers = array())
{
$format = $this->getFormat();
switch ($format) {
case 'xml':
case 'txt':
/* Ensure resource views are in an expected directory.
* @example The request is for a blog post in XML format. The
* view name should be the default path for html rendering (e.g.
* "post.show"). The final path will be resources.xml.post.show.
* This is to keep API-aimed views separate from standard HTML
* ones.
*/
if (!empty($view)) {
if (strpos($view, $format) === false) {
$view = $format . '.' . $view;
}
if (strpos($view, 'resources') === false) {
$view = 'resources.' . $view;
}
}
// fall through to html handling
case 'html':
if (!empty($view)) {
$response = Response::view($view, $data, $status, $headers);
} else {
$response = Response::make(
Collection::make($data)->flatten()->implode(0, "\n"),
$status,
$headers
);
}
break;
default:
$json = (isset($data['json'])) ? $data['json'] : $data;
$response = Response::json($json, $status, $headers);
break;
}
return $response;
}
/**
* Not Supported
*
* Helper method to return an error for unsupported methods.
* @param string $view The view to render
* @return \Illuminate\Http\Response Laravel response
*/
protected function notSupported($message = '', $view = 'errors.405', $status = 405)
{
if (empty($message)) {
$message = 'This resource does not support this method';
}
if (!is_array($message)) {
$message = [$message];
}
$data = array(
'success' => false,
'errors' => $message,
);
return $this->respond($data, $view, $status);
}
}