1+ <?php
2+
3+ namespace SkoreLabs \JsonApi \Http \Resources ;
4+
5+ use Illuminate \Http \Resources \Json \JsonResource ;
6+ use Illuminate \Http \Resources \MissingValue ;
7+ use Illuminate \Support \Facades \Auth ;
8+ use Illuminate \Support \Str ;
9+
10+ class JsonApiResource extends JsonResource
11+ {
12+ use RelationshipsWithIncludes, ConditionallyLoadsAttributes;
13+
14+ /**
15+ * The resource instance.
16+ *
17+ * @var \Illuminate\Database\Eloquent\Model
18+ */
19+ public $ resource ;
20+
21+ /**
22+ * Specify if show any pivot table data.
23+ *
24+ * @var bool
25+ */
26+ protected $ showPivot = false ;
27+
28+ /**
29+ * Determine whether authorize to view this resource.
30+ *
31+ * @var bool
32+ */
33+ protected $ authorize ;
34+
35+ /**
36+ * Authorize to view this resource.
37+ *
38+ * @return bool
39+ */
40+ protected function authorize ()
41+ {
42+ $ strClass = get_class ($ this ->resource );
43+
44+ return $ this ->authorize
45+ ?: is_string ($ strClass )
46+ ?: Auth::user ()->can ('viewAny ' , $ strClass )
47+ ?: Auth::user ()->can ('view ' , $ this ->resource );
48+ }
49+
50+ /**
51+ * Set authorization bypassing automatic authorization.
52+ *
53+ * @param bool $value
54+ * @return void
55+ */
56+ public function setAuthorize ($ value = true )
57+ {
58+ $ this ->authorize = $ value ;
59+ }
60+
61+ /**
62+ * Transform the resource into an array.
63+ *
64+ * @param \Illuminate\Http\Request $request
65+ * @return array
66+ */
67+ public function toArray ($ request )
68+ {
69+ if ($ this ->authorize () === false ) {
70+ return new MissingValue ();
71+ }
72+
73+ if (is_null ($ this ->resource )) {
74+ return [];
75+ }
76+
77+ return (is_array ($ this ->resource ))
78+ ? $ this ->resource
79+ : $ this ->formatResponse ();
80+ }
81+
82+ /**
83+ * Format model response to array.
84+ *
85+ * @return array
86+ */
87+ protected function formatResponse ()
88+ {
89+ $ hiddenAttrs = [
90+ $ this ->resource ->getKeyName (),
91+ ];
92+
93+ if (! $ this ->showPivot ) {
94+ $ hiddenAttrs [] = 'pivot ' ;
95+ }
96+
97+ $ this ->resource ->addHidden ($ hiddenAttrs );
98+
99+ return [
100+ $ this ->resource ->getKeyName () => (string ) $ this ->resource ->getKey (),
101+ 'type ' => Str::lower (class_basename ($ this ->resource )),
102+ 'attributes ' => $ this ->resource ->toArray (),
103+ 'relationships ' => $ this ->when (
104+ $ this ->relationships , $ this ->relationships
105+ ),
106+ ];
107+ }
108+ }
0 commit comments