1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
namespace JMS\Serializer\Tests\Serializer\Doctrine;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\ORMException;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\UnitOfWork;
use JMS\Serializer\Builder\CallbackDriverFactory;
use JMS\Serializer\Builder\DefaultDriverFactory;
use JMS\Serializer\Construction\DoctrineObjectConstructor;
use JMS\Serializer\Construction\ObjectConstructorInterface;
use JMS\Serializer\Construction\UnserializeObjectConstructor;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\Driver\DoctrineTypeDriver;
use JMS\Serializer\Serializer;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Tests\Fixtures\Doctrine\Author;
use JMS\Serializer\Tests\Fixtures\Doctrine\IdentityFields\Server;
use JMS\Serializer\Tests\Fixtures\Doctrine\SingleTableInheritance\Excursion;
use JMS\Serializer\VisitorInterface;
class ObjectConstructorTest extends \PHPUnit_Framework_TestCase
{
/** @var ManagerRegistry */
private $registry;
/** @var Serializer */
private $serializer;
/** @var VisitorInterface */
private $visitor;
/** @var DeserializationContext */
private $context;
public function testFindEntity()
{
$em = $this->registry->getManager();
$author = new Author('John', 5);
$em->persist($author);
$em->flush();
$em->clear();
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback);
$authorFetched = $constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
$this->assertEquals($author, $authorFetched);
}
public function testFindManagedEntity()
{
$em = $this->registry->getManager();
$author = new Author('John', 5);
$em->persist($author);
$em->flush();
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback);
$authorFetched = $constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
$this->assertSame($author, $authorFetched);
}
public function testMissingAuthor()
{
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback);
$author = $constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
$this->assertNull($author);
}
public function testMissingAuthorFallback()
{
$author = new Author('John');
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$fallback->expects($this->once())->method('construct')->willReturn($author);
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, DoctrineObjectConstructor::ON_MISSING_FALLBACK);
$authorFetched = $constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
$this->assertSame($author, $authorFetched);
}
public function testMissingNotManaged()
{
$author = new \JMS\Serializer\Tests\Fixtures\DoctrinePHPCR\Author('foo');
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$fallback->expects($this->once())->method('construct')->willReturn($author);
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, DoctrineObjectConstructor::ON_MISSING_FALLBACK);
$authorFetched = $constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
$this->assertSame($author, $authorFetched);
}
public function testReference()
{
$em = $this->registry->getManager();
$author = new Author('John', 5);
$em->persist($author);
$em->flush();
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, DoctrineObjectConstructor::ON_MISSING_FALLBACK);
$authorFetched = $constructor->construct($this->visitor, $class, 5, $type, $this->context);
$this->assertSame($author, $authorFetched);
}
/**
* @expectedException \JMS\Serializer\Exception\ObjectConstructionException
*/
public function testMissingAuthorException()
{
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, DoctrineObjectConstructor::ON_MISSING_EXCEPTION);
$constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
}
/**
* @expectedException \JMS\Serializer\Exception\InvalidArgumentException
*/
public function testInvalidArg()
{
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, 'foo');
$constructor->construct($this->visitor, $class, ['id' => 5], $type, $this->context);
}
public function testMissingData()
{
$author = new Author('John');
$fallback = $this->getMockBuilder(ObjectConstructorInterface::class)->getMock();
$fallback->expects($this->once())->method('construct')->willReturn($author);
$type = array('name' => Author::class, 'params' => array());
$class = new ClassMetadata(Author::class);
$constructor = new DoctrineObjectConstructor($this->registry, $fallback, 'foo');
$authorFetched = $constructor->construct($this->visitor, $class, ['foo' => 5], $type, $this->context);
$this->assertSame($author, $authorFetched);
}
public function testNamingForIdentifierColumnIsConsidered()
{
$serializer = $this->createSerializerWithDoctrineObjectConstructor();
/** @var EntityManager $em */
$em = $this->registry->getManager();
$server = new Server('Linux', '127.0.0.1', 'home');
$em->persist($server);
$em->flush();
$em->clear();
$jsonData = '{"ip_address":"127.0.0.1", "server_id_extracted":"home", "name":"Windows"}';
/** @var Server $serverDeserialized */
$serverDeserialized = $serializer->deserialize($jsonData, Server::class, 'json');
static::assertSame(
$em->getUnitOfWork()->getEntityState($serverDeserialized),
UnitOfWork::STATE_MANAGED
);
}
protected function setUp()
{
$this->visitor = $this->getMockBuilder('JMS\Serializer\VisitorInterface')->getMock();
$this->context = $this->getMockBuilder('JMS\Serializer\DeserializationContext')->getMock();
$connection = $this->createConnection();
$entityManager = $this->createEntityManager($connection);
$this->registry = $registry = new SimpleBaseManagerRegistry(
function ($id) use ($connection, $entityManager) {
switch ($id) {
case 'default_connection':
return $connection;
case 'default_manager':
return $entityManager;
default:
throw new \RuntimeException(sprintf('Unknown service id "%s".', $id));
}
}
);
$this->serializer = SerializerBuilder::create()
->setMetadataDriverFactory(new CallbackDriverFactory(
function (array $metadataDirs, Reader $annotationReader) use ($registry) {
$defaultFactory = new DefaultDriverFactory();
return new DoctrineTypeDriver($defaultFactory->createDriver($metadataDirs, $annotationReader), $registry);
}
))
->build();
$this->prepareDatabase();
}
private function prepareDatabase()
{
/** @var EntityManager $em */
$em = $this->registry->getManager();
$tool = new SchemaTool($em);
$tool->createSchema($em->getMetadataFactory()->getAllMetadata());
}
private function createConnection()
{
$con = DriverManager::getConnection(array(
'driver' => 'pdo_sqlite',
'memory' => true,
));
return $con;
}
private function createEntityManager(Connection $con)
{
$cfg = new Configuration();
$cfg->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader(), array(
__DIR__ . '/../../Fixtures/Doctrine',
)));
$cfg->setAutoGenerateProxyClasses(true);
$cfg->setProxyNamespace('JMS\Serializer\DoctrineProxy');
$cfg->setProxyDir(sys_get_temp_dir() . '/serializer-test-proxies');
$em = EntityManager::create($con, $cfg);
return $em;
}
/**
* @return \JMS\Serializer\SerializerInterface
*/
private function createSerializerWithDoctrineObjectConstructor()
{
return SerializerBuilder::create()
->setObjectConstructor(
new DoctrineObjectConstructor(
$this->registry,
new UnserializeObjectConstructor(),
DoctrineObjectConstructor::ON_MISSING_FALLBACK
)
)
->addDefaultHandlers()
->build();
}
}
\Doctrine\DBAL\Types\Type::addType('Author', 'Doctrine\DBAL\Types\StringType');
\Doctrine\DBAL\Types\Type::addType('some_custom_type', 'Doctrine\DBAL\Types\StringType');
class SimpleBaseManagerRegistry extends AbstractManagerRegistry
{
private $services = array();
private $serviceCreator;
public function __construct($serviceCreator, $name = 'anonymous', array $connections = array('default' => 'default_connection'), array $managers = array('default' => 'default_manager'), $defaultConnection = null, $defaultManager = null, $proxyInterface = 'Doctrine\Common\Persistence\Proxy')
{
if (null === $defaultConnection) {
$defaultConnection = key($connections);
}
if (null === $defaultManager) {
$defaultManager = key($managers);
}
parent::__construct($name, $connections, $managers, $defaultConnection, $defaultManager, $proxyInterface);
if (!is_callable($serviceCreator)) {
throw new \InvalidArgumentException('$serviceCreator must be a valid callable.');
}
$this->serviceCreator = $serviceCreator;
}
public function getService($name)
{
if (isset($this->services[$name])) {
return $this->services[$name];
}
return $this->services[$name] = call_user_func($this->serviceCreator, $name);
}
public function resetService($name)
{
unset($this->services[$name]);
}
public function getAliasNamespace($alias)
{
foreach (array_keys($this->getManagers()) as $name) {
$manager = $this->getManager($name);
if ($manager instanceof EntityManager) {
try {
return $manager->getConfiguration()->getEntityNamespace($alias);
} catch (ORMException $ex) {
// Probably mapped by another entity manager, or invalid, just ignore this here.
}
} else {
throw new \LogicException(sprintf('Unsupported manager type "%s".', get_class($manager)));
}
}
throw new \RuntimeException(sprintf('The namespace alias "%s" is not known to any manager.', $alias));
}
}