Merge "buttons: Update focus for quiet buttons"
[mediawiki.git] / includes / content / JsonContent.php
blobb36827c507824691e4ca71e878fc8e417f378542
1 <?php
2 /**
3 * JSON Content Model
5 * @file
7 * @author Ori Livneh <ori@wikimedia.org>
8 * @author Kunal Mehta <legoktm@gmail.com>
9 */
11 /**
12 * Represents the content of a JSON content.
13 * @since 1.24
15 class JsonContent extends TextContent {
17 public function __construct( $text, $modelId = CONTENT_MODEL_JSON ) {
18 parent::__construct( $text, $modelId );
21 /**
22 * Decodes the JSON into a PHP associative array.
23 * @return array
25 public function getJsonData() {
26 return FormatJson::decode( $this->getNativeData(), true );
29 /**
30 * @return bool Whether content is valid JSON.
32 public function isValid() {
33 return $this->getJsonData() !== null;
36 /**
37 * Pretty-print JSON
39 * @return bool|null|string
41 public function beautifyJSON() {
42 $decoded = FormatJson::decode( $this->getNativeData(), true );
43 if ( !is_array( $decoded ) ) {
44 return null;
46 return FormatJson::encode( $decoded, true );
50 /**
51 * Beautifies JSON prior to save.
52 * @param Title $title Title
53 * @param User $user User
54 * @param ParserOptions $popts
55 * @return JsonContent
57 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
58 return new static( $this->beautifyJSON() );
61 /**
62 * Set the HTML and add the appropriate styles
65 * @param Title $title
66 * @param int $revId
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
73 ) {
74 if ( $generateHtml ) {
75 $output->setText( $this->objectTable( $this->getJsonData() ) );
76 $output->addModuleStyles( 'mediawiki.content.json' );
77 } else {
78 $output->setText( '' );
81 /**
82 * Constructs an HTML representation of a JSON object.
83 * @param array $mapping
84 * @return string HTML
86 protected function objectTable( $mapping ) {
87 $rows = array();
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 ) )
97 /**
98 * Constructs HTML representation of a single key-value pair.
99 * @param string $key
100 * @param mixed $val
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 ) );
107 } else {
108 if ( is_string( $val ) ) {
109 $val = '"' . $val . '"';
110 } else {
111 $val = FormatJson::encode( $val );
114 $td = Xml::elementClean( 'td', array( 'class' => 'value' ), $val );
117 return Xml::tags( 'tr', array(), $th . $td );