forked from doctrine/orm
/
ClassMetadataFactoryTest.php
516 lines (407 loc) · 18.3 KB
/
ClassMetadataFactoryTest.php
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
<?php
declare(strict_types=1);
namespace Doctrine\Tests\ORM\Mapping;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\Mapping;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Mapping\Driver\MappingDriver;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Reflection\RuntimeReflectionService;
use Doctrine\ORM\Sequencing\Generator;
use Doctrine\Tests\Mocks\ConnectionMock;
use Doctrine\Tests\Mocks\DriverMock;
use Doctrine\Tests\Mocks\EntityManagerMock;
use Doctrine\Tests\Mocks\MetadataDriverMock;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\DDC4006\DDC4006User;
use Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass;
use Doctrine\Tests\Models\JoinedInheritanceType\ChildClass;
use Doctrine\Tests\Models\JoinedInheritanceType\RootClass;
use Doctrine\Tests\Models\Quote;
use Doctrine\Tests\OrmTestCase;
use DoctrineGlobalArticle;
use function array_search;
use function reset;
use function sprintf;
class ClassMetadataFactoryTest extends OrmTestCase
{
public function testGetMetadataForSingleClass() : void
{
$mockDriver = new MetadataDriverMock();
$entityManager = $this->createEntityManager($mockDriver);
$conn = $entityManager->getConnection();
$mockPlatform = $conn->getDatabasePlatform();
$mockPlatform->setPrefersSequences(true);
$mockPlatform->setPrefersIdentityColumns(false);
$cm1 = $this->createValidClassMetadata();
// SUT
$cmf = new ClassMetadataFactory();
$cmf->setEntityManager($entityManager);
$cmf->setMetadataFor($cm1->getClassName(), $cm1);
// Prechecks
self::assertCount(0, $cm1->getAncestorsIterator());
self::assertEquals(Mapping\InheritanceType::NONE, $cm1->inheritanceType);
self::assertEquals(Mapping\GeneratorType::AUTO, $cm1->getProperty('id')->getValueGenerator()->getType());
self::assertTrue($cm1->hasField('name'));
self::assertCount(4, $cm1->getDeclaredPropertiesIterator()); // 2 fields + 2 associations
self::assertEquals('group', $cm1->table->getName());
// Go
$cmMap1 = $cmf->getMetadataFor($cm1->getClassName());
self::assertSame($cm1, $cmMap1);
self::assertEquals('group', $cmMap1->table->getName());
self::assertCount(0, $cmMap1->getAncestorsIterator());
self::assertTrue($cmMap1->hasField('name'));
}
public function testGetMetadataForThrowsExceptionOnUnknownCustomGeneratorClass() : void
{
$cm1 = $this->createValidClassMetadata();
$cm1->getProperty('id')->setValueGenerator(
new Mapping\ValueGeneratorMetadata(
Mapping\GeneratorType::CUSTOM,
[
'class' => 'NotExistingGenerator',
'arguments' => [],
]
)
);
$cmf = $this->createTestFactory();
$cmf->setMetadataForClass($cm1->getClassName(), $cm1);
$this->expectException(ORMException::class);
$actual = $cmf->getMetadataFor($cm1->getClassName());
}
public function testGetMetadataForThrowsExceptionOnMissingCustomGeneratorDefinition() : void
{
$cm1 = $this->createValidClassMetadata();
$cm1->getProperty('id')->setValueGenerator(
new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::CUSTOM)
);
$cmf = $this->createTestFactory();
$cmf->setMetadataForClass($cm1->getClassName(), $cm1);
$this->expectException(ORMException::class);
$actual = $cmf->getMetadataFor($cm1->getClassName());
}
public function testHasGetMetadataNamespaceSeparatorIsNotNormalized() : void
{
require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php';
$metadataDriver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Global/']);
$entityManager = $this->createEntityManager($metadataDriver);
$mf = $entityManager->getMetadataFactory();
self::assertSame(
$mf->getMetadataFor(DoctrineGlobalArticle::class),
$mf->getMetadataFor('\\' . DoctrineGlobalArticle::class)
);
self::assertTrue($mf->hasMetadataFor(DoctrineGlobalArticle::class));
self::assertTrue($mf->hasMetadataFor('\\' . DoctrineGlobalArticle::class));
}
/**
* @group DDC-1512
*/
public function testIsTransient() : void
{
$cmf = new ClassMetadataFactory();
$driver = $this->createMock(MappingDriver::class);
$driver->expects($this->at(0))
->method('isTransient')
->with($this->equalTo(CmsUser::class))
->will($this->returnValue(true));
$driver->expects($this->at(1))
->method('isTransient')
->with($this->equalTo(CmsArticle::class))
->will($this->returnValue(false));
$em = $this->createEntityManager($driver);
self::assertTrue($em->getMetadataFactory()->isTransient(CmsUser::class));
self::assertFalse($em->getMetadataFactory()->isTransient(CmsArticle::class));
}
public function testAddDefaultDiscriminatorMap() : void
{
$cmf = new ClassMetadataFactory();
$driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/JoinedInheritanceType/']);
$em = $this->createEntityManager($driver);
$cmf->setEntityManager($em);
$rootMetadata = $cmf->getMetadataFor(RootClass::class);
$childMetadata = $cmf->getMetadataFor(ChildClass::class);
$anotherChildMetadata = $cmf->getMetadataFor(AnotherChildClass::class);
$rootDiscriminatorMap = $rootMetadata->discriminatorMap;
$childDiscriminatorMap = $childMetadata->discriminatorMap;
$anotherChildDiscriminatorMap = $anotherChildMetadata->discriminatorMap;
$rootClass = RootClass::class;
$childClass = ChildClass::class;
$anotherChildClass = AnotherChildClass::class;
$rootClassKey = array_search($rootClass, $rootDiscriminatorMap, true);
$childClassKey = array_search($childClass, $rootDiscriminatorMap, true);
$anotherChildClassKey = array_search($anotherChildClass, $rootDiscriminatorMap, true);
self::assertEquals('rootclass', $rootClassKey);
self::assertEquals('childclass', $childClassKey);
self::assertEquals('anotherchildclass', $anotherChildClassKey);
self::assertEquals($childDiscriminatorMap, $rootDiscriminatorMap);
self::assertEquals($anotherChildDiscriminatorMap, $rootDiscriminatorMap);
}
public function testGetAllMetadataWorksWithBadConnection() : void
{
// DDC-3551
$conn = $this->createMock(Connection::class);
$mockDriver = new MetadataDriverMock();
$conn->expects($this->any())
->method('getEventManager')
->willReturn(new EventManager());
$em = $this->createEntityManager($mockDriver, $conn);
$conn->expects($this->any())
->method('getDatabasePlatform')
->will($this->throwException(new \Exception('Exception thrown in test when calling getDatabasePlatform')));
$cmf = new ClassMetadataFactory();
$cmf->setEntityManager($em);
// getting all the metadata should work, even if get DatabasePlatform blows up
$metadata = $cmf->getAllMetadata();
// this will just be an empty array - there was no error
self::assertEquals([], $metadata);
}
protected function createEntityManager($metadataDriver, $conn = null)
{
$driverMock = new DriverMock();
$config = new Configuration();
$config->setProxyDir(__DIR__ . '/../../Proxies');
$config->setProxyNamespace('Doctrine\Tests\Proxies');
if (! $conn) {
$conn = new ConnectionMock([], $driverMock, $config, new EventManager());
}
$eventManager = $conn->getEventManager();
$config->setMetadataDriverImpl($metadataDriver);
return EntityManagerMock::create($conn, $config, $eventManager);
}
/**
* @return ClassMetadataFactoryTestSubject
*/
protected function createTestFactory()
{
$mockDriver = new MetadataDriverMock();
$entityManager = $this->createEntityManager($mockDriver);
$cmf = new ClassMetadataFactoryTestSubject();
$cmf->setEntityManager($entityManager);
return $cmf;
}
/**
* @return ClassMetadata
*/
protected function createValidClassMetadata()
{
// Self-made metadata
$metadataBuildingContext = new Mapping\ClassMetadataBuildingContext(
$this->createMock(ClassMetadataFactory::class),
new RuntimeReflectionService()
);
$cm1 = new ClassMetadata(TestEntity1::class, $metadataBuildingContext);
$tableMetadata = new Mapping\TableMetadata();
$tableMetadata->setName('group');
$cm1->setTable($tableMetadata);
// Add a mapped field
$fieldMetadata = new Mapping\FieldMetadata('id');
$fieldMetadata->setType(Type::getType('integer'));
$fieldMetadata->setPrimaryKey(true);
$fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata(Mapping\GeneratorType::AUTO));
$cm1->addProperty($fieldMetadata);
// Add a mapped field
$fieldMetadata = new Mapping\FieldMetadata('name');
$fieldMetadata->setType(Type::getType('string'));
$cm1->addProperty($fieldMetadata);
// and a mapped association
$association = new Mapping\OneToOneAssociationMetadata('other');
$association->setTargetEntity(TestEntity1::class);
$association->setMappedBy('this');
$cm1->addProperty($association);
// and an association on the owning side
$joinColumns = [];
$joinColumn = new Mapping\JoinColumnMetadata();
$joinColumn->setColumnName('other_id');
$joinColumn->setReferencedColumnName('id');
$joinColumns[] = $joinColumn;
$association = new Mapping\OneToOneAssociationMetadata('association');
$association->setJoinColumns($joinColumns);
$association->setTargetEntity(TestEntity1::class);
$cm1->addProperty($association);
return $cm1;
}
/**
* @group DDC-1845
*/
public function testQuoteMetadata() : void
{
$cmf = new ClassMetadataFactory();
$driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Quote/']);
$em = $this->createEntityManager($driver);
$cmf->setEntityManager($em);
$userMetadata = $cmf->getMetadataFor(Quote\User::class);
$phoneMetadata = $cmf->getMetadataFor(Quote\Phone::class);
$groupMetadata = $cmf->getMetadataFor(Quote\Group::class);
$addressMetadata = $cmf->getMetadataFor(Quote\Address::class);
// Phone Class Metadata
self::assertNotNull($phoneMetadata->getProperty('number'));
self::assertEquals('phone-number', $phoneMetadata->getProperty('number')->getColumnName());
$user = $phoneMetadata->getProperty('user');
$userJoinColumns = $user->getJoinColumns();
$phoneUserJoinColumn = reset($userJoinColumns);
self::assertEquals('user-id', $phoneUserJoinColumn->getColumnName());
self::assertEquals('user-id', $phoneUserJoinColumn->getReferencedColumnName());
// Address Class Metadata
self::assertNotNull($addressMetadata->getProperty('id'));
self::assertNotNull($addressMetadata->getProperty('zip'));
self::assertEquals('address-id', $addressMetadata->getProperty('id')->getColumnName());
self::assertEquals('address-zip', $addressMetadata->getProperty('zip')->getColumnName());
// User Class Metadata
self::assertNotNull($userMetadata->getProperty('id'));
self::assertNotNull($userMetadata->getProperty('name'));
self::assertEquals('user-id', $userMetadata->getProperty('id')->getColumnName());
self::assertEquals('user-name', $userMetadata->getProperty('name')->getColumnName());
$group = $groupMetadata->getProperty('parent');
$groupJoinColumns = $group->getJoinColumns();
$groupUserJoinColumn = reset($groupJoinColumns);
self::assertEquals('parent-id', $groupUserJoinColumn->getColumnName());
self::assertEquals('group-id', $groupUserJoinColumn->getReferencedColumnName());
$user = $addressMetadata->getProperty('user');
$userJoinColumns = $user->getJoinColumns();
$addressUserJoinColumn = reset($userJoinColumns);
self::assertEquals('user-id', $addressUserJoinColumn->getColumnName());
self::assertEquals('user-id', $addressUserJoinColumn->getReferencedColumnName());
$groups = $userMetadata->getProperty('groups');
$groupsJoinTable = $groups->getJoinTable();
$userGroupsJoinColumns = $groupsJoinTable->getJoinColumns();
$userGroupsJoinColumn = reset($userGroupsJoinColumns);
$userGroupsInverseJoinColumns = $groupsJoinTable->getInverseJoinColumns();
$userGroupsInverseJoinColumn = reset($userGroupsInverseJoinColumns);
self::assertEquals('quote-users-groups', $groupsJoinTable->getName());
self::assertEquals('user-id', $userGroupsJoinColumn->getColumnName());
self::assertEquals('user-id', $userGroupsJoinColumn->getReferencedColumnName());
self::assertEquals('group-id', $userGroupsInverseJoinColumn->getColumnName());
self::assertEquals('group-id', $userGroupsInverseJoinColumn->getReferencedColumnName());
}
/**
* @group DDC-3385
* @group 1181
* @group 385
*/
public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMetadata() : void
{
$test = $this;
/** @var ClassMetadata $metadata */
$metadata = $this->createMock(ClassMetadata::class);
$cmf = new ClassMetadataFactory();
$mockDriver = new MetadataDriverMock();
$em = $this->createEntityManager($mockDriver);
$listener = $this->getMockBuilder(\stdClass::class)->setMethods(['onClassMetadataNotFound'])->getMock();
$eventManager = $em->getEventManager();
$cmf->setEntityManager($em);
$listener
->expects($this->any())
->method('onClassMetadataNotFound')
->will($this->returnCallback(function (OnClassMetadataNotFoundEventArgs $args) use ($metadata, $em, $test) {
$test->assertNull($args->getFoundMetadata());
$test->assertSame('Foo', $args->getClassName());
$test->assertSame($em, $args->getObjectManager());
$args->setFoundMetadata($metadata);
}));
$eventManager->addEventListener([Events::onClassMetadataNotFound], $listener);
self::assertSame($metadata, $cmf->getMetadataFor('Foo'));
}
/**
* @group DDC-3427
*/
public function testAcceptsEntityManagerInterfaceInstances() : void
{
$classMetadataFactory = new ClassMetadataFactory();
/** @var EntityManagerInterface $entityManager */
$entityManager = $this->createMock(EntityManagerInterface::class);
$classMetadataFactory->setEntityManager($entityManager);
// not really the cleanest way to check it, but we won't add a getter to the CMF just for the sake of testing.
self::assertAttributeSame($entityManager, 'em', $classMetadataFactory);
}
/**
* @group embedded
* @group DDC-3305
*/
public function testRejectsEmbeddableWithoutValidClassName() : void
{
$metadata = $this->createValidClassMetadata();
$metadata->mapEmbedded(
[
'fieldName' => 'embedded',
'class' => '',
'columnPrefix' => false,
]
);
$cmf = $this->createTestFactory();
$cmf->setMetadataForClass($metadata->getClassName(), $metadata);
$this->expectException(MappingException::class);
$this->expectExceptionMessage('The embed mapping \'embedded\' misses the \'class\' attribute.');
$cmf->getMetadataFor($metadata->getClassName());
}
/**
* @group embedded
* @group DDC-4006
*/
public function testInheritsIdGeneratorMappingFromEmbeddable() : void
{
$cmf = new ClassMetadataFactory();
$driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/DDC4006/']);
$em = $this->createEntityManager($driver);
$cmf->setEntityManager($em);
$userMetadata = $cmf->getMetadataFor(DDC4006User::class);
self::assertTrue($userMetadata->isIdGeneratorIdentity());
}
}
/* Test subject class with overridden factory method for mocking purposes */
class ClassMetadataFactoryTestSubject extends ClassMetadataFactory
{
private $mockMetadata = [];
private $requestedClasses = [];
protected function newClassMetadataInstance(
string $className,
?Mapping\ClassMetadata $parent,
Mapping\ClassMetadataBuildingContext $metadataBuildingContext
) : ClassMetadata {
$this->requestedClasses[] = $className;
if (! isset($this->mockMetadata[$className])) {
throw new \InvalidArgumentException(sprintf('No mock metadata found for class %s.', $className));
}
return $this->mockMetadata[$className];
}
public function setMetadataForClass($className, $metadata)
{
$this->mockMetadata[$className] = $metadata;
}
public function getRequestedClasses()
{
return $this->requestedClasses;
}
}
class TestEntity1
{
private $id;
private $name;
private $other;
private $association;
private $embedded;
}
class CustomIdGenerator implements Generator
{
/**
* {@inheritdoc}
*/
public function generate(EntityManagerInterface $em, ?object $entity)
{
}
/**
* {@inheritdoc}
*/
public function isPostInsertGenerator() : bool
{
return false;
}
}