\Symfony\Component\HttpFoundationJsonResponse

Response represents an HTTP response in JSON format.

Note that this class does not force the returned JSON content to be an object. It is however recommended that you do return an object as it protects yourself against XSSI and JSON-JavaScript Hijacking.

Summary

Methods
Properties
Constants
__construct()
create()
__toString()
__clone()
prepare()
sendHeaders()
sendContent()
send()
setContent()
getContent()
setProtocolVersion()
getProtocolVersion()
setStatusCode()
getStatusCode()
setCharset()
getCharset()
isCacheable()
isFresh()
isValidateable()
setPrivate()
setPublic()
setImmutable()
isImmutable()
mustRevalidate()
getDate()
setDate()
getAge()
expire()
getExpires()
setExpires()
getMaxAge()
setMaxAge()
setSharedMaxAge()
getTtl()
setTtl()
setClientTtl()
getLastModified()
setLastModified()
getEtag()
setEtag()
setCache()
setNotModified()
hasVary()
getVary()
setVary()
isNotModified()
isInvalid()
isInformational()
isSuccessful()
isRedirection()
isClientError()
isServerError()
isOk()
isForbidden()
isNotFound()
isRedirect()
isEmpty()
closeOutputBuffers()
fromJsonString()
setCallback()
setJson()
setData()
getEncodingOptions()
setEncodingOptions()
$headers
$statusTexts
HTTP_CONTINUE
HTTP_SWITCHING_PROTOCOLS
HTTP_PROCESSING
HTTP_EARLY_HINTS
HTTP_OK
HTTP_CREATED
HTTP_ACCEPTED
HTTP_NON_AUTHORITATIVE_INFORMATION
HTTP_NO_CONTENT
HTTP_RESET_CONTENT
HTTP_PARTIAL_CONTENT
HTTP_MULTI_STATUS
HTTP_ALREADY_REPORTED
HTTP_IM_USED
HTTP_MULTIPLE_CHOICES
HTTP_MOVED_PERMANENTLY
HTTP_FOUND
HTTP_SEE_OTHER
HTTP_NOT_MODIFIED
HTTP_USE_PROXY
HTTP_RESERVED
HTTP_TEMPORARY_REDIRECT
HTTP_PERMANENTLY_REDIRECT
HTTP_BAD_REQUEST
HTTP_UNAUTHORIZED
HTTP_PAYMENT_REQUIRED
HTTP_FORBIDDEN
HTTP_NOT_FOUND
HTTP_METHOD_NOT_ALLOWED
HTTP_NOT_ACCEPTABLE
HTTP_PROXY_AUTHENTICATION_REQUIRED
HTTP_REQUEST_TIMEOUT
HTTP_CONFLICT
HTTP_GONE
HTTP_LENGTH_REQUIRED
HTTP_PRECONDITION_FAILED
HTTP_REQUEST_ENTITY_TOO_LARGE
HTTP_REQUEST_URI_TOO_LONG
HTTP_UNSUPPORTED_MEDIA_TYPE
HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_EXPECTATION_FAILED
HTTP_I_AM_A_TEAPOT
HTTP_MISDIRECTED_REQUEST
HTTP_UNPROCESSABLE_ENTITY
HTTP_LOCKED
HTTP_FAILED_DEPENDENCY
HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL
HTTP_TOO_EARLY
HTTP_UPGRADE_REQUIRED
HTTP_PRECONDITION_REQUIRED
HTTP_TOO_MANY_REQUESTS
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE
HTTP_UNAVAILABLE_FOR_LEGAL_REASONS
HTTP_INTERNAL_SERVER_ERROR
HTTP_NOT_IMPLEMENTED
HTTP_BAD_GATEWAY
HTTP_SERVICE_UNAVAILABLE
HTTP_GATEWAY_TIMEOUT
HTTP_VERSION_NOT_SUPPORTED
HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL
HTTP_INSUFFICIENT_STORAGE
HTTP_LOOP_DETECTED
HTTP_NOT_EXTENDED
HTTP_NETWORK_AUTHENTICATION_REQUIRED
DEFAULT_ENCODING_OPTIONS
ensureIEOverSSLCompatibility()
update()
$content
$version
$statusCode
$statusText
$charset
$data
$callback
$encodingOptions
N/A
No private methods found
No private properties found
N/A

Constants

HTTP_CONTINUE

HTTP_CONTINUE = 100

HTTP_SWITCHING_PROTOCOLS

HTTP_SWITCHING_PROTOCOLS = 101

HTTP_PROCESSING

HTTP_PROCESSING = 102

HTTP_EARLY_HINTS

HTTP_EARLY_HINTS = 103

HTTP_OK

HTTP_OK = 200

HTTP_CREATED

HTTP_CREATED = 201

HTTP_ACCEPTED

HTTP_ACCEPTED = 202

HTTP_NON_AUTHORITATIVE_INFORMATION

HTTP_NON_AUTHORITATIVE_INFORMATION = 203

HTTP_NO_CONTENT

HTTP_NO_CONTENT = 204

HTTP_RESET_CONTENT

HTTP_RESET_CONTENT = 205

HTTP_PARTIAL_CONTENT

HTTP_PARTIAL_CONTENT = 206

HTTP_MULTI_STATUS

HTTP_MULTI_STATUS = 207

HTTP_ALREADY_REPORTED

HTTP_ALREADY_REPORTED = 208

HTTP_IM_USED

HTTP_IM_USED = 226

HTTP_MULTIPLE_CHOICES

HTTP_MULTIPLE_CHOICES = 300

HTTP_MOVED_PERMANENTLY

HTTP_MOVED_PERMANENTLY = 301

HTTP_FOUND

HTTP_FOUND = 302

HTTP_SEE_OTHER

HTTP_SEE_OTHER = 303

HTTP_NOT_MODIFIED

HTTP_NOT_MODIFIED = 304

HTTP_USE_PROXY

HTTP_USE_PROXY = 305

HTTP_RESERVED

HTTP_RESERVED = 306

HTTP_TEMPORARY_REDIRECT

HTTP_TEMPORARY_REDIRECT = 307

HTTP_PERMANENTLY_REDIRECT

HTTP_PERMANENTLY_REDIRECT = 308

HTTP_BAD_REQUEST

HTTP_BAD_REQUEST = 400

HTTP_UNAUTHORIZED

HTTP_UNAUTHORIZED = 401

HTTP_PAYMENT_REQUIRED

HTTP_PAYMENT_REQUIRED = 402

HTTP_FORBIDDEN

HTTP_FORBIDDEN = 403

HTTP_NOT_FOUND

HTTP_NOT_FOUND = 404

HTTP_METHOD_NOT_ALLOWED

HTTP_METHOD_NOT_ALLOWED = 405

HTTP_NOT_ACCEPTABLE

HTTP_NOT_ACCEPTABLE = 406

HTTP_PROXY_AUTHENTICATION_REQUIRED

HTTP_PROXY_AUTHENTICATION_REQUIRED = 407

HTTP_REQUEST_TIMEOUT

HTTP_REQUEST_TIMEOUT = 408

HTTP_CONFLICT

HTTP_CONFLICT = 409

HTTP_GONE

HTTP_GONE = 410

HTTP_LENGTH_REQUIRED

HTTP_LENGTH_REQUIRED = 411

HTTP_PRECONDITION_FAILED

HTTP_PRECONDITION_FAILED = 412

HTTP_REQUEST_ENTITY_TOO_LARGE

HTTP_REQUEST_ENTITY_TOO_LARGE = 413

HTTP_REQUEST_URI_TOO_LONG

HTTP_REQUEST_URI_TOO_LONG = 414

HTTP_UNSUPPORTED_MEDIA_TYPE

HTTP_UNSUPPORTED_MEDIA_TYPE = 415

HTTP_REQUESTED_RANGE_NOT_SATISFIABLE

HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416

HTTP_EXPECTATION_FAILED

HTTP_EXPECTATION_FAILED = 417

HTTP_I_AM_A_TEAPOT

HTTP_I_AM_A_TEAPOT = 418

HTTP_MISDIRECTED_REQUEST

HTTP_MISDIRECTED_REQUEST = 421

HTTP_UNPROCESSABLE_ENTITY

HTTP_UNPROCESSABLE_ENTITY = 422

HTTP_LOCKED

HTTP_LOCKED = 423

HTTP_FAILED_DEPENDENCY

HTTP_FAILED_DEPENDENCY = 424

HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL

HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425

HTTP_TOO_EARLY

HTTP_TOO_EARLY = 425

HTTP_UPGRADE_REQUIRED

HTTP_UPGRADE_REQUIRED = 426

HTTP_PRECONDITION_REQUIRED

HTTP_PRECONDITION_REQUIRED = 428

HTTP_TOO_MANY_REQUESTS

HTTP_TOO_MANY_REQUESTS = 429

HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE

HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431

HTTP_INTERNAL_SERVER_ERROR

HTTP_INTERNAL_SERVER_ERROR = 500

HTTP_NOT_IMPLEMENTED

HTTP_NOT_IMPLEMENTED = 501

HTTP_BAD_GATEWAY

HTTP_BAD_GATEWAY = 502

HTTP_SERVICE_UNAVAILABLE

HTTP_SERVICE_UNAVAILABLE = 503

HTTP_GATEWAY_TIMEOUT

HTTP_GATEWAY_TIMEOUT = 504

HTTP_VERSION_NOT_SUPPORTED

HTTP_VERSION_NOT_SUPPORTED = 505

HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL

HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506

HTTP_INSUFFICIENT_STORAGE

HTTP_INSUFFICIENT_STORAGE = 507

HTTP_LOOP_DETECTED

HTTP_LOOP_DETECTED = 508

HTTP_NOT_EXTENDED

HTTP_NOT_EXTENDED = 510

HTTP_NETWORK_AUTHENTICATION_REQUIRED

HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511

DEFAULT_ENCODING_OPTIONS

DEFAULT_ENCODING_OPTIONS = 15

Properties

$content

$content : string

Type

string

$version

$version : string

Type

string

$statusCode

$statusCode : integer

Type

integer

$statusText

$statusText : string

Type

string

$charset

$charset : string

Type

string

$data

$data : 

Type

$callback

$callback : 

Type

$encodingOptions

$encodingOptions : 

Type

Methods

__construct()

__construct(mixed  $data = null, integer  $status = 200, array  $headers = array(), boolean  $json = false) 

Parameters

mixed $data

The response data

integer $status

The response status code

array $headers

An array of response headers

boolean $json

If the data is already a JSON string

create()

create(mixed  $data = null, integer  $status = 200, array  $headers = array()) : static

Factory method for chainability.

Example:

return JsonResponse::create($data, 200)
    ->setSharedMaxAge(300);

Parameters

mixed $data

The json response data

integer $status

The response status code

array $headers

An array of response headers

Returns

static

__toString()

__toString() : string

Returns the Response as an HTTP string.

The string representation of the Response is the same as the one that will be sent to the client only if the prepare() method has been called before.

Returns

string —

The Response as an HTTP string

__clone()

__clone() 

Clones the current Response instance.

prepare()

prepare(\Symfony\Component\HttpFoundation\Request  $request) : $this

Prepares the Response before it is sent to the client.

This method tweaks the Response to ensure that it is compliant with RFC 2616. Most of the changes are based on the Request that is "associated" with this Response.

Parameters

\Symfony\Component\HttpFoundation\Request $request

Returns

$this

sendHeaders()

sendHeaders() : $this

Sends HTTP headers.

Returns

$this

sendContent()

sendContent() : $this

Sends content for the current web response.

Returns

$this

send()

send() : $this

Sends HTTP headers and content.

Returns

$this

setContent()

setContent(mixed  $content) : $this

Sets the response content.

Valid types are strings, numbers, null, and objects that implement a __toString() method.

Parameters

mixed $content

Content that can be cast to string

Throws

\UnexpectedValueException

Returns

$this

getContent()

getContent() : string

Gets the current response content.

Returns

string —

Content

setProtocolVersion()

setProtocolVersion(string  $version) : $this

Sets the HTTP protocol version (1.0 or 1.1).

Parameters

string $version

The HTTP protocol version

Returns

$this

getProtocolVersion()

getProtocolVersion() : string

Gets the HTTP protocol version.

Returns

string —

The HTTP protocol version

setStatusCode()

setStatusCode(integer  $code, mixed  $text = null) : $this

Sets the response status code.

If the status text is null it will be automatically populated for the known status codes and left empty otherwise.

Parameters

integer $code

HTTP status code

mixed $text

HTTP status text

Throws

\InvalidArgumentException

When the HTTP status code is not valid

Returns

$this

getStatusCode()

getStatusCode() : integer

Retrieves the status code for the current web response.

Returns

integer —

Status code

setCharset()

setCharset(string  $charset) : $this

Sets the response charset.

Parameters

string $charset

Character set

Returns

$this

getCharset()

getCharset() : string

Retrieves the response charset.

Returns

string —

Character set

isCacheable()

isCacheable() : boolean

Returns true if the response may safely be kept in a shared (surrogate) cache.

Responses marked "private" with an explicit Cache-Control directive are considered uncacheable.

Responses with neither a freshness lifetime (Expires, max-age) nor cache validator (Last-Modified, ETag) are considered uncacheable because there is no way to tell when or how to remove them from the cache.

Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation, for example "status codes that are defined as cacheable by default [...] can be reused by a cache with heuristic expiration unless otherwise indicated" (https://tools.ietf.org/html/rfc7231#section-6.1)

Returns

boolean —

true if the response is worth caching, false otherwise

isFresh()

isFresh() : boolean

Returns true if the response is "fresh".

Fresh responses may be served from cache without any interaction with the origin. A response is considered fresh when it includes a Cache-Control/max-age indicator or Expires header and the calculated age is less than the freshness lifetime.

Returns

boolean —

true if the response is fresh, false otherwise

isValidateable()

isValidateable() : boolean

Returns true if the response includes headers that can be used to validate the response with the origin server using a conditional GET request.

Returns

boolean —

true if the response is validateable, false otherwise

setPrivate()

setPrivate() : $this

Marks the response as "private".

It makes the response ineligible for serving other clients.

Returns

$this

setPublic()

setPublic() : $this

Marks the response as "public".

It makes the response eligible for serving other clients.

Returns

$this

setImmutable()

setImmutable(boolean  $immutable = true) : $this

Marks the response as "immutable".

Parameters

boolean $immutable

enables or disables the immutable directive

Returns

$this

isImmutable()

isImmutable() : boolean

Returns true if the response is marked as "immutable".

Returns

boolean —

returns true if the response is marked as "immutable"; otherwise false

mustRevalidate()

mustRevalidate() : boolean

Returns true if the response must be revalidated by caches.

This method indicates that the response must not be served stale by a cache in any circumstance without first revalidating with the origin. When present, the TTL of the response should not be overridden to be greater than the value provided by the origin.

Returns

boolean —

true if the response must be revalidated by a cache, false otherwise

getDate()

getDate() : \DateTime

Returns the Date header as a DateTime instance.

Throws

\RuntimeException

When the header is not parseable

Returns

\DateTime —

A \DateTime instance

setDate()

setDate(\DateTime  $date) : $this

Sets the Date header.

Parameters

\DateTime $date

Returns

$this

getAge()

getAge() : integer

Returns the age of the response.

Returns

integer —

The age of the response in seconds

expire()

expire() : $this

Marks the response stale by setting the Age header to be equal to the maximum age of the response.

Returns

$this

getExpires()

getExpires() : \DateTime|null

Returns the value of the Expires header as a DateTime instance.

Returns

\DateTime|null —

A DateTime instance or null if the header does not exist

setExpires()

setExpires(\DateTime|null  $date = null) : $this

Sets the Expires HTTP header with a DateTime instance.

Passing null as value will remove the header.

Parameters

\DateTime|null $date

A \DateTime instance or null to remove the header

Returns

$this

getMaxAge()

getMaxAge() : integer|null

Returns the number of seconds after the time specified in the response's Date header when the response should no longer be considered fresh.

First, it checks for a s-maxage directive, then a max-age directive, and then it falls back on an expires header. It returns null when no maximum age can be established.

Returns

integer|null —

Number of seconds

setMaxAge()

setMaxAge(integer  $value) : $this

Sets the number of seconds after which the response should no longer be considered fresh.

This methods sets the Cache-Control max-age directive.

Parameters

integer $value

Number of seconds

Returns

$this

setSharedMaxAge()

setSharedMaxAge(integer  $value) : $this

Sets the number of seconds after which the response should no longer be considered fresh by shared caches.

This methods sets the Cache-Control s-maxage directive.

Parameters

integer $value

Number of seconds

Returns

$this

getTtl()

getTtl() : integer|null

Returns the response's time-to-live in seconds.

It returns null when no freshness information is present in the response.

When the responses TTL is <= 0, the response may not be served from cache without first revalidating with the origin.

Returns

integer|null —

The TTL in seconds

setTtl()

setTtl(integer  $seconds) : $this

Sets the response's time-to-live for shared caches.

This method adjusts the Cache-Control/s-maxage directive.

Parameters

integer $seconds

Number of seconds

Returns

$this

setClientTtl()

setClientTtl(integer  $seconds) : $this

Sets the response's time-to-live for private/client caches.

This method adjusts the Cache-Control/max-age directive.

Parameters

integer $seconds

Number of seconds

Returns

$this

getLastModified()

getLastModified() : \DateTime|null

Returns the Last-Modified HTTP header as a DateTime instance.

Throws

\RuntimeException

When the HTTP header is not parseable

Returns

\DateTime|null —

A DateTime instance or null if the header does not exist

setLastModified()

setLastModified(\DateTime|null  $date = null) : $this

Sets the Last-Modified HTTP header with a DateTime instance.

Passing null as value will remove the header.

Parameters

\DateTime|null $date

A \DateTime instance or null to remove the header

Returns

$this

getEtag()

getEtag() : string|null

Returns the literal value of the ETag HTTP header.

Returns

string|null —

The ETag HTTP header or null if it does not exist

setEtag()

setEtag(string|null  $etag = null, boolean  $weak = false) : $this

Sets the ETag value.

Parameters

string|null $etag

The ETag unique identifier or null to remove the header

boolean $weak

Whether you want a weak ETag or not

Returns

$this

setCache()

setCache(array  $options) : $this

Sets the response's cache headers (validation and/or expiration).

Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.

Parameters

array $options

An array of cache options

Throws

\InvalidArgumentException

Returns

$this

setNotModified()

setNotModified() : $this

Modifies the response so that it conforms to the rules defined for a 304 status code.

This sets the status, removes the body, and discards any headers that MUST NOT be included in 304 responses.

Returns

$this

hasVary()

hasVary() : boolean

Returns true if the response includes a Vary header.

Returns

boolean —

true if the response includes a Vary header, false otherwise

getVary()

getVary() : array

Returns an array of header names given in the Vary header.

Returns

array —

An array of Vary names

setVary()

setVary(string|array  $headers, boolean  $replace = true) : $this

Sets the Vary header.

Parameters

string|array $headers
boolean $replace

Whether to replace the actual value or not (true by default)

Returns

$this

isNotModified()

isNotModified(\Symfony\Component\HttpFoundation\Request  $request) : boolean

Determines if the Response validators (ETag, Last-Modified) match a conditional value specified in the Request.

If the Response is not modified, it sets the status code to 304 and removes the actual content by calling the setNotModified() method.

Parameters

\Symfony\Component\HttpFoundation\Request $request

Returns

boolean —

true if the Response validators match the Request, false otherwise

isInvalid()

isInvalid() : boolean

Is response invalid?

Returns

boolean

isInformational()

isInformational() : boolean

Is response informative?

Returns

boolean

isSuccessful()

isSuccessful() : boolean

Is response successful?

Returns

boolean

isRedirection()

isRedirection() : boolean

Is the response a redirect?

Returns

boolean

isClientError()

isClientError() : boolean

Is there a client error?

Returns

boolean

isServerError()

isServerError() : boolean

Was there a server side error?

Returns

boolean

isOk()

isOk() : boolean

Is the response OK?

Returns

boolean

isForbidden()

isForbidden() : boolean

Is the response forbidden?

Returns

boolean

isNotFound()

isNotFound() : boolean

Is the response a not found error?

Returns

boolean

isRedirect()

isRedirect(string  $location = null) : boolean

Is the response a redirect of some form?

Parameters

string $location

Returns

boolean

isEmpty()

isEmpty() : boolean

Is the response empty?

Returns

boolean

closeOutputBuffers()

closeOutputBuffers(integer  $targetLevel, boolean  $flush) 

Cleans or flushes output buffers up to target level.

Resulting level can be greater than target level if a non-removable buffer has been encountered.

Parameters

integer $targetLevel

The target output buffering level

boolean $flush

Whether to flush or clean the buffers

fromJsonString()

fromJsonString(  $data = null,   $status = 200,   $headers = array()) 

Make easier the creation of JsonResponse from raw json.

Parameters

$data
$status
$headers

setCallback()

setCallback(string|null  $callback = null) : $this

Sets the JSONP callback.

Parameters

string|null $callback

The JSONP callback or null to use none

Throws

\InvalidArgumentException

When the callback name is not valid

Returns

$this

setJson()

setJson(string  $json) : $this

Sets a raw string containing a JSON document to be sent.

Parameters

string $json

Throws

\InvalidArgumentException

Returns

$this

setData()

setData(mixed  $data = array()) : $this

Sets the data to be sent as JSON.

Parameters

mixed $data

Throws

\InvalidArgumentException

Returns

$this

getEncodingOptions()

getEncodingOptions() : integer

Returns options used while encoding data to JSON.

Returns

integer

setEncodingOptions()

setEncodingOptions(integer  $encodingOptions) : $this

Sets options used while encoding data to JSON.

Parameters

integer $encodingOptions

Returns

$this

ensureIEOverSSLCompatibility()

ensureIEOverSSLCompatibility(\Symfony\Component\HttpFoundation\Request  $request) 

Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.

Parameters

\Symfony\Component\HttpFoundation\Request $request

update()

update() : $this

Updates the content and headers according to the JSON data and callback.

Returns

$this