GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 457e68...90832a )
by Juan
02:34
created

JsonSerializerTest::testCustomObjectSerializer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace Zumba\JsonSerializer\Test;
4
5
use Zumba\JsonSerializer\JsonSerializer;
6
use stdClass;
7
use SuperClosure\Serializer as ClosureSerializer;
8
9
class JsonSerializerTest extends \PHPUnit_Framework_TestCase
10
{
11
12
    /**
13
     * Serializer instance
14
     *
15
     * @var JsonSerializer
16
     */
17
    protected $serializer;
18
19
    /**
20
     * Test case setup
21
     *
22
     * @return void
23
     */
24
    public function setUp()
25
    {
26
        parent::setUp();
27
        $customObjectSerializerMap['Zumba\\JsonSerializer\\Test\\SupportClasses\\MyType'] = new \Zumba\JsonSerializer\Test\SupportClasses\MyTypeSerializer();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$customObjectSerializerMap was never initialized. Although not strictly required by PHP, it is generally a good practice to add $customObjectSerializerMap = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
28
        $this->serializer = new JsonSerializer(null, $customObjectSerializerMap);
29
    }
30
31
    /**
32
     * Test serialization of scalar values
33
     *
34
     * @dataProvider scalarData
35
     * @param mixed $scalar
36
     * @param string $jsoned
37
     * @return void
38
     */
39
    public function testSerializeScalar($scalar, $jsoned)
40
    {
41
        $this->assertSame($jsoned, $this->serializer->serialize($scalar));
42
    }
43
44
    /**
45
     * Test serialization of float values with locale
46
     *
47
     * @return void
48
     */
49
    public function testSerializeFloatLocalized()
50
    {
51
        $possibleLocales = ['fr_FR', 'fr_FR.utf8', 'fr', 'fra', 'French'];
52
        $originalLocale = setlocale(LC_NUMERIC, 0);
53
        if (!setlocale(LC_NUMERIC, $possibleLocales)) {
54
            $this->markTestSkipped('Unable to set an i18n locale.');
55
        }
56
57
        $data = [1.0, 1.1, 0.00000000001, 1.999999999999, 223423.123456789, 1e5, 1e11];
58
        $expected = '[1.0,1.1,1.0e-11,1.999999999999,223423.12345679,100000.0,100000000000.0]';
59
        $this->assertSame($expected, $this->serializer->serialize($data));
60
61
        setlocale(LC_NUMERIC, $originalLocale);
62
    }
63
    /**
64
     * Test unserialization of scalar values
65
     *
66
     * @dataProvider scalarData
67
     * @param mixed $scalar
68
     * @param string $jsoned
69
     * @return void
70
     */
71
    public function testUnserializeScalar($scalar, $jsoned)
72
    {
73
        $this->assertSame($scalar, $this->serializer->unserialize($jsoned));
74
    }
75
76
    /**
77
     * List of scalar data
78
     *
79
     * @return array
80
     */
81
    public function scalarData()
82
    {
83
        return array(
84
            array('testing', '"testing"'),
85
            array(123, '123'),
86
            array(0, '0'),
87
            array(0.0, '0.0'),
88
            array(17.0, '17.0'),
89
            array(17e1, '170.0'),
90
            array(17.2, '17.2'),
91
            array(true, 'true'),
92
            array(false, 'false'),
93
            array(null, 'null'),
94
            // Non UTF8
95
            array('ßåö', '"ßåö"')
96
        );
97
    }
98
99
    /**
100
     * Test the serialization of resources
101
     *
102
     * @return void
103
     */
104
    public function testSerializeResource()
105
    {
106
        $this->setExpectedException('Zumba\JsonSerializer\Exception\JsonSerializerException');
107
        $this->serializer->serialize(fopen(__FILE__, 'r'));
108
    }
109
110
    /**
111
     * Test the serialization of closures when not providing closure serializer
112
     *
113
     * @return void
114
     */
115
    public function testSerializeClosureWithoutSerializer()
116
    {
117
        $this->setExpectedException('Zumba\JsonSerializer\Exception\JsonSerializerException');
118
        $this->serializer->serialize(array('func' => function () {
119
            echo 'whoops';
120
        }));
121
    }
122
123
    /**
124
     * Test serialization of array without objects
125
     *
126
     * @dataProvider arrayNoObjectData
127
     * @param array $array
128
     * @param string $jsoned
129
     * @return void
130
     */
131
    public function testSerializeArrayNoObject($array, $jsoned)
132
    {
133
        $this->assertSame($jsoned, $this->serializer->serialize($array));
134
    }
135
136
    /**
137
     * Test unserialization of array without objects
138
     *
139
     * @dataProvider arrayNoObjectData
140
     * @param array $array
141
     * @param string $jsoned
142
     * @return void
143
     */
144
    public function testUnserializeArrayNoObject($array, $jsoned)
145
    {
146
        $this->assertSame($array, $this->serializer->unserialize($jsoned));
147
    }
148
149
    /**
150
     * List of array data
151
     *
152
     * @return array
153
     */
154
    public function arrayNoObjectData()
155
    {
156
        return array(
157
            array(array(1, 2, 3), '[1,2,3]'),
158
            array(array(1, 'abc', false), '[1,"abc",false]'),
159
            array(array('a' => 1, 'b' => 2, 'c' => 3), '{"a":1,"b":2,"c":3}'),
160
            array(array('integer' => 1, 'string' => 'abc', 'bool' => false), '{"integer":1,"string":"abc","bool":false}'),
161
            array(array(1, array('nested')), '[1,["nested"]]'),
162
            array(array('integer' => 1, 'array' => array('nested')), '{"integer":1,"array":["nested"]}'),
163
            array(array('integer' => 1, 'array' => array('nested' => 'object')), '{"integer":1,"array":{"nested":"object"}}'),
164
            array(array(1.0, 2, 3e1), '[1.0,2,30.0]'),
165
        );
166
    }
167
168
    /**
169
     * Test serialization of objects
170
     *
171
     * @return void
172
     */
173
    public function testSerializeObject()
174
    {
175
        $obj = new stdClass();
176
        $this->assertSame('{"@type":"stdClass"}', $this->serializer->serialize($obj));
177
178
        $obj = $empty = new SupportClasses\EmptyClass();
179
        $this->assertSame('{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"}', $this->serializer->serialize($obj));
180
181
        $obj = new SupportClasses\AllVisibilities();
182
        $expected = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\AllVisibilities","pub":"this is public","prot":"protected","priv":"dont tell anyone"}';
183
        $this->assertSame($expected, $this->serializer->serialize($obj));
184
185
        $obj->pub = 'new value';
186
        $expected = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\AllVisibilities","pub":"new value","prot":"protected","priv":"dont tell anyone"}';
187
        $this->assertSame($expected, $this->serializer->serialize($obj));
188
189
        $obj->pub = $empty;
0 ignored issues
show
Documentation Bug introduced by
It seems like $empty of type object<Zumba\JsonSeriali...portClasses\EmptyClass> is incompatible with the declared type string of property $pub.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
190
        $expected = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\AllVisibilities","pub":{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"},"prot":"protected","priv":"dont tell anyone"}';
