This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
ApiProblemResponse.php
98 lines (85 loc) · 2.21 KB
/
ApiProblemResponse.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace ZF\ApiProblem;
use Zend\Http\Response;
/**
* Represents an ApiProblem response payload.
*/
class ApiProblemResponse extends Response
{
/**
* @var ApiProblem
*/
protected $apiProblem;
/**
* Flags to use with json_encode.
*
* @var int
*/
protected $jsonFlags;
/**
* @param ApiProblem $apiProblem
*/
public function __construct(ApiProblem $apiProblem)
{
$this->apiProblem = $apiProblem;
$this->setCustomStatusCode($apiProblem->status);
$this->setReasonPhrase($apiProblem->title);
$this->jsonFlags = JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR;
}
/**
* @return ApiProblem
*/
public function getApiProblem()
{
return $this->apiProblem;
}
/**
* Retrieve the content.
*
* Serializes the composed ApiProblem instance to JSON.
*
* @return string
*/
public function getContent()
{
return json_encode($this->apiProblem->toArray(), $this->jsonFlags);
}
/**
* Retrieve headers.
*
* Proxies to parent class, but then checks if we have an content-type
* header; if not, sets it, with a value of "application/problem+json".
*
* @return \Zend\Http\Headers
*/
public function getHeaders()
{
$headers = parent::getHeaders();
if (! $headers->has('content-type')) {
$headers->addHeaderLine('content-type', ApiProblem::CONTENT_TYPE);
}
return $headers;
}
/**
* Override reason phrase handling.
*
* If no corresponding reason phrase is available for the current status
* code, return "Unknown Error".
*
* @return string
*/
public function getReasonPhrase()
{
if (! empty($this->reasonPhrase)) {
return $this->reasonPhrase;
}
if (isset($this->recommendedReasonPhrases[$this->statusCode])) {
return $this->recommendedReasonPhrases[$this->statusCode];
}
return 'Unknown Error';
}
}