1 <?php
2 /**
3 * @package Joomla.Libraries
4 * @subpackage Response
5 *
6 * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
7 * @license GNU General Public License version 2 or later; see LICENSE.txt
8 */
9
10 defined('JPATH_PLATFORM') or die;
11
12 /**
13 * JSON Response class.
14 *
15 * This class serves to provide the Joomla Platform with a common interface to access
16 * response variables for e.g. Ajax requests.
17 *
18 * @since 3.1
19 */
20 class JResponseJson
21 {
22 /**
23 * Determines whether the request was successful
24 *
25 * @var boolean
26 * @since 3.1
27 */
28 public $success = true;
29
30 /**
31 * The main response message
32 *
33 * @var string
34 * @since 3.1
35 */
36 public $message = null;
37
38 /**
39 * Array of messages gathered in the JApplication object
40 *
41 * @var array
42 * @since 3.1
43 */
44 public $messages = null;
45
46 /**
47 * The response data
48 *
49 * @var mixed
50 * @since 3.1
51 */
52 public $data = null;
53
54 /**
55 * Constructor
56 *
57 * @param mixed $response The Response data
58 * @param string $message The main response message
59 * @param boolean $error True, if the success flag shall be set to false, defaults to false
60 * @param boolean $ignoreMessages True, if the message queue shouldn't be included, defaults to false
61 *
62 * @since 3.1
63 */
64 public function __construct($response = null, $message = null, $error = false, $ignoreMessages = false)
65 {
66 $this->message = $message;
67
68 // Get the message queue if requested and available
69 $app = JFactory::getApplication();
70
71 if (!$ignoreMessages && $app !== null && is_callable(array($app, 'getMessageQueue')))
72 {
73 $messages = $app->getMessageQueue();
74
75 // Build the sorted messages list
76 if (is_array($messages) && count($messages))
77 {
78 foreach ($messages as $message)
79 {
80 if (isset($message['type']) && isset($message['message']))
81 {
82 $lists[$message['type']][] = $message['message'];
83 }
84 }
85 }
86
87 // If messages exist add them to the output
88 if (isset($lists) && is_array($lists))
89 {
90 $this->messages = $lists;
91 }
92 }
93
94 // Check if we are dealing with an error
95 if ($response instanceof Exception || $response instanceof Throwable)
96 {
97 // Prepare the error response
98 $this->success = false;
99 $this->message = $response->getMessage();
100 }
101 else
102 {
103 // Prepare the response data
104 $this->success = !$error;
105 $this->data = $response;
106 }
107 }
108
109 /**
110 * Magic toString method for sending the response in JSON format
111 *
112 * @return string The response in JSON format
113 *
114 * @since 3.1
115 */
116 public function __toString()
117 {
118 return json_encode($this);
119 }
120 }
121