191
        $this->assertSame($expected, $this->serializer->serialize($obj));
192
193
        $array = array('instance' => $empty);
194
        $expected = '{"instance":{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"}}';
195
        $this->assertSame($expected, $this->serializer->serialize($array));
196
197
        $obj = new stdClass();
198
        $obj->total = 10.0;
199
        $obj->discount = 0.0;
200
        $expected = '{"@type":"stdClass","total":10.0,"discount":0.0}';
201
        $this->assertSame($expected, $this->serializer->serialize($obj));
202
    }
203
204
    /**
205
     * Test unserialization of objects
206
     *
207
     * @return void
208
     */
209
    public function testUnserializeObjects()
210
    {
211
        $serialized = '{"@type":"stdClass"}';
212
        $obj = $this->serializer->unserialize($serialized);
213
        $this->assertInstanceOf('stdClass', $obj);
214
215
        $serialized = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"}';
216
        $obj = $this->serializer->unserialize($serialized);
217
        $this->assertInstanceOf('Zumba\JsonSerializer\Test\SupportClasses\EmptyClass', $obj);
218
219
        $serialized = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\AllVisibilities","pub":{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"},"prot":"protected","priv":"dont tell anyone"}';
220
        $obj = $this->serializer->unserialize($serialized);
221
        $this->assertInstanceOf('Zumba\JsonSerializer\Test\SupportClasses\AllVisibilities', $obj);
