Эмулировать модель-экземпляр - PullRequest
0 голосов
/ 07 апреля 2020

Я хотел бы сделать следующее: Новая модель должна быть создана путем отправки данных через API на другой сервер.

Ответ: Illuminate\Http\JsonResponse.

Вот что Я делаю в настоящее время:

    public static function create($data)
    {
        /*Create a new item using the API*/
        $client = new ApiClient();

        $response = $client->postToApi('/api/item', $data);

        if ($response->getStatusCode() !== 200) {
            return $response;
        }

        return json_decode((string)$response->getBody())->data;
    }

Если отправка завершается успешно, возвращается следующий ответ (который является выводом json_decode((string)$response->getBody())->data):

{#1046
  +"id": 10
  +"country": "de"
  +"homepage": null
  +"status": "active"
}

Если действие не удается Я получаю этот объект:

Illuminate\Http\JsonResponse {#1038
  #data: ""{\"message\":\"The given data was invalid.\",\"errors\":{\"data.id\":[\"data.id is not unique.\"]}}""
  #callback: null
  #encodingOptions: 0
  +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1037
    #computedCacheControl: array:2 [
      "no-cache" => true
      "private" => true
    ]
    #cookies: []
    #headerNames: array:3 [
      "cache-control" => "Cache-Control"
      "date" => "Date"
      "content-type" => "Content-Type"
    ]
    #headers: array:3 [
      "cache-control" => array:1 [
        0 => "no-cache, private"
      ]
      "date" => array:1 [
        0 => "Tue, 07 Apr 2020 14:11:01 GMT"
      ]
      "content-type" => array:1 [
        0 => "application/json"
      ]
    ]
    #cacheControl: []
  }
  #content: ""{\"message\":\"The given data was invalid.\",\"errors\":{\"data.id\":[\"data.id is not unique.\"]}}""
  #version: "1.0"
  #statusCode: 422
  #statusText: "Unprocessable Entity"
  #charset: null
  +original: "{"message":"The given data was invalid.","errors":{"data.id":["data.id is not unique."]}}"
  +exception: null
}
=> Illuminate\Http\JsonResponse {#1038
     +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1037},
     +original: "{"message":"The given data was invalid.","errors":{"data.id":["data.id is not unique."]}}",
     +exception: null,
   }

Хорошо, я могу работать с этим. Но: есть ли возможность сделать этот ответ более «совместимым» с красноречивыми моделями по умолчанию (при успехе и при неудаче)?

...