Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 3 commits into
base: 1.x
Choose a base branch
from

Conversation

emrancu
Copy link

@emrancu emrancu commented Nov 15, 2023

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.

* @return self
* @throws \InvalidArgumentException when encoding fails
*/
public static function json($data)
public static function json($data, $status = null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also work:

Suggested change
public static function json($data, $status = null)
public static function json($data, $status = self::STATUS_OK)

Copy link
Author

@emrancu emrancu Nov 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!! You are right.

@SimonFrings
Copy link
Member

Hey @emrancu, thank you for contributing to ReactPHP! ❤️

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants