Completed
Pull Request — 3.x (#830)
by
unknown
02:54
created

getMetadataForSubEmbeddedEntity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 14
c 1
b 0
f 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\DoctrineORMAdminBundle\Tests\Model;
13
14
use Doctrine\Common\Collections\ArrayCollection;
15
use Doctrine\Common\Persistence\ObjectManager;
16
use Doctrine\DBAL\Connection;
17
use Doctrine\DBAL\DBALException;
18
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
19
use Doctrine\DBAL\Types\Type;
20
use Doctrine\ORM\Configuration;
21
use Doctrine\ORM\EntityManager;
22
use Doctrine\ORM\Mapping\ClassMetadata;
23
use Doctrine\ORM\Mapping\ClassMetadataFactory;
24
use Doctrine\ORM\OptimisticLockException;
25
use Doctrine\ORM\Query;
26
use Doctrine\ORM\QueryBuilder;
27
use Doctrine\ORM\Version;
28
use PHPUnit\Framework\TestCase;
29
use Sonata\AdminBundle\Datagrid\Datagrid;
30
use Sonata\AdminBundle\Datagrid\DatagridInterface;
31
use Sonata\AdminBundle\Exception\LockException;
32
use Sonata\AdminBundle\Exception\ModelManagerException;
33
use Sonata\AdminBundle\Filter\FilterInterface;
34
use Sonata\DoctrineORMAdminBundle\Admin\FieldDescription;
35
use Sonata\DoctrineORMAdminBundle\Datagrid\OrderByToSelectWalker;
36
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
37
use Sonata\DoctrineORMAdminBundle\Model\ModelManager;
38
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\DoctrineType\UuidType;
39
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\AbstractEntity;
40
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\AssociatedEntity;
41
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\ContainerEntity;
42
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\Embeddable\EmbeddedEntity;
43
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\Embeddable\SubEmbeddedEntity;
44
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\SimpleEntity;
45
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\UuidEntity;
46
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Entity\VersionedEntity;
47
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Util\NonIntegerIdentifierTestClass;
48
use Symfony\Bridge\Doctrine\RegistryInterface;
49
50
class ModelManagerTest extends TestCase
51
{
52
    public static function setUpBeforeClass()
53
    {
54
        if (!Type::hasType('uuid')) {
55
            Type::addType('uuid', UuidType::class);
56
        }
57
    }
58
59
    public function testSortParameters()
60
    {
61
        $registry = $this->createMock(RegistryInterface::class);
62
63
        $manager = new ModelManager($registry);
64
65
        $datagrid1 = $this->createMock(Datagrid::class);
66
        $datagrid2 = $this->createMock(Datagrid::class);
67
68
        $field1 = new FieldDescription();
69
        $field1->setName('field1');
70
71
        $field2 = new FieldDescription();
72
        $field2->setName('field2');
73
74
        $field3 = new FieldDescription();
75
        $field3->setName('field3');
76
        $field3->setOption('sortable', 'field3sortBy');
77
78
        $datagrid1
79
            ->expects($this->any())
80
            ->method('getValues')
81
            ->will($this->returnValue([
82
                '_sort_by' => $field1,
83
                '_sort_order' => 'ASC',
84
            ]));
85
86
        $datagrid2
87
            ->expects($this->any())
88
            ->method('getValues')
89
            ->will($this->returnValue([
90
                '_sort_by' => $field3,
91
                '_sort_order' => 'ASC',
92
            ]));
93
94
        $parameters = $manager->getSortParameters($field1, $datagrid1);
95
96
        $this->assertEquals('DESC', $parameters['filter']['_sort_order']);
97
        $this->assertEquals('field1', $parameters['filter']['_sort_by']);
98
99
        $parameters = $manager->getSortParameters($field2, $datagrid1);
100
101
        $this->assertEquals('ASC', $parameters['filter']['_sort_order']);
102
        $this->assertEquals('field2', $parameters['filter']['_sort_by']);
103
104
        $parameters = $manager->getSortParameters($field3, $datagrid1);
105
106
        $this->assertEquals('ASC', $parameters['filter']['_sort_order']);
107
        $this->assertEquals('field3sortBy', $parameters['filter']['_sort_by']);
108
109
        $parameters = $manager->getSortParameters($field3, $datagrid2);
110
111
        $this->assertEquals('DESC', $parameters['filter']['_sort_order']);
112
        $this->assertEquals('field3sortBy', $parameters['filter']['_sort_by']);
113
    }
114
115
    public function getVersionDataProvider()
116
    {
117
        return [
118
            [true],
119
            [false],
120
        ];
121
    }
122
123
    /**
124
     * @dataProvider getVersionDataProvider
125
     */
126
    public function testGetVersion($isVersioned)
127
    {
128
        $object = new VersionedEntity();
129
130
        $modelManager = $this->getMockBuilder(ModelManager::class)
131
            ->disableOriginalConstructor()
132
            ->setMethods(['getMetadata'])
133
            ->getMock();
134
135
        $metadata = $this->getMetadata(get_class($object), $isVersioned);
136
137
        $modelManager->expects($this->any())
138
            ->method('getMetadata')
139
            ->will($this->returnValue($metadata));
140
141
        if ($isVersioned) {
142
            $object->version = 123;
143
144
            $this->assertNotNull($modelManager->getLockVersion($object));
145
        } else {
146
            $this->assertNull($modelManager->getLockVersion($object));
147
        }
148
    }
149
150
    public function lockDataProvider()
151
    {
152
        return [
153
            [true,  false],
154
            [true,  true],
155
            [false, false],
156
        ];
157
    }
158
159
    /**
160
     * @dataProvider lockDataProvider
161
     */
162
    public function testLock($isVersioned, $expectsException)
163
    {
164
        $object = new VersionedEntity();
165
166
        $em = $this->getMockBuilder(EntityManager::class)
167
            ->disableOriginalConstructor()
168
            ->setMethods(['lock'])
169
            ->getMock();
170
171
        $modelManager = $this->getMockBuilder(ModelManager::class)
172
            ->disableOriginalConstructor()
173
            ->setMethods(['getMetadata', 'getEntityManager'])
174
            ->getMock();
175
176
        $modelManager->expects($this->any())
177
            ->method('getEntityManager')
178
            ->will($this->returnValue($em));
179
180
        $metadata = $this->getMetadata(get_class($object), $isVersioned);
181
182
        $modelManager->expects($this->any())
183
            ->method('getMetadata')
184
            ->will($this->returnValue($metadata));
185
186
        if ($expectsException) {
187
            $em->expects($this->once())
188
                ->method('lock')
189
                ->will($this->throwException(OptimisticLockException::lockFailed($object)));
190
191
            $this->expectException(LockException::class);
192
        }
193
194
        $modelManager->lock($object, 123);
195
    }
196
197
    public function testGetParentMetadataForProperty()
198
    {
199
        if (version_compare(Version::VERSION, '2.5') < 0) {
200
            $this->markTestSkipped('Test for embeddables needs to run on Doctrine >= 2.5');
201
202
            return;
203
        }
204
205
        $containerEntityClass = ContainerEntity::class;
206
        $associatedEntityClass = AssociatedEntity::class;
207
        $embeddedEntityClass = EmbeddedEntity::class;
208
        $modelManagerClass = ModelManager::class;
209
210
        $em = $this->createMock(EntityManager::class);
211
212
        /** @var \PHPUnit_Framework_MockObject_MockObject|ModelManager $modelManager */
213
        $modelManager = $this->getMockBuilder($modelManagerClass)
214
            ->disableOriginalConstructor()
215
            ->setMethods(['getMetadata', 'getEntityManager'])
216
            ->getMock();
217
218
        $modelManager->expects($this->any())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\DoctrineOR...dle\Model\ModelManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
219
            ->method('getEntityManager')
220
            ->will($this->returnValue($em));
221
222
        $containerEntityMetadata = $this->getMetadataForContainerEntity();
223
        $associatedEntityMetadata = $this->getMetadataForAssociatedEntity();
224
        $embeddedEntityMetadata = $this->getMetadataForEmbeddedEntity();
225
226
        $modelManager->expects($this->any())->method('getMetadata')
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\DoctrineOR...dle\Model\ModelManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
227
            ->will(
228
                $this->returnValueMap(
229
                    [
230
                        [$containerEntityClass, $containerEntityMetadata],
231
                        [$embeddedEntityClass, $embeddedEntityMetadata],
232
                        [$associatedEntityClass, $associatedEntityMetadata],
233
                    ]
234
                )
235
            );
236
237
        /** @var ClassMetadata $metadata */
238
        list($metadata, $lastPropertyName) = $modelManager
239
            ->getParentMetadataForProperty($containerEntityClass, 'plainField');
240
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'integer');
241
242
        list($metadata, $lastPropertyName) = $modelManager
243
            ->getParentMetadataForProperty($containerEntityClass, 'associatedEntity.plainField');
244
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'string');
245
246
        list($metadata, $lastPropertyName) = $modelManager
247
            ->getParentMetadataForProperty($containerEntityClass, 'embeddedEntity.plainField');
248
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'boolean');
249
250
        list($metadata, $lastPropertyName) = $modelManager
251
            ->getParentMetadataForProperty($containerEntityClass, 'associatedEntity.embeddedEntity.plainField');
252
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'boolean');
253
254
        list($metadata, $lastPropertyName) = $modelManager
255
            ->getParentMetadataForProperty($containerEntityClass, 'associatedEntity.embeddedEntity.subEmbeddedEntity.plainField');
256
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'boolean');
257
    }
258
259
    public function getMetadataForEmbeddedEntity()
260
    {
261
        $metadata = new ClassMetadata(EmbeddedEntity::class);
262
263
        $metadata->fieldMappings = [
264
            'plainField' => [
265
                'fieldName' => 'plainField',
266
                'columnName' => 'plainField',
267
                'type' => 'boolean',
268
            ],
269
        ];
270
271
        return $metadata;
272
    }
273
274
    public function getMetadataForSubEmbeddedEntity()
275
    {
276
        $metadata = new ClassMetadata(SubEmbeddedEntity::class);
277
278
        $metadata->fieldMappings = [
279
            'plainField' => [
280
                'fieldName' => 'plainField',
281
                'columnName' => 'plainField',
282
                'type' => 'boolean',
283
            ],
284
        ];
285
286
        return $metadata;
287
    }
288
289
    public function getMetadataForAssociatedEntity()
290
    {
291
        $embeddedEntityClass = EmbeddedEntity::class;
292
        $subEmbeddedEntityClass = SubEmbeddedEntity::class;
293
294
        $metadata = new ClassMetadata(AssociatedEntity::class);
295
296
        $metadata->fieldMappings = [
297
            'plainField' => [
298
                'fieldName' => 'plainField',
299
                'columnName' => 'plainField',
300
                'type' => 'string',
301
            ],
302
        ];
303
304
        $metadata->embeddedClasses['embeddedEntity'] = [
305
            'class' => $embeddedEntityClass,
306
            'columnPrefix' => 'embedded_entity_',
307
        ];
308
        $metadata->embeddedClasses['embeddedEntity.subEmbeddedEntity'] = [
309
            'class' => $subEmbeddedEntityClass,
310
            'columnPrefix' => 'embedded_entity_sub_embedded_entity_',
311
            'declaredField' => 'embeddedEntity',
312
            'originalField' => 'subEmbeddedEntity',
313
        ];
314
315
        $metadata->inlineEmbeddable('embeddedEntity', $this->getMetadataForEmbeddedEntity());
316
        $metadata->inlineEmbeddable('embeddedEntity.subEmbeddedEntity', $this->getMetadataForSubEmbeddedEntity());
317
318
        return $metadata;
319
    }
320
321
    public function getMetadataForContainerEntity()
322
    {
323
        $containerEntityClass = ContainerEntity::class;
324
        $associatedEntityClass = AssociatedEntity::class;
325
        $embeddedEntityClass = EmbeddedEntity::class;
326
        $subEmbeddedEntityClass = SubEmbeddedEntity::class;
327
328
        $metadata = new ClassMetadata($containerEntityClass);
329
330
        $metadata->fieldMappings = [
331
            'plainField' => [
332
                'fieldName' => 'plainField',
333
                'columnName' => 'plainField',
334
                'type' => 'integer',
335
            ],
336
        ];
337
338
        $metadata->associationMappings['associatedEntity'] = [
339
            'fieldName' => 'associatedEntity',
340
            'targetEntity' => $associatedEntityClass,
341
            'sourceEntity' => $containerEntityClass,
342
        ];
343
344
        $metadata->embeddedClasses['embeddedEntity'] = [
345
            'class' => $embeddedEntityClass,
346
            'columnPrefix' => 'embeddedEntity',
347
        ];
348
        $metadata->embeddedClasses['embeddedEntity.subEmbeddedEntity'] = [
349
            'class' => $subEmbeddedEntityClass,
350
            'columnPrefix' => 'embedded_entity_sub_embedded_entity_',
351
            'declaredField' => 'embeddedEntity',
352
            'originalField' => 'subEmbeddedEntity',
353
        ];
354
355
        $metadata->inlineEmbeddable('embeddedEntity', $this->getMetadataForEmbeddedEntity());
356
        $metadata->inlineEmbeddable('embeddedEntity.subEmbeddedEntity', $this->getMetadataForSubEmbeddedEntity());
357
358
        return $metadata;
359
    }
360
361
    public function testNonIntegerIdentifierType()
362
    {
363
        $uuid = new NonIntegerIdentifierTestClass('efbcfc4b-8c43-4d42-aa4c-d707e55151ac');
364
        $entity = new UuidEntity($uuid);
365
366
        $meta = $this->createMock(ClassMetadata::class);
367
        $meta->expects($this->any())
368
            ->method('getIdentifierValues')
369
            ->willReturn([$entity->getId()]);
370
        $meta->expects($this->any())
371
            ->method('getTypeOfField')
372
            ->willReturn(UuidType::NAME);
373
374
        $mf = $this->createMock(ClassMetadataFactory::class);
375
        $mf->expects($this->any())
376
            ->method('getMetadataFor')
377
            ->willReturn($meta);
378
379
        $platform = $this->createMock(PostgreSqlPlatform::class);
380
381
        $conn = $this->createMock(Connection::class);
382
        $conn->expects($this->any())
383
            ->method('getDatabasePlatform')
384
            ->willReturn($platform);
385
386
        $em = $this->createMock(EntityManager::class);
387
        $em->expects($this->any())
388
            ->method('getMetadataFactory')
389
            ->willReturn($mf);
390
        $em->expects($this->any())
391
            ->method('getConnection')
392
            ->willReturn($conn);
393
394
        $registry = $this->createMock(RegistryInterface::class);
395
        $registry->expects($this->any())
396
            ->method('getManagerForClass')
397
            ->willReturn($em);
398
399
        $manager = new ModelManager($registry);
400
        $result = $manager->getIdentifierValues($entity);
401
402
        $this->assertEquals($entity->getId()->toString(), $result[0]);
403
    }
404
405
    public function testAssociationIdentifierType()
