Projekt

Obecné

Profil

Stáhnout (5.16 KB) Statistiky
| Větev: | Revize:
1 cb15593b Cajova-Houba
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symfony\Component\HttpFoundation;
13
14
/**
15
 * Response represents an HTTP response in JSON format.
16
 *
17
 * Note that this class does not force the returned JSON content to be an
18
 * object. It is however recommended that you do return an object as it
19
 * protects yourself against XSSI and JSON-JavaScript Hijacking.
20
 *
21
 * @see https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside
22
 *
23
 * @author Igor Wiedler <igor@wiedler.ch>
24
 */
25
class JsonResponse extends Response
26
{
27
    protected $data;
28
    protected $callback;
29
30
    // Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
31
    // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
32
    protected $encodingOptions = 15;
33
34
    /**
35
     * Constructor.
36
     *
37
     * @param mixed $data    The response data
38
     * @param int   $status  The response status code
39
     * @param array $headers An array of response headers
40
     */
41
    public function __construct($data = null, $status = 200, $headers = array())
42
    {
43
        parent::__construct('', $status, $headers);
44
45
        if (null === $data) {
46
            $data = new \ArrayObject();
47
        }
48
49
        $this->setData($data);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public static function create($data = null, $status = 200, $headers = array())
56
    {
57
        return new static($data, $status, $headers);
58
    }
59
60
    /**
61
     * Sets the JSONP callback.
62
     *
63
     * @param string|null $callback The JSONP callback or null to use none
64
     *
65
     * @return JsonResponse
66
     *
67
     * @throws \InvalidArgumentException When the callback name is not valid
68
     */
69
    public function setCallback($callback = null)
70
    {
71
        if (null !== $callback) {
72
            // taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
73
            $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u';
74
            $parts = explode('.', $callback);
75
            foreach ($parts as $part) {
76
                if (!preg_match($pattern, $part)) {
77
                    throw new \InvalidArgumentException('The callback name is not valid.');
78
                }
79
            }
80
        }
81
82
        $this->callback = $callback;
83
84
        return $this->update();
85
    }
86
87
    /**
88
     * Sets the data to be sent as JSON.
89
     *
90
     * @param mixed $data
91
     *
92
     * @return JsonResponse
93
     *
94
     * @throws \InvalidArgumentException
95
     */
96
    public function setData($data = array())
97
    {
98
        if (defined('HHVM_VERSION')) {
99
            // HHVM does not trigger any warnings and let exceptions
100
            // thrown from a JsonSerializable object pass through.
101
            // If only PHP did the same...
102
            $data = json_encode($data, $this->encodingOptions);
103
        } else {
104
            try {
105
                // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
106
                // objects in a new exception that needs to be removed.
107
                // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
108
                $data = json_encode($data, $this->encodingOptions);
109
            } catch (\Exception $e) {
110
                if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
111
                    throw $e->getPrevious() ?: $e;
112
                }
113
                throw $e;
114
            }
115
        }
116
117
        if (JSON_ERROR_NONE !== json_last_error()) {
118
            throw new \InvalidArgumentException(json_last_error_msg());
119
        }
120
121
        $this->data = $data;
122
123
        return $this->update();
124
    }
125
126
    /**
127
     * Returns options used while encoding data to JSON.
128
     *
129
     * @return int
130
     */
131
    public function getEncodingOptions()
132
    {
133
        return $this->encodingOptions;
134
    }
135
136
    /**
137
     * Sets options used while encoding data to JSON.
138
     *
139
     * @param int $encodingOptions
140
     *
141
     * @return JsonResponse
142
     */
143
    public function setEncodingOptions($encodingOptions)
144
    {
145
        $this->encodingOptions = (int) $encodingOptions;
146
147
        return $this->setData(json_decode($this->data));
148
    }
149
150
    /**
151
     * Updates the content and headers according to the JSON data and callback.
152
     *
153
     * @return JsonResponse
154
     */
155
    protected function update()
156
    {
157
        if (null !== $this->callback) {
158
            // Not using application/javascript for compatibility reasons with older browsers.
159
            $this->headers->set('Content-Type', 'text/javascript');
160
161
            return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
162
        }
163
164
        // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
165
        // in order to not overwrite a custom definition.
166
        if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
167
            $this->headers->set('Content-Type', 'application/json');
168
        }
169
170
        return $this->setContent($this->data);
171
    }
172
}