Skip to content

Commit

Permalink
[10.x] update [JsonResponse]: using match expression instead of if-el…
Browse files Browse the repository at this point in the history
…seif-else (#47524)

* refactor(JsonResponse): using match expression instead of switch in setData method

* Update JsonResponse.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
saMahmoudzadeh and taylorotwell authored Jun 22, 2023
1 parent f30422f commit a69c1bd
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/Illuminate/Http/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class JsonResponse extends BaseJsonResponse
}

/**
* Constructor.
* Create a new JSON response instance.
*
* @param mixed $data
* @param int $status
Expand Down Expand Up @@ -77,15 +77,12 @@ public function setData($data = []): static
// Ensure json_last_error() is cleared...
json_decode('[]');

if ($data instanceof Jsonable) {
$this->data = $data->toJson($this->encodingOptions);
} elseif ($data instanceof JsonSerializable) {
$this->data = json_encode($data->jsonSerialize(), $this->encodingOptions);
} elseif ($data instanceof Arrayable) {
$this->data = json_encode($data->toArray(), $this->encodingOptions);
} else {
$this->data = json_encode($data, $this->encodingOptions);
}
$this->data = match (true) {
$data instanceof Jsonable => $data->toJson($this->encodingOptions),
$data instanceof JsonSerializable => json_encode($data->jsonSerialize(), $this->encodingOptions),
$data instanceof Arrayable => json_encode($data->toArray(), $this->encodingOptions),
default => json_encode($data, $this->encodingOptions),
};

if (! $this->hasValidJson(json_last_error())) {
throw new InvalidArgumentException(json_last_error_msg());
Expand Down

0 comments on commit a69c1bd

Please sign in to comment.