222
        $this->assertInstanceOf('Zumba\JsonSerializer\Test\SupportClasses\EmptyClass', $obj->pub);
223
        $this->assertAttributeSame('protected', 'prot', $obj);
224
        $this->assertAttributeSame('dont tell anyone', 'priv', $obj);
225
226
        $serialized = '{"instance":{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\EmptyClass"}}';
227
        $array = $this->serializer->unserialize($serialized);
228
        $this->assertTrue(is_array($array));
229
        $this->assertInstanceOf('Zumba\JsonSerializer\Test\SupportClasses\EmptyClass', $array['instance']);
230
    }
231
232
233
    /**
234
     * Test serialization of objects using the custom serializers
235
     *
236
     * @return void
237
     */
238
    public function testCustomObjectSerializer()
239
    {
240
        $obj = new SupportClasses\MyType();
241
        $obj->field1 = 'x';
242
        $obj->field2 = 'y';
243
        $this->assertSame('{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MyType","fields":"x y"}', $this->serializer->serialize($obj));
244
    }
245
246
    /**
247
     * Test unserialization of objects using the custom serializers
248
     *
249
     * @return void
250
     */
251
    public function testCustomObjectsUnserializer()
252
    {
253
        $serialized = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MyType","fields":"x y"}';
254
        $obj = $this->serializer->unserialize($serialized);
255
        $this->assertInstanceOf('Zumba\JsonSerializer\Test\SupportClasses\MyType', $obj);
256
        $this->assertAttributeSame('x', 'field1', $obj);
257
        $this->assertAttributeSame('y', 'field2', $obj);
258
    }
259
260
    /**
261
     * Test magic serialization methods
262
     *
263
     * @return void
264
     */
265
    public function testSerializationMagicMethods()
266
    {
267
        $obj = new SupportClasses\MagicClass();
268
        $serialized = '{"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MagicClass","show":true}';
269
        $this->assertSame($serialized, $this->serializer->serialize($obj));
270
        $this->assertFalse($obj->woke);
271
272
        $obj = $this->serializer->unserialize($serialized);
273
        $this->assertTrue($obj->woke);
274
    }
275
276
    /**
277
     * Test serialization of DateTime classes
278
     *
279
     * Some interal classes, such as DateTime, cannot be initialized with
280
     * ReflectionClass::newInstanceWithoutConstructor()
281
     *
282
     * @return void
283
     */
284
    public function testSerializationOfDateTime()
285
    {
286
        $date = new \DateTime('2014-06-15 12:00:00', new \DateTimeZone('UTC'));
287
        $obj = $this->serializer->unserialize($this->serializer->serialize($date));
288
        $this->assertSame($date->getTimestamp(), $obj->getTimestamp());
289
    }
290
291
    /**
292
     * Test the serialization of closures providing closure serializer
293
     *
294
     * @return void
295
     */
296
    public function testSerializationOfClosure()
297
    {
298
        if (!class_exists('SuperClosure\Serializer')) {
299
            $this->markTestSkipped('SuperClosure is not installed.');
300
        }
301
302
        $closureSerializer = new ClosureSerializer();
303
        $serializer = new JsonSerializer($closureSerializer);
304
        $serialized = $serializer->serialize(array(
305
            'func' => function () {
306
                return 'it works';
307
            },
308
            'nice' => true
309
        ));
310
311
        $unserialized = $serializer->unserialize($serialized);
312
        $this->assertTrue(is_array($unserialized));
313
        $this->assertTrue($unserialized['nice']);
314
        $this->assertInstanceOf('Closure', $unserialized['func']);
315
        $this->assertSame('it works', $unserialized['func']());
316
    }
