2727 * @package tamedevelopers\validator
2828 * @author Tame Developers <tamedevelopers@gmail.com>
2929 * @copyright 2021-2023 Tame Developers
30- * @license http://www.opensource.org/licenses/MIT The MIT License
3130 * @link https://github.com/tamedevelopers/validator
3231 */
3332class Validator implements ValidatorInterface
@@ -113,7 +112,7 @@ public function validate($closure = null)
113112 $ response = $ this ->callback ($ closure );
114113
115114 // Keep chaining but store JsonResponse for later
116- if ($ response instanceof \ Symfony \ Component \ HttpFoundation \JsonResponse ) {
115+ if (ValidatorMethod:: isJsonResponse ( $ response) ) {
117116 $ this ->jsonResponse = $ response ;
118117 }
119118 }
@@ -123,40 +122,37 @@ public function validate($closure = null)
123122
124123 /**
125124 * Form save response
126- *
125+ *
127126 * @param Closure $function
128127 * @return mixed
129128 */
130129 public function save ($ closure )
131130 {
132- // if validation already failed, return stored JsonResponse
133- if ($ this ->jsonResponse instanceof \ Symfony \ Component \ HttpFoundation \JsonResponse ) {
134- // Send only if not in Laravel environment to avoid double sending
135- if (!class_exists ( ' Illuminate\Foundation\Application ' ) ) {
131+ // if validation already failed, send stored JsonResponse now
132+ if (ValidatorMethod:: isJsonResponse ( $ this ->jsonResponse ) ) {
133+ // Send headers/body only once and return response for frameworks/tests
134+ if (!$ this -> responseSent ) {
136135 $ this ->jsonResponse ->send ();
136+ $ this ->responseSent = true ;
137137 }
138138 return $ this ->jsonResponse ;
139139 }
140140
141141 if ($ this ->isValidated ()){
142-
142+
143143 // save into a remembering variable
144144 ValidatorMethod::resolveFlash ($ this );
145-
145+
146146 $ response = $ this ->callback ($ closure );
147147
148- // If user returns a JsonResponse in save, return it
149- if ($ response instanceof \Symfony \Component \HttpFoundation \JsonResponse) {
150- // delete csrf session token
151- CsrfToken::unsetToken ();
152-
153- // Send only if not in Laravel environment to avoid double sending
154- if (!class_exists ('Illuminate\Foundation\Application ' )) {
148+ // If user returns a JsonResponse in save, send and return it
149+ if (ValidatorMethod::isJsonResponse ($ response )) {
150+ if (!$ this ->responseSent ) {
155151 $ response ->send ();
152+ $ this ->responseSent = true ;
156153 }
157- return $ response ;
158154 }
159-
155+
160156 // delete csrf session token
161157 CsrfToken::unsetToken ();
162158 }
0 commit comments