7 * @author Ori Livneh <ori@wikimedia.org>
8 * @author Kunal Mehta <legoktm@gmail.com>
12 * Represents the content of a JSON content.
15 class JSONContent
extends TextContent
{
17 public function __construct( $text, $modelId = CONTENT_MODEL_JSON
) {
18 parent
::__construct( $text, $modelId );
22 * Decodes the JSON into a PHP associative array.
25 public function getJsonData() {
26 return FormatJson
::decode( $this->getNativeData(), true );
30 * @return bool Whether content is valid JSON.
32 public function isValid() {
33 return $this->getJsonData() !== null;
39 * @return bool|null|string
41 public function beautifyJSON() {
42 $decoded = FormatJson
::decode( $this->getNativeData(), true );
43 if ( !is_array( $decoded ) ) {
46 return FormatJson
::encode( $decoded, true );
51 * Beautifies JSON prior to save.
52 * @param Title $title Title
53 * @param User $user User
54 * @param ParserOptions $popts
57 public function preSaveTransform( Title
$title, User
$user, ParserOptions
$popts ) {
58 return new static( $this->beautifyJSON() );
62 * Set the HTML and add the appropriate styles
67 * @param ParserOptions $options
68 * @param bool $generateHtml
69 * @param ParserOutput $output
71 protected function fillParserOutput( Title
$title, $revId,
72 ParserOptions
$options, $generateHtml, ParserOutput
&$output
74 if ( $generateHtml ) {
75 $output->setText( $this->objectTable( $this->getJsonData() ) );
76 $output->addModuleStyles( 'mediawiki.content.json' );
78 $output->setText( '' );
82 * Constructs an HTML representation of a JSON object.
83 * @param array $mapping
86 protected function objectTable( $mapping ) {
89 foreach ( $mapping as $key => $val ) {
90 $rows[] = $this->objectRow( $key, $val );
92 return Xml
::tags( 'table', array( 'class' => 'mw-json' ),
93 Xml
::tags( 'tbody', array(), join( "\n", $rows ) )
98 * Constructs HTML representation of a single key-value pair.
101 * @return string HTML.
103 protected function objectRow( $key, $val ) {
104 $th = Xml
::elementClean( 'th', array(), $key );
105 if ( is_array( $val ) ) {
106 $td = Xml
::tags( 'td', array(), self
::objectTable( $val ) );
108 if ( is_string( $val ) ) {
109 $val = '"' . $val . '"';
111 $val = FormatJson
::encode( $val );
114 $td = Xml
::elementClean( 'td', array( 'class' => 'value' ), $val );
117 return Xml
::tags( 'tr', array(), $th . $td );