317
318
    /**
319
     * Test the unserialization of closures without providing closure serializer
320
     *
321
     * @return void
322
     */
323
    public function testUnserializeOfClosureWithoutSerializer()
324
    {
325
        if (!class_exists('SuperClosure\Serializer')) {
326
            $this->markTestSkipped('SuperClosure is not installed.');
327
        }
328
329
        $closureSerializer = new ClosureSerializer();
330
        $serializer = new JsonSerializer($closureSerializer);
331
        $serialized = $serializer->serialize(array(
332
            'func' => function () {
333
                return 'it works';
334
            },
335
            'nice' => true
336
        ));
337
338
        $this->setExpectedException('Zumba\JsonSerializer\Exception\JsonSerializerException');
339
        $this->serializer->unserialize($serialized);
340
    }
341
342
    /**
343
     * Test unserialize of unknown class
344
     *
345
     * @return void
346
     */
347
    public function testUnserializeUnknownClass()
348
    {
349
        $this->setExpectedException('Zumba\JsonSerializer\Exception\JsonSerializerException');
350
        $serialized = '{"@type":"UnknownClass"}';
351
        $this->serializer->unserialize($serialized);
352
    }
353
354
    /**
355
     * Test serialization of undeclared properties
356
     *
357
     * @return void
358
     */
359
    public function testSerializationUndeclaredProperties()
360
    {
361
        $obj = new stdClass();
362
        $obj->param1 = true;
363
        $obj->param2 = 'store me, please';
364
        $serialized = '{"@type":"stdClass","param1":true,"param2":"store me, please"}';
365
        $this->assertSame($serialized, $this->serializer->serialize($obj));
366
367
        $obj2 = $this->serializer->unserialize($serialized);
368
        $this->assertInstanceOf('stdClass', $obj2);
369
        $this->assertTrue($obj2->param1);
370
        $this->assertSame('store me, please', $obj2->param2);
371
372
        $serialized = '{"@type":"stdClass","sub":{"@type":"stdClass","key":"value"}}';
373
        $obj = $this->serializer->unserialize($serialized);
374
        $this->assertInstanceOf('stdClass', $obj->sub);
375
        $this->assertSame('value', $obj->sub->key);
376
    }
377
378
    /**
379
     * Test serialize with recursion
380
     *
381
     * @return void
382
     */
383
    public function testSerializeRecursion()
384
    {
385
        $c1 = new stdClass();
386
        $c1->c2 = new stdClass();
387
        $c1->c2->c3 = new stdClass();
388
        $c1->c2->c3->c1 = $c1;
389
        $c1->something = 'ok';
390
        $c1->c2->c3->ok = true;
391
392
        $expected = '{"@type":"stdClass","c2":{"@type":"stdClass","c3":{"@type":"stdClass","c1":{"@type":"@0"},"ok":true}},"something":"ok"}';
393
        $this->assertSame($expected, $this->serializer->serialize($c1));
394
395
        $c1 = new stdClass();
396
        $c1->mirror = $c1;
397
        $expected = '{"@type":"stdClass","mirror":{"@type":"@0"}}';
398
        $this->assertSame($expected, $this->serializer->serialize($c1));
399
    }
400
401
    /**
402
     * Test unserialize with recursion
403
     *
404
     * @return void
405
     */
406
    public function testUnserializeRecursion()
407
    {
408
        $serialized = '{"@type":"stdClass","c2":{"@type":"stdClass","c3":{"@type":"stdClass","c1":{"@type":"@0"},"ok":true}},"something":"ok"}';
409
        $obj = $this->serializer->unserialize($serialized);
410
        $this->assertTrue($obj->c2->c3->ok);
411
        $this->assertSame($obj, $obj->c2->c3->c1);
412
        $this->assertNotSame($obj, $obj->c2);
413
414
        $serialized = '{"@type":"stdClass","c2":{"@type":"stdClass","c3":{"@type":"stdClass","c1":{"@type":"@0"},"c2":{"@type":"@1"},"c3":{"@type":"@2"}},"c3_copy":{"@type":"@2"}}}';
415
        $obj = $this->serializer->unserialize($serialized);
416
        $this->assertSame($obj, $obj->c2->c3->c1);
417
        $this->assertSame($obj->c2, $obj->c2->c3->c2);
418
        $this->assertSame($obj->c2->c3, $obj->c2->c3->c3);
419
        $this->assertSame($obj->c2->c3_copy, $obj->c2->c3);
420
    }
