77use Ark4ne \JsonApi \Resources \Relationship ;
88use Ark4ne \JsonApi \Support \Fields ;
99use Ark4ne \JsonApi \Support \Includes ;
10+ use Ark4ne \JsonApi \Support \Supported ;
1011use Illuminate \Http \Request ;
1112use Illuminate \Http \Resources \MergeValue ;
1213use Illuminate \Http \Resources \MissingValue ;
@@ -19,8 +20,8 @@ trait ConditionallyLoadsAttributes
1920 * @template K
2021 *
2122 * @param \Illuminate\Http\Request $request
22- * @param string $attribute
23- * @param K $value
23+ * @param string $attribute
24+ * @param K $value
2425 *
2526 * @return \Illuminate\Http\Resources\MissingValue|K
2627 */
@@ -35,8 +36,8 @@ protected function whenInFields(Request $request, string $attribute, mixed $valu
3536 * @template K
3637 *
3738 * @param \Illuminate\Http\Request $request
38- * @param string $type
39- * @param K $value
39+ * @param string $type
40+ * @param K $value
4041 *
4142 * @return \Illuminate\Http\Resources\MissingValue|K
4243 */
@@ -46,7 +47,7 @@ protected function whenIncluded(Request $request, string $type, mixed $value)
4647 }
4748
4849 /**
49- * @param bool $condition
50+ * @param bool $condition
5051 * @param iterable<array-key, mixed> $data
5152 *
5253 * @return \Illuminate\Http\Resources\MergeValue
@@ -69,4 +70,56 @@ protected function applyWhen(bool $condition, iterable $data): MergeValue
6970 return new MissingValue ();
7071 }));
7172 }
73+
74+ /**
75+ * @polyfill JsonResource::whenHas
76+ * @see https://github.com/laravel/framework/pull/45376/files
77+ *
78+ * Retrieve an attribute if it exists on the resource.
79+ *
80+ * @param string $attribute
81+ * @param mixed $value
82+ * @param mixed $default
83+ * @return \Illuminate\Http\Resources\MissingValue|mixed
84+ */
85+ public function whenHas ($ attribute , $ value = null , $ default = null )
86+ {
87+ if (Supported::$ whenHas ) {
88+ return parent ::whenHas ($ attribute , $ value , $ default );
89+ }
90+
91+ if (func_num_args () < 3 ) {
92+ $ default = new MissingValue ;
93+ }
94+
95+ if (!array_key_exists ($ attribute , $ this ->resource ->getAttributes ())) {
96+ return value ($ default );
97+ }
98+
99+ return func_num_args () === 1
100+ ? $ this ->resource ->{$ attribute }
101+ : value ($ value , $ this ->resource ->{$ attribute });
102+ }
103+
104+ /**
105+ * @polyfill JsonResource::unless
106+ * @see https://github.com/laravel/framework/pull/45419/files
107+ *
108+ * Retrieve a value if the given "condition" is falsy.
109+ *
110+ * @param bool $condition
111+ * @param mixed $value
112+ * @param mixed $default
113+ * @return \Illuminate\Http\Resources\MissingValue|mixed
114+ */
115+ public function unless ($ condition , $ value , $ default = null )
116+ {
117+ if (Supported::$ whenHas ) {
118+ return parent ::unless ($ condition , $ value , $ default );
119+ }
120+
121+ $ arguments = func_num_args () === 2 ? [$ value ] : [$ value , $ default ];
122+
123+ return $ this ->when (! $ condition , ...$ arguments );
124+ }
72125}
0 commit comments