5

I have the following class that handles JSON responses for me:

<?php
namespace BulkTransactionalSMS\Http\Handlers\Response;

use Symfony\Component\HttpFoundation\Response;

class JsonResponseHandler implements ResponseHandlerInterface
{
    /**
     * @param string $message
     * @return Response
     */
    public function errorResponse(string $message): Response
    {
        return response()->json([
            'status' => 'error',
            'message' => $message
        ]);
    }

    /**
     * @param array $successDetails
     * @return Response
     */
    public function successResponse(array $successDetails = []): Response
    {
        $response = array_merge(['status' => 'success'], $successDetails);
        return response()->json($response);
    }
}

All JSON responses is handled by this class because then it's uniform and easy to change. I have tried this class as it is as well as with Response::json() and both yield the same result.

JSON headers are being sent back which is screwing with jQuery handling the response. This is an example call, and what I'm getting back:

// Example call
$jsonResponseHandler = new JsonResponseHandler();
return $jsonResponseHandler->errorResponse('This is not working');

// Returns this:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Tue, 12 Mar 2019 06:15:28 GMT

{"status":"error","message":"This is not working"}

// Expected return:
{"status":"error","message":"This is not working"}

The route that is called (via Ajax) is set up like this:

Route::post('/upload-file', 'UploadController@uploadFile');

And this is what the target function looks like:

/**
 * @param Request $request
 * @return Response
 */
public function uploadFile(Request $request)
{
    $fileHandler = new FileUploadHandler(
        new MessagesRepository(new Message()),
        new JsonResponseHandler(),
        new Hasher()
    );
    return $fileHandler->uploadFile($request);
}

Why is it returning the headers in the body and how do I fix it?

EDIT 1

Here is FileUploadHandler.php.

Community
  • 1
  • 1
Bird87 ZA
  • 2,313
  • 8
  • 36
  • 69
  • Can you also show how you call this code in your controllers? I'm betting what's happening is you are returning the JsonResonseHandler object instead of returning the method call (such as return `$jsonHandler->errorResponse()`). When you return an object from a controller Laravel tries to convert it to a string, which would be the full HTTP response. – FatBoyXPC Mar 12 '19 at 06:40
  • typecast to `\Illuminate\Http\JsonResponse` instead of `Symfony\Component\HttpFoundation\Response` or remove it – Sohel0415 Mar 12 '19 at 06:45
  • More specifically, can you show me `FileUploadHandler`'s `uploadFile` method? That's what I meant when I said controller, but I can't edit that comment now. – FatBoyXPC Mar 12 '19 at 06:58
  • @Sohel0415: `\Illuminate\Http\JsonResponse` extends `\Symfony\Component\HttpFoundation\Response`. Regardless, typecasting to `JsonResponse` doesn't solve the issue – Bird87 ZA Mar 12 '19 at 07:28
  • @FatBoyXPC: I've updated the original question – Bird87 ZA Mar 12 '19 at 07:31
  • @FatBoyXPC: I found the issue, check my answer – Bird87 ZA Mar 12 '19 at 07:34

1 Answers1

9

As I went through the file I uploaded for FatBoyXPC, I saw that my typecasting for the function was string. That's why it broke. Here's how I fixed it:

public function uploadFile(Request $request): string
{
    // do stuff
}

It's supposed to be:

public function uploadFile(Request $request): \Symfony\Component\HttpFoundation\Response
{
    // do stuff
}
Bird87 ZA
  • 2,313
  • 8
  • 36
  • 69
  • 3
    Thanks for following up. Saved my butt – Clayton Engle Oct 15 '20 at 15:14
  • Why does PHP cast anything to a string when that's the return type. How this doesn't result in a type error is beyond me... – Kerwin Sneijders Apr 13 '23 at 10:14
  • Because `\Symfony\Component\HttpFoundation\Response` has a `__toString()` method. So when I forced it to return string, PHP automatically looks if there's a `__toString()` method. It would have thrown an exception if none was found. – Bird87 ZA Apr 14 '23 at 07:03