MediaWiki  1.28.0
FormatJsonTest.php
Go to the documentation of this file.
1 <?php
2 
7 
8  public static function provideEncoderPrettyPrinting() {
9  return [
10  // Four spaces
11  [ true, ' ' ],
12  [ ' ', ' ' ],
13  // Two spaces
14  [ ' ', ' ' ],
15  // One tab
16  [ "\t", "\t" ],
17  ];
18  }
19 
23  public function testEncoderPrettyPrinting( $pretty, $expectedIndent ) {
24  $obj = [
25  'emptyObject' => new stdClass,
26  'emptyArray' => [],
27  'string' => 'foobar\\',
28  'filledArray' => [
29  [
30  123,
31  456,
32  ],
33  // Nested json works without problems
34  '"7":["8",{"9":"10"}]',
35  // Whitespace clean up doesn't touch strings that look alike
36  "{\n\t\"emptyObject\": {\n\t},\n\t\"emptyArray\": [ ]\n}",
37  ],
38  ];
39 
40  // No trailing whitespace, no trailing linefeed
41  $json = '{
42  "emptyObject": {},
43  "emptyArray": [],
44  "string": "foobar\\\\",
45  "filledArray": [
46  [
47  123,
48  456
49  ],
50  "\"7\":[\"8\",{\"9\":\"10\"}]",
51  "{\n\t\"emptyObject\": {\n\t},\n\t\"emptyArray\": [ ]\n}"
52  ]
53 }';
54 
55  $json = str_replace( "\r", '', $json ); // Windows compat
56  $json = str_replace( "\t", $expectedIndent, $json );
57  $this->assertSame( $json, FormatJson::encode( $obj, $pretty ) );
58  }
59 
60  public static function provideEncodeDefault() {
61  return self::getEncodeTestCases( [] );
62  }
63 
67  public function testEncodeDefault( $from, $to ) {
68  $this->assertSame( $to, FormatJson::encode( $from ) );
69  }
70 
71  public static function provideEncodeUtf8() {
72  return self::getEncodeTestCases( [ 'unicode' ] );
73  }
74 
78  public function testEncodeUtf8( $from, $to ) {
79  $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::UTF8_OK ) );
80  }
81 
82  public static function provideEncodeXmlMeta() {
83  return self::getEncodeTestCases( [ 'xmlmeta' ] );
84  }
85 
89  public function testEncodeXmlMeta( $from, $to ) {
90  $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::XMLMETA_OK ) );
91  }
92 
93  public static function provideEncodeAllOk() {
94  return self::getEncodeTestCases( [ 'unicode', 'xmlmeta' ] );
95  }
96 
100  public function testEncodeAllOk( $from, $to ) {
101  $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::ALL_OK ) );
102  }
103 
104  public function testEncodePhpBug46944() {
105  $this->assertNotEquals(
106  '\ud840\udc00',
107  strtolower( FormatJson::encode( "\xf0\xa0\x80\x80" ) ),
108  'Test encoding an broken json_encode character (U+20000)'
109  );
110  }
111 
112  public function testDecodeReturnType() {
113  $this->assertInternalType(
114  'object',
115  FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}' ),
116  'Default to object'
117  );
118 
119  $this->assertInternalType(
120  'array',
121  FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}', true ),
122  'Optional array'
123  );
124  }
125 
126  public static function provideParse() {
127  return [
128  [ null ],
129  [ true ],
130  [ false ],
131  [ 0 ],
132  [ 1 ],
133  [ 1.2 ],
134  [ '' ],
135  [ 'str' ],
136  [ [ 0, 1, 2 ] ],
137  [ [ 'a' => 'b' ] ],
138  [ [ 'a' => 'b' ] ],
139  [ [ 'a' => 'b', 'x' => [ 'c' => 'd' ] ] ],
140  ];
141  }
142 
148  public static function toObject( $value ) {
149  return !is_array( $value ) ? $value : (object) array_map( __METHOD__, $value );
150  }
151 
156  public function testParse( $value ) {
157  $expected = self::toObject( $value );
158  $json = FormatJson::encode( $expected, false, FormatJson::ALL_OK );
159  $this->assertJson( $json );
160 
161  $st = FormatJson::parse( $json );
162  $this->assertInstanceOf( 'Status', $st );
163  $this->assertTrue( $st->isGood() );
164  $this->assertEquals( $expected, $st->getValue() );
165 
167  $this->assertInstanceOf( 'Status', $st );
168  $this->assertTrue( $st->isGood() );
169  $this->assertEquals( $value, $st->getValue() );
170  }
171 
190  public static function provideParseTryFixing() {
191  return [
192  [ "[,]", '[]', false ],
193  [ "[ , ]", '[]', false ],
194  [ "[ , }", false ],
195  [ '[1],', false, true, '[1]' ],
196  [ "[1,]", '[1]' ],
197  [ "[1\n,]", '[1]' ],
198  [ "[1,\n]", '[1]' ],
199  [ "[1,]\n", '[1]' ],
200  [ "[1\n,\n]\n", '[1]' ],
201  [ '["a,",]', '["a,"]' ],
202  [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ],
203  // I wish we could parse this, but would need quote parsing
204  [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ],
205  [ '[1,,]', false, false, '[1]' ],
206  ];
207  }
208 
217  public function testParseTryFixing(
218  $value, $expected,
219  $jsoncParses = true, $expectedJsonc = null
220  ) {
221  // PHP5 results are always expected to have isGood() === false
222  $expectedGoodStatus = false;
223 
224  // Check to see if json parser allows trailing commas
225  if ( json_decode( '[1,]' ) !== null ) {
226  // Use json-c specific expected result if provided
227  $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc;
228  // If json-c parses the value natively, expect isGood() === true
229  $expectedGoodStatus = $jsoncParses;
230  }
231 
233  $this->assertInstanceOf( 'Status', $st );
234  if ( $expected === false ) {
235  $this->assertFalse( $st->isOK(), 'Expected isOK() == false' );
236  } else {
237  $this->assertSame( $expectedGoodStatus, $st->isGood(),
238  'Expected isGood() == ' . ( $expectedGoodStatus ? 'true' : 'false' )
239  );
240  $this->assertTrue( $st->isOK(), 'Expected isOK == true' );
241  $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK );
242  $this->assertEquals( $expected, $val );
243  }
244  }
245 
246  public static function provideParseErrors() {
247  return [
248  [ 'aaa' ],
249  [ '{"j": 1 ] }' ],
250  ];
251  }
252 
257  public function testParseErrors( $value ) {
258  $st = FormatJson::parse( $value );
259  $this->assertInstanceOf( 'Status', $st );
260  $this->assertFalse( $st->isOK() );
261  }
262 
263  public function provideStripComments() {
264  return [
265  [ '{"a":"b"}', '{"a":"b"}' ],
266  [ "{\"a\":\"b\"}\n", "{\"a\":\"b\"}\n" ],
267  [ '/*c*/{"c":"b"}', '{"c":"b"}' ],
268  [ '{"a":"c"}/*c*/', '{"a":"c"}' ],
269  [ '/*c//d*/{"c":"b"}', '{"c":"b"}' ],
270  [ '{/*c*/"c":"b"}', '{"c":"b"}' ],
271  [ "/*\nc\r\n*/{\"c\":\"b\"}", '{"c":"b"}' ],
272  [ "//c\n{\"c\":\"b\"}", '{"c":"b"}' ],
273  [ "//c\r\n{\"c\":\"b\"}", '{"c":"b"}' ],
274  [ '{"a":"c"}//c', '{"a":"c"}' ],
275  [ "{\"a-c\"://c\n\"b\"}", '{"a-c":"b"}' ],
276  [ '{"/*a":"b"}', '{"/*a":"b"}' ],
277  [ '{"a":"//b"}', '{"a":"//b"}' ],
278  [ '{"a":"b/*c*/"}', '{"a":"b/*c*/"}' ],
279  [ "{\"\\\"/*a\":\"b\"}", "{\"\\\"/*a\":\"b\"}" ],
280  [ '', '' ],
281  [ '/*c', '' ],
282  [ '//c', '' ],
283  [ '"http://example.com"', '"http://example.com"' ],
284  [ "\0", "\0" ],
285  [ '"Blåbærsyltetøy"', '"Blåbærsyltetøy"' ],
286  ];
287  }
288 
295  public function testStripComments( $json, $expect ) {
296  $this->assertSame( $expect, FormatJson::stripComments( $json ) );
297  }
298 
299  public function provideParseStripComments() {
300  return [
301  [ '/* blah */true', true ],
302  [ "// blah \ntrue", true ],
303  [ '[ "a" , /* blah */ "b" ]', [ 'a', 'b' ] ],
304  ];
305  }
306 
314  public function testParseStripComments( $json, $expect ) {
316  $this->assertInstanceOf( 'Status', $st );
317  $this->assertTrue( $st->isGood() );
318  $this->assertEquals( $expect, $st->getValue() );
319  }
320 
327  private static function getEncodeTestCases( array $unescapedGroups ) {
328  $groups = [
329  'always' => [
330  // Forward slash (always unescaped)
331  '/' => '/',
332 
333  // Control characters
334  "\0" => '\u0000',
335  "\x08" => '\b',
336  "\t" => '\t',
337  "\n" => '\n',
338  "\r" => '\r',
339  "\f" => '\f',
340  "\x1f" => '\u001f', // representative example
341 
342  // Double quotes
343  '"' => '\"',
344 
345  // Backslashes
346  '\\' => '\\\\',
347  '\\\\' => '\\\\\\\\',
348  '\\u00e9' => '\\\u00e9', // security check for Unicode unescaping
349 
350  // Line terminators
351  "\xe2\x80\xa8" => '\u2028',
352  "\xe2\x80\xa9" => '\u2029',
353  ],
354  'unicode' => [
355  "\xc3\xa9" => '\u00e9',
356  "\xf0\x9d\x92\x9e" => '\ud835\udc9e', // U+1D49E, outside the BMP
357  ],
358  'xmlmeta' => [
359  '<' => '\u003C', // JSON_HEX_TAG uses uppercase hex digits
360  '>' => '\u003E',
361  '&' => '\u0026',
362  ],
363  ];
364 
365  $cases = [];
366  foreach ( $groups as $name => $rules ) {
367  $leaveUnescaped = in_array( $name, $unescapedGroups );
368  foreach ( $rules as $from => $to ) {
369  $cases[] = [ $from, '"' . ( $leaveUnescaped ? $from : $to ) . '"' ];
370  }
371  }
372 
373  return $cases;
374  }
375 }
FormatJson.
the array() calling protocol came about after MediaWiki 1.4rc1.
static provideEncoderPrettyPrinting()
testParseTryFixing($value, $expected, $jsoncParses=true, $expectedJsonc=null)
provideParseTryFixing
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
testEncodeDefault($from, $to)
provideEncodeDefault
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
testStripComments($json, $expect)
FormatJson::stripComments provideStripComments.
$value
testEncodeAllOk($from, $to)
provideEncodeAllOk
static parse($value, $options=0)
Decodes a JSON string.
Definition: FormatJson.php:201
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
testEncoderPrettyPrinting($pretty, $expectedIndent)
provideEncoderPrettyPrinting
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
Definition: FormatJson.php:34
testEncodeUtf8($from, $to)
provideEncodeUtf8
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1936
static provideParseErrors()
const TRY_FIXING
If set, attempts to fix invalid json.
Definition: FormatJson.php:71
const FORCE_ASSOC
If set, treat json objects '{...}' as associative arrays.
Definition: FormatJson.php:64
testParseStripComments($json, $expect)
FormatJson::parse FormatJson::stripComments provideParseStripComments.
const STRIP_COMMENTS
If set, strip comments from input before parsing as JSON.
Definition: FormatJson.php:78
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
static provideEncodeXmlMeta()
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
testParse($value)
provideParse
static provideEncodeAllOk()
static provideParseTryFixing()
Test data for testParseTryFixing.
$from
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static provideEncodeDefault()
static toObject($value)
Recursively convert arrays into stdClass.
testParseErrors($value)
provideParseErrors
static provideParse()
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
static provideEncodeUtf8()
testEncodeXmlMeta($from, $to)
provideEncodeXmlMeta
static stripComments($json)
Remove multiline and single line comments from an otherwise valid JSON input string.
Definition: FormatJson.php:272
static getEncodeTestCases(array $unescapedGroups)
Generate a set of test cases for a particular combination of encoder options.
const XMLMETA_OK
Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML...
Definition: FormatJson.php:46
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300