421
422
    /**
423
     * Test unserialize with bad JSON
424
     *
425
     * @return void
426
     */
427
    public function testUnserializeBadJSON()
428
    {
429
        $this->setExpectedException('Zumba\Exception\JsonSerializerException');
430
        $this->serializer->unserialize('[this is not a valid json!}');
431
    }
432
433
    /**
434
     * The test attempts to serialize an array containing a NAN
435
     */
436
    public function testSerializeInvalidData()
437
    {
438
        if (PHP_VERSION_ID < 50500) {
439
            $this->markTestSkipped('PHP 5.4 raises a warning when encoding NAN, which fails the test.');
440
        }
441
442
        $this->setExpectedException('Zumba\Exception\JsonSerializerException');
443
        $this->serializer->serialize(array(NAN));
444
    }
445
446
    /**
447
     * @return void
448
     */
449
    public function testSerializeBinaryStringScalar()
450
    {
451
        $data = '';
452
        for ($i = 0; $i <= 255; $i++) {
453
            $data .= chr($i);
454
        }
455
456
        $unserialized = $this->serializer->unserialize($this->serializer->serialize($data));
457
        $this->assertSame($data, $unserialized);
458
    }
459
460
    /**
461
     * @return void
462
     */
463
    public function testSerializeArrayWithBinaryStringsAsValues()
464
    {
465
        $data = '';
466
        for ($i = 0; $i <= 255; $i++) {
467
            $data .= chr($i);
468
        }
469
470
        $data = [$data, "$data 1", "$data 2"];
471
        $unserialized = $this->serializer->unserialize($this->serializer->serialize($data));
472
        $this->assertSame($data, $unserialized);
473
    }
474
475
    /**
476
     * Starting from 1 and not from 0 because php cannot handle the nil character (\u0000) in json keys as per:
477
     * https://github.com/remicollet/pecl-json-c/issues/7
478
     * https://github.com/json-c/json-c/issues/108
479
     *
480
     * @return void
481
     */
482
    public function testSerializeArrayWithBinaryStringsAsKeys()
483
    {
484
        $data = '';
485
        for ($i = 1; $i <= 255; $i++) {
486
            $data .= chr($i);
487
        }
488
489
        $data = [$data => $data, "$data 1" => 'something'];
490
        $unserialized = $this->serializer->unserialize($this->serializer->serialize($data));
491
        $this->assertSame($data, $unserialized);
492
    }
493
494
    /**
495
     * @return void
496
     */
497
    public function testSerializeObjectWithBinaryStrings()
498
    {
499
        $data = '';
500
        for ($i = 0; $i <= 255; $i++) {
501
            $data .= chr($i);
502
        }
503
504
        $obj = new \stdClass();
505
        $obj->string = $data;
506
        $unserialized = $this->serializer->unserialize($this->serializer->serialize($obj));
507
        $this->assertInstanceOf('stdClass', $obj);
508
        $this->assertSame($obj->string, $unserialized->string);
509
    }
510
511
    /*
512
     * Test namespace change (backward compatibility)
513
     *
514
     * @return void
515
     * @deprecated
516
     */
517
    public function testNamespaceRename()
518
    {
519
        $serializer = new \Zumba\Util\JsonSerializer();
0 ignored issues
show
Unused Code introduced by
$serializer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Deprecated Code introduced by
The class Zumba\Util\JsonSerializer has been deprecated with message: Will be removed on the 3.0.0. Use Zumba\JsonSerializer\JsonSerializer instead

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
520
521
        $f = fopen(__FILE__, 'r');
522
        $this->setExpectedException('Zumba\Exception\JsonSerializerException');
523
        $this->serializer->serialize($f);
524
    }
525
}
526