406
    {
407
        $entity = new ContainerEntity(new AssociatedEntity(42, new EmbeddedEntity()), new EmbeddedEntity());
408
409
        $meta = $this->createMock(ClassMetadata::class);
410
        $meta->expects($this->any())
411
            ->method('getIdentifierValues')
412
            ->willReturn([$entity->getAssociatedEntity()->getPlainField()]);
413
        $meta->expects($this->any())
414
            ->method('getTypeOfField')
415
            ->willReturn(null);
416
417
        $mf = $this->createMock(ClassMetadataFactory::class);
418
        $mf->expects($this->any())
419
            ->method('getMetadataFor')
420
            ->willReturn($meta);
421
422
        $platform = $this->createMock(PostgreSqlPlatform::class);
423
424
        $conn = $this->createMock(Connection::class);
425
        $conn->expects($this->any())
426
            ->method('getDatabasePlatform')
427
            ->willReturn($platform);
428
429
        $em = $this->createMock(EntityManager::class);
430
        $em->expects($this->any())
431
            ->method('getMetadataFactory')
432
            ->willReturn($mf);
433
        $em->expects($this->any())
434
            ->method('getConnection')
435
            ->willReturn($conn);
436
437
        $registry = $this->createMock(RegistryInterface::class);
438
        $registry->expects($this->any())
439
            ->method('getManagerForClass')
440
            ->willReturn($em);
441
442
        $manager = new ModelManager($registry);
443
        $result = $manager->getIdentifierValues($entity);
444
445
        $this->assertSame(42, $result[0]);
446
    }
447
448
    /**
449
     * [sortBy, sortOrder, isAddOrderBy].
450
     *
451
     * @return array
452
     */
453
    public function getSortableInDataSourceIteratorDataProvider()
454
    {
455
        return [
456
            [null, null, false],
457
            ['', 'ASC', false],
458
            ['field', 'ASC', true],
459
            ['field', null, true],
460
        ];
461
    }
462
463
    /**
464
     * @dataProvider getSortableInDataSourceIteratorDataProvider
465
     *
466
     * @param string|null $sortBy
467
     * @param string|null $sortOrder
468
     * @param bool        $isAddOrderBy
469
     */
470
    public function testSortableInDataSourceIterator($sortBy, $sortOrder, $isAddOrderBy)
471
    {
472
        $datagrid = $this->getMockForAbstractClass(DatagridInterface::class);
473
        $configuration = $this->getMockBuilder(Configuration::class)->getMock();
474
        $configuration->expects($this->any())
475
            ->method('getDefaultQueryHints')
476
            ->willReturn([]);
477
478
        $em = $this->getMockBuilder(EntityManager::class)
479
            ->disableOriginalConstructor()
480
            ->getMock();
481
482
        $em->expects($this->any())
483
            ->method('getConfiguration')
484
            ->willReturn($configuration);
485
486
        $queryBuilder = $this->getMockBuilder(QueryBuilder::class)
487
            ->setConstructorArgs([$em])
488
            ->getMock();
489
        $query = new Query($em);
490
491
        $proxyQuery = $this->getMockBuilder(ProxyQuery::class)
492
            ->setConstructorArgs([$queryBuilder])
493
            ->setMethods(['getSortBy', 'getSortOrder', 'getRootAliases'])
494
            ->getMock();
495
496
        $proxyQuery->expects($this->any())
497
            ->method('getSortOrder')
498
            ->willReturn($sortOrder);
499
500
        $proxyQuery->expects($this->any())
501
            ->method('getSortBy')
502
            ->willReturn($sortBy);
503
504
        $queryBuilder->expects($isAddOrderBy ? $this->atLeastOnce() : $this->never())
505
            ->method('addOrderBy');
506
507
        $proxyQuery->expects($this->any())
508
            ->method('getRootAliases')
509
            ->willReturn(['a']);
510
511
        $queryBuilder->expects($this->any())
512
            ->method('getQuery')
513
            ->willReturn($query);
514
515
        $datagrid->expects($this->any())
516
            ->method('getQuery')
517
            ->willReturn($proxyQuery);
518
519
        $registry = $this->getMockBuilder(RegistryInterface::class)->getMock();
520
        $manager = new ModelManager($registry);
521
        $manager->getDataSourceIterator($datagrid, []);
522
523
        if ($isAddOrderBy) {
524
            $this->assertArrayHasKey($key = 'doctrine.customTreeWalkers', $hints = $query->getHints());
525
            $this->assertContains(OrderByToSelectWalker::class, $hints[$key]);
526
        }
527
    }
528
529
    public function testModelReverseTransform()
530
    {
531
        $class = SimpleEntity::class;
532
533
        $metadataFactory = $this->createMock(ClassMetadataFactory::class);
534
        $modelManager = $this->createMock(ObjectManager::class);
535
        $registry = $this->createMock(RegistryInterface::class);
536
537
        $classMetadata = new ClassMetadata($class);
538
        $classMetadata->reflClass = new \ReflectionClass($class);
539
540
        $modelManager->expects($this->once())
541
            ->method('getMetadataFactory')
542
            ->willReturn($metadataFactory);
543
        $metadataFactory->expects($this->once())
544
            ->method('getMetadataFor')
545
            ->with($class)
546
            ->willReturn($classMetadata);
547
        $registry->expects($this->once())
548
            ->method('getManagerForClass')
549
            ->with($class)
550
            ->willReturn($modelManager);
551
552
        $manager = new ModelManager($registry);
553
        $this->assertInstanceOf($class, $object = $manager->modelReverseTransform(
554
            $class,
555
            [
556
                'schmeckles' => 42,
557
                'multi_word_property' => 'hello',
558
            ]
559
        ));
560
        $this->assertSame(42, $object->getSchmeckles());
561
        $this->assertSame('hello', $object->getMultiWordProperty());
562
    }
563
564
    public function testCollections()
565
    {
566
        $registry = $this->createMock(RegistryInterface::class);
567
        $model = new ModelManager($registry);
568
569
        $collection = $model->getModelCollectionInstance('whyDoWeEvenHaveThisParameter');
570
        $this->assertInstanceOf(ArrayCollection::class, $collection);
571
572
        $item1 = 'item1';
573
        $item2 = 'item2';
574
        $model->collectionAddElement($collection, $item1);
575
        $model->collectionAddElement($collection, $item2);
576
577
        $this->assertTrue($model->collectionHasElement($collection, $item1));
578
579
        $model->collectionRemoveElement($collection, $item1);
580
581
        $this->assertFalse($model->collectionHasElement($collection, $item1));
582
583
        $model->collectionClear($collection);
584
585
        $this->assertTrue($collection->isEmpty());
586
    }
587
588
    public function testModelTransform()
589
    {
590
        $registry = $this->createMock(RegistryInterface::class);
591
        $model = new ModelManager($registry);
592
593
        $result = $model->modelTransform('thisIsNotUsed', 'doWeNeedThisMethod');
0 ignored issues
show
Documentation introduced by
'doWeNeedThisMethod' is of type string, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
594
595
        $this->assertSame('doWeNeedThisMethod', $result);
596
    }
597
598
    public function testGetPaginationParameters()
599
    {
600
        $datagrid = $this->createMock(DatagridInterface::class);
601
        $filter = $this->createMock(FilterInterface::class);
602
        $registry = $this->createMock(RegistryInterface::class);
603
604
        $datagrid->expects($this->once())
605
            ->method('getValues')
606
            ->willReturn(['_sort_by' => $filter]);
607
608
        $filter->expects($this->once())
609
            ->method('getName')
610
            ->willReturn($name = 'test');
611
612
        $model = new ModelManager($registry);
613
614
        $result = $model->getPaginationParameters($datagrid, $page = 5);
615
616
        $this->assertSame($page, $result['filter']['_page']);
617
        $this->assertSame($name, $result['filter']['_sort_by']);
618
    }
619
620
    public function testGetModelInstanceException()
621
    {
622
        $registry = $this->createMock(RegistryInterface::class);
623
624
        $model = new ModelManager($registry);
625
626
        $this->expectException(\RuntimeException::class);
627
628
        $model->getModelInstance(AbstractEntity::class);
629
    }
630
631
    public function testGetEntityManagerException()
632
    {
633
        $registry = $this->createMock(RegistryInterface::class);
634
635
        $model = new ModelManager($registry);
636
637
        $this->expectException(\RuntimeException::class);
638
639
        $model->getEntityManager(VersionedEntity::class);
640
    }
641
642
    public function testGetNewFieldDescriptionInstanceException()
643
    {
644
        $registry = $this->createMock(RegistryInterface::class);
645
646
        $model = new ModelManager($registry);
647
648
        $this->expectException(\RuntimeException::class);
649
650
        $model->getNewFieldDescriptionInstance(VersionedEntity::class, [], []);
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
651
    }
652
653
    /**
654
     * @dataProvider createUpdateRemoveData
655
     */
656
    public function testCreate($exception)
657
    {
658
        $registry = $this->createMock(RegistryInterface::class);
659
660
        $entityManger = $this->createMock(EntityManager::class);
661
662
        $registry->expects($this->once())
663
            ->method('getManagerForClass')
664
            ->willReturn($entityManger);
665
666
        $entityManger->expects($this->once())
667
            ->method('persist');
668
669
        $entityManger->expects($this->once())
670
            ->method('flush')
671
            ->willThrowException($exception);
672
673
        $model = new ModelManager($registry);
674
675
        $this->expectException(ModelManagerException::class);
676
677
        $model->create(new VersionedEntity());
678
    }
679
680
    public function createUpdateRemoveData()
681
    {
682
        return [
683
            'PDOException' => [
684
                new \PDOException(),
685
            ],
686
            'DBALException' => [
687
                new DBALException(),
688
            ],
689
        ];
690
    }
691
692
    /**
693
     * @dataProvider createUpdateRemoveData
694
     */
695
    public function testUpdate($exception)
696
    {
697
        $registry = $this->createMock(RegistryInterface::class);
698
699
        $entityManger = $this->createMock(EntityManager::class);
700
701
        $registry->expects($this->once())
702
            ->method('getManagerForClass')
703
            ->willReturn($entityManger);
704
705
        $entityManger->expects($this->once())
706
            ->method('persist');
707
708
        $entityManger->expects($this->once())
709
            ->method('flush')
710
            ->willThrowException($exception);
711
712
        $model = new ModelManager($registry);
713
714
        $this->expectException(ModelManagerException::class);
715
716
        $model->update(new VersionedEntity());
717
    }
718
719
    /**
720
     * @dataProvider createUpdateRemoveData
721
     */
722
    public function testRemove($exception)
723
    {
724
        $registry = $this->createMock(RegistryInterface::class);
725
726
        $entityManger = $this->createMock(EntityManager::class);
727
728
        $registry->expects($this->once())
729
            ->method('getManagerForClass')
730
            ->willReturn($entityManger);
731
732
        $entityManger->expects($this->once())
733
            ->method('remove');
734
735
        $entityManger->expects($this->once())
736
            ->method('flush')
737
            ->willThrowException($exception);
738
739
        $model = new ModelManager($registry);
740
741
        $this->expectException(ModelManagerException::class);
742
743
        $model->delete(new VersionedEntity());
744
    }
745
746
    public function testFindBadId()
747
    {
748
        $registry = $this->createMock(RegistryInterface::class);
749
750
        $model = new ModelManager($registry);
751
752
        $this->assertNull($model->find('notImportant', null));
753
    }
754
755
    public function testGetUrlsafeIdentifierException()
756
    {
757
        $registry = $this->createMock(RegistryInterface::class);
758
759
        $model = new ModelManager($registry);
760
761
        $this->expectException(\RuntimeException::class);
762
763
        $model->getNormalizedIdentifier('test');
0 ignored issues
show
Documentation introduced by
'test' is of type string, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
764
    }
765
766
    public function testGetUrlsafeIdentifierNull()
767
    {
768
        $registry = $this->createMock(RegistryInterface::class);
769
770
        $model = new ModelManager($registry);
771
772
        $this->assertNull($model->getNormalizedIdentifier(null));
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
773
    }
774
775
    private function getMetadata($class, $isVersioned)
776
    {
777
        $metadata = new ClassMetadata($class);
778
779
        $metadata->isVersioned = $isVersioned;
780
781
        if ($isVersioned) {
782
            $versionField = 'version';
783
            $metadata->versionField = $versionField;
784
            $metadata->reflFields[$versionField] = new \ReflectionProperty($class, $versionField);
785
        }
786
787
        return $metadata;
788
    }
789
}
790