1<?php 2 3declare(strict_types=1); 4 5namespace JMS\Serializer\Tests\Serializer; 6 7use JMS\Serializer\SerializerBuilder; 8use JMS\Serializer\Tests\Fixtures\Author; 9use JMS\Serializer\Tests\Fixtures\AuthorList; 10use JMS\Serializer\Tests\Fixtures\Order; 11use JMS\Serializer\Tests\Fixtures\Price; 12use PHPUnit\Framework\TestCase; 13 14class ArrayTest extends TestCase 15{ 16 protected $serializer; 17 18 public function setUp() 19 { 20 $builder = SerializerBuilder::create(); 21 $this->serializer = $builder->build(); 22 } 23 24 public function testToArray() 25 { 26 $order = new Order(new Price(5)); 27 28 $expected = [ 29 'cost' => ['price' => 5], 30 ]; 31 32 $result = $this->serializer->toArray($order); 33 34 self::assertEquals($expected, $result); 35 } 36 37 /** 38 * @dataProvider scalarValues 39 */ 40 public function testToArrayWithScalar($input) 41 { 42 $this->expectException('JMS\Serializer\Exception\RuntimeException'); 43 $this->expectExceptionMessage(sprintf( 44 'The input data of type "%s" did not convert to an array, but got a result of type "%s".', 45 gettype($input), 46 gettype($input) 47 )); 48 $result = $this->serializer->toArray($input); 49 50 self::assertEquals([$input], $result); 51 } 52 53 public function scalarValues() 54 { 55 return [ 56 [42], 57 [3.14159], 58 ['helloworld'], 59 [true], 60 ]; 61 } 62 63 public function testFromArray() 64 { 65 $data = [ 66 'cost' => ['price' => 2.5], 67 ]; 68 69 $expected = new Order(new Price(2.5)); 70 $result = $this->serializer->fromArray($data, 'JMS\Serializer\Tests\Fixtures\Order'); 71 72 self::assertEquals($expected, $result); 73 } 74 75 public function testToArrayReturnsArrayObjectAsArray() 76 { 77 $result = $this->serializer->toArray(new Author(null)); 78 79 self::assertSame([], $result); 80 } 81 82 public function testToArrayConversNestedArrayObjects() 83 { 84 $list = new AuthorList(); 85 $list->add(new Author(null)); 86 87 $result = $this->serializer->toArray($list); 88 self::assertSame(['authors' => [[]]], $result); 89 } 90} 91