MediaWiki REL1_33
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 testEncodeFail() {
113 // Set up a recursive object that can't be encoded.
114 $a = new stdClass;
115 $b = new stdClass;
116 $a->b = $b;
117 $b->a = $a;
118 $this->assertFalse( FormatJson::encode( $a ) );
119 }
120
121 public function testDecodeReturnType() {
122 $this->assertInternalType(
123 'object',
124 FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}' ),
125 'Default to object'
126 );
127
128 $this->assertInternalType(
129 'array',
130 FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}', true ),
131 'Optional array'
132 );
133 }
134
135 public static function provideParse() {
136 return [
137 [ null ],
138 [ true ],
139 [ false ],
140 [ 0 ],
141 [ 1 ],
142 [ 1.2 ],
143 [ '' ],
144 [ 'str' ],
145 [ [ 0, 1, 2 ] ],
146 [ [ 'a' => 'b' ] ],
147 [ [ 'a' => 'b' ] ],
148 [ [ 'a' => 'b', 'x' => [ 'c' => 'd' ] ] ],
149 ];
150 }
151
157 public static function toObject( $value ) {
158 return !is_array( $value ) ? $value : (object)array_map( __METHOD__, $value );
159 }
160
165 public function testParse( $value ) {
166 $expected = self::toObject( $value );
167 $json = FormatJson::encode( $expected, false, FormatJson::ALL_OK );
168 $this->assertJson( $json );
169
170 $st = FormatJson::parse( $json );
171 $this->assertInstanceOf( Status::class, $st );
172 $this->assertTrue( $st->isGood() );
173 $this->assertEquals( $expected, $st->getValue() );
174
175 $st = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
176 $this->assertInstanceOf( Status::class, $st );
177 $this->assertTrue( $st->isGood() );
178 $this->assertEquals( $value, $st->getValue() );
179 }
180
199 public static function provideParseTryFixing() {
200 return [
201 [ "[,]", '[]', false ],
202 [ "[ , ]", '[]', false ],
203 [ "[ , }", false ],
204 [ '[1],', false, true, '[1]' ],
205 [ "[1,]", '[1]' ],
206 [ "[1\n,]", '[1]' ],
207 [ "[1,\n]", '[1]' ],
208 [ "[1,]\n", '[1]' ],
209 [ "[1\n,\n]\n", '[1]' ],
210 [ '["a,",]', '["a,"]' ],
211 [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ],
212 // I wish we could parse this, but would need quote parsing
213 [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ],
214 [ '[1,,]', false, false, '[1]' ],
215 ];
216 }
217
226 public function testParseTryFixing(
227 $value, $expected,
228 $jsoncParses = true, $expectedJsonc = null
229 ) {
230 // PHP5 results are always expected to have isGood() === false
231 $expectedGoodStatus = false;
232
233 // Check to see if json parser allows trailing commas
234 if ( json_decode( '[1,]' ) !== null ) {
235 // Use json-c specific expected result if provided
236 $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc;
237 // If json-c parses the value natively, expect isGood() === true
238 $expectedGoodStatus = $jsoncParses;
239 }
240
241 $st = FormatJson::parse( $value, FormatJson::TRY_FIXING );
242 $this->assertInstanceOf( Status::class, $st );
243 if ( $expected === false ) {
244 $this->assertFalse( $st->isOK(), 'Expected isOK() == false' );
245 } else {
246 $this->assertSame( $expectedGoodStatus, $st->isGood(),
247 'Expected isGood() == ' . ( $expectedGoodStatus ? 'true' : 'false' )
248 );
249 $this->assertTrue( $st->isOK(), 'Expected isOK == true' );
250 $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK );
251 $this->assertEquals( $expected, $val );
252 }
253 }
254
255 public static function provideParseErrors() {
256 return [
257 [ 'aaa' ],
258 [ '{"j": 1 ] }' ],
259 ];
260 }
261
266 public function testParseErrors( $value ) {
267 $st = FormatJson::parse( $value );
268 $this->assertInstanceOf( Status::class, $st );
269 $this->assertFalse( $st->isOK() );
270 }
271
272 public function provideStripComments() {
273 return [
274 [ '{"a":"b"}', '{"a":"b"}' ],
275 [ "{\"a\":\"b\"}\n", "{\"a\":\"b\"}\n" ],
276 [ '/*c*/{"c":"b"}', '{"c":"b"}' ],
277 [ '{"a":"c"}/*c*/', '{"a":"c"}' ],
278 [ '/*c//d*/{"c":"b"}', '{"c":"b"}' ],
279 [ '{/*c*/"c":"b"}', '{"c":"b"}' ],
280 [ "/*\nc\r\n*/{\"c\":\"b\"}", '{"c":"b"}' ],
281 [ "//c\n{\"c\":\"b\"}", '{"c":"b"}' ],
282 [ "//c\r\n{\"c\":\"b\"}", '{"c":"b"}' ],
283 [ '{"a":"c"}//c', '{"a":"c"}' ],
284 [ "{\"a-c\"://c\n\"b\"}", '{"a-c":"b"}' ],
285 [ '{"/*a":"b"}', '{"/*a":"b"}' ],
286 [ '{"a":"//b"}', '{"a":"//b"}' ],
287 [ '{"a":"b/*c*/"}', '{"a":"b/*c*/"}' ],
288 [ "{\"\\\"/*a\":\"b\"}", "{\"\\\"/*a\":\"b\"}" ],
289 [ '', '' ],
290 [ '/*c', '' ],
291 [ '//c', '' ],
292 [ '"http://example.com"', '"http://example.com"' ],
293 [ "\0", "\0" ],
294 [ '"Blåbærsyltetøy"', '"Blåbærsyltetøy"' ],
295 ];
296 }
297
304 public function testStripComments( $json, $expect ) {
305 $this->assertSame( $expect, FormatJson::stripComments( $json ) );
306 }
307
308 public function provideParseStripComments() {
309 return [
310 [ '/* blah */true', true ],
311 [ "// blah \ntrue", true ],
312 [ '[ "a" , /* blah */ "b" ]', [ 'a', 'b' ] ],
313 ];
314 }
315
323 public function testParseStripComments( $json, $expect ) {
324 $st = FormatJson::parse( $json, FormatJson::STRIP_COMMENTS );
325 $this->assertInstanceOf( Status::class, $st );
326 $this->assertTrue( $st->isGood() );
327 $this->assertEquals( $expect, $st->getValue() );
328 }
329
336 private static function getEncodeTestCases( array $unescapedGroups ) {
337 $groups = [
338 'always' => [
339 // Forward slash (always unescaped)
340 '/' => '/',
341
342 // Control characters
343 "\0" => '\u0000',
344 "\x08" => '\b',
345 "\t" => '\t',
346 "\n" => '\n',
347 "\r" => '\r',
348 "\f" => '\f',
349 "\x1f" => '\u001f', // representative example
350
351 // Double quotes
352 '"' => '\"',
353
354 // Backslashes
355 '\\' => '\\\\',
356 '\\\\' => '\\\\\\\\',
357 '\\u00e9' => '\\\u00e9', // security check for Unicode unescaping
358
359 // Line terminators
360 "\xe2\x80\xa8" => '\u2028',
361 "\xe2\x80\xa9" => '\u2029',
362 ],
363 'unicode' => [
364 "\xc3\xa9" => '\u00e9',
365 "\xf0\x9d\x92\x9e" => '\ud835\udc9e', // U+1D49E, outside the BMP
366 ],
367 'xmlmeta' => [
368 '<' => '\u003C', // JSON_HEX_TAG uses uppercase hex digits
369 '>' => '\u003E',
370 '&' => '\u0026',
371 ],
372 ];
373
374 $cases = [];
375 foreach ( $groups as $name => $rules ) {
376 $leaveUnescaped = in_array( $name, $unescapedGroups );
377 foreach ( $rules as $from => $to ) {
378 $cases[] = [ $from, '"' . ( $leaveUnescaped ? $from : $to ) . '"' ];
379 }
380 }
381
382 return $cases;
383 }
384
385 public function provideEmptyJsonKeyStrings() {
386 return [
387 [
388 '{"":"foo"}',
389 '{"":"foo"}',
390 ''
391 ],
392 [
393 '{"_empty_":"foo"}',
394 '{"_empty_":"foo"}',
395 '_empty_' ],
396 [
397 '{"\u005F\u0065\u006D\u0070\u0074\u0079\u005F":"foo"}',
398 '{"_empty_":"foo"}',
399 '_empty_'
400 ],
401 [
402 '{"_empty_":"bar","":"foo"}',
403 '{"_empty_":"bar","":"foo"}',
404 ''
405 ],
406 [
407 '{"":"bar","_empty_":"foo"}',
408 '{"":"bar","_empty_":"foo"}',
409 '_empty_'
410 ]
411 ];
412 }
413
423 public function testEmptyJsonKeyArray( $json, $expect, $php71Name ) {
424 // Decoding to array is consistent across supported PHP versions
425 $this->assertSame( $expect, FormatJson::encode(
426 FormatJson::decode( $json, true ) ) );
427
428 // Decoding to object differs between supported PHP versions
429 $obj = FormatJson::decode( $json );
430 if ( version_compare( PHP_VERSION, '7.1', '<' ) ) {
431 $this->assertEquals( 'foo', $obj->_empty_ );
432 } else {
433 $this->assertEquals( 'foo', $obj->{$php71Name} );
434 }
435 }
436}
testParse( $value)
provideParse
testParseTryFixing( $value, $expected, $jsoncParses=true, $expectedJsonc=null)
provideParseTryFixing
static provideEncodeAllOk()
testParseErrors( $value)
provideParseErrors
static provideEncoderPrettyPrinting()
testStripComments( $json, $expect)
FormatJson::stripComments provideStripComments.
testEncodeUtf8( $from, $to)
provideEncodeUtf8
static provideEncodeUtf8()
static provideEncodeXmlMeta()
static provideParseErrors()
static provideParseTryFixing()
Test data for testParseTryFixing.
testEncodeXmlMeta( $from, $to)
provideEncodeXmlMeta
testEmptyJsonKeyArray( $json, $expect, $php71Name)
FormatJson::encode FormatJson::decode provideEmptyJsonKeyStrings.
testEncodeAllOk( $from, $to)
provideEncodeAllOk
testParseStripComments( $json, $expect)
FormatJson::parse FormatJson::stripComments provideParseStripComments.
testEncodeDefault( $from, $to)
provideEncodeDefault
static toObject( $value)
Recursively convert arrays into stdClass.
static provideEncodeDefault()
testEncoderPrettyPrinting( $pretty, $expectedIndent)
provideEncoderPrettyPrinting
static getEncodeTestCases(array $unescapedGroups)
Generate a set of test cases for a particular combination of encoder options.
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
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 $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:62
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition hooks.txt:783
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:2004
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
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:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))