SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/Json.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use Throwable;
  17.  
  18.  
  19. /**
  20.  * Methods for handling JSON output, usually for AJAX responses
  21.  */
  22. class Json
  23. {
  24.  
  25. /**
  26.   * Sends a JSON message which has the success field set to zero
  27.   * and the specified message in the message field.
  28.   *
  29.   * If $message is an Exception object, the message will be extracted
  30.   * and if on the test server, a stacktrace is included as well.
  31.   *
  32.   * This method halts execution
  33.   **/
  34. public static function error($message)
  35. {
  36. if ($message instanceof Throwable) {
  37. $json = array('success' => 0, 'message' => $message->getMessage());
  38.  
  39. if (!IN_PRODUCTION) {
  40. $json['file'] = $message->getFile();
  41. $json['line'] = $message->getLine();
  42. $json['stacktrace'] = $message->getTraceAsString();
  43. }
  44.  
  45. } else {
  46. $json = array('success' => 0, 'message' => $message);
  47. }
  48.  
  49. header('Content-type: application/json');
  50. echo json_encode($json);
  51. }
  52.  
  53.  
  54. /**
  55.   * Sends a JSON confirmation response, and then terminates.
  56.   *
  57.   * The returned data will have the key 'success' => 1 added.
  58.   * If no data is provided, the returned JSON will only contain the 'success' key.
  59.   *
  60.   * This method halts execution
  61.   **/
  62. public static function confirm($data = null)
  63. {
  64. if (!is_array($data)) $data = array();
  65.  
  66. $data['success'] = 1;
  67.  
  68. header('Content-type: application/json');
  69. echo json_encode($data);
  70. }
  71.  
  72.  
  73. /**
  74.   * Outputs the JSON data (encoded) + correct mime type, then stops script execution
  75.   *
  76.   * @param mixed $data Any kind of data to be JSON encoded
  77.   * @param int $options E.g. JSON_PRETTY_PRINT, as per http://php.net/manual/en/function.json-encode.php
  78.   * @return void This function calls echo
  79.   */
  80. public static function out($data, $options = 0)
  81. {
  82. header('Content-type: application/json');
  83. echo json_encode($data, $options);
  84. exit(0);
  85. }
  86.  
  87. }
  88.  
  89.  
  90.