reactphp / http

Event-driven, streaming HTTP client and server implementation for ReactPHP.
https://reactphp.org/http/
MIT License
747 stars 143 forks source link

Add Dynamic HTTP Status Code for JSON Responses in React\Http\Message\Response #507

Open emrancu opened 1 year ago

emrancu commented 1 year ago

This pull request enhances the React\Http\Message\Response class by introducing the ability to set dynamic HTTP status codes for JSON responses.

This feature provides developers with the flexibility to adapt status codes based on contextual requirements.

SimonFrings commented 7 months ago

Hey @emrancu, thank you for contributing to ReactPHP! :heart:

The React\Http\Message\Response::json() method alongside the other methods (HTML/plaintext/XML) were introduced in #439 and we use these factory methods throughout our documentation and examples to make them more readable. These methods are entirely optional and do not replace the Response constructor. This means, instead of using the json() method, we can also use:

$response = new React\Http\Message\Response(
    React\Http\Message\Response::STATUS_OK,
    [
        'Content-Type' => 'application/json'
    ],
    json_encode(
        ['name' => 'Alice'],
        JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION
    ) . "\n"
);

This way you can directly use the Response constructor in order to adapt the status code. So I'm wondering how much is gained by the suggested change, what do you think?