Completed
Pull Request — 3.x (#830)
by
unknown
07:11
created

ModelManagerTest::getMetadataForAssociatedEntity()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 31
c 3
b 0
f 0
rs 8.8571
cc 1
eloc 20
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(
256
                $containerEntityClass,
257
                'associatedEntity.embeddedEntity.subEmbeddedEntity.plainField'
258
            );
259
        $this->assertEquals($metadata->fieldMappings[$lastPropertyName]['type'], 'boolean');
260
    }
261
262
    public function getMetadataForEmbeddedEntity()
263
    {
264
        $metadata = new ClassMetadata(EmbeddedEntity::class);
265
266
        $metadata->fieldMappings = [
267
            'plainField' => [
268
                'fieldName' => 'plainField',
269
                'columnName' => 'plainField',
270
                'type' => 'boolean',
271
            ],
272
        ];
273
274
        return $metadata;
275
    }
276
277
    public function getMetadataForSubEmbeddedEntity()
278
    {
279
        $metadata = new ClassMetadata(SubEmbeddedEntity::class);
280
281
        $metadata->fieldMappings = [
282
            'plainField' => [
283
                'fieldName' => 'plainField',
284
                'columnName' => 'plainField',
285
                'type' => 'boolean',
286
            ],
287
        ];
288
289
        return $metadata;
290
    }
291
292
    public function getMetadataForAssociatedEntity()
293
    {
294
        $embeddedEntityClass = EmbeddedEntity::class;
295
        $subEmbeddedEntityClass = SubEmbeddedEntity::class;
296
297
        $metadata = new ClassMetadata(AssociatedEntity::class);
298
299
        $metadata->fieldMappings = [
300
            'plainField' => [
301
                'fieldName' => 'plainField',
302
                'columnName' => 'plainField',
303
                'type' => 'string',
304
            ],
305
        ];
306
307
        $metadata->embeddedClasses['embeddedEntity'] = [
308
            'class' => $embeddedEntityClass,
309
            'columnPrefix' => 'embedded_entity_',
310
        ];
311
        $metadata->embeddedClasses['embeddedEntity.subEmbeddedEntity'] = [
312
            'class' => $subEmbeddedEntityClass,
313
            'columnPrefix' => 'embedded_entity_sub_embedded_entity_',
314
            'declaredField' => 'embeddedEntity',
315
            'originalField' => 'subEmbeddedEntity',
316
        ];
317
318
        $metadata->inlineEmbeddable('embeddedEntity', $this->getMetadataForEmbeddedEntity());
319
        $metadata->inlineEmbeddable('embeddedEntity.subEmbeddedEntity', $this->getMetadataForSubEmbeddedEntity());
320
321
        return $metadata;
322
    }
323
324
    public function getMetadataForContainerEntity()
325
    {
326
        $containerEntityClass = ContainerEntity::class;
327
        $associatedEntityClass = AssociatedEntity::class;
328
        $embeddedEntityClass = EmbeddedEntity::class;
329
        $subEmbeddedEntityClass = SubEmbeddedEntity::class;
330
331
        $metadata = new ClassMetadata($containerEntityClass);
332
333
        $metadata->fieldMappings = [
334
            'plainField' => [
335
                'fieldName' => 'plainField',
336
                'columnName' => 'plainField',
337
                'type' => 'integer',
338
            ],
339
        ];
340
341
        $metadata->associationMappings['associatedEntity'] = [
342
            'fieldName' => 'associatedEntity',
343
            'targetEntity' => $associatedEntityClass,
344
            'sourceEntity' => $containerEntityClass,
345
        ];
346
347
        $metadata->embeddedClasses['embeddedEntity'] = [
348
            'class' => $embeddedEntityClass,
349
            'columnPrefix' => 'embeddedEntity',
350
        ];
351
        $metadata->embeddedClasses['embeddedEntity.subEmbeddedEntity'] = [
352
            'class' => $subEmbeddedEntityClass,
353
            'columnPrefix' => 'embedded_entity_sub_embedded_entity_',
354
            'declaredField' => 'embeddedEntity',
355
            'originalField' => 'subEmbeddedEntity',
356
        ];
357
358
        $metadata->inlineEmbeddable('embeddedEntity', $this->getMetadataForEmbeddedEntity());
359
        $metadata->inlineEmbeddable('embeddedEntity.subEmbeddedEntity', $this->getMetadataForSubEmbeddedEntity());
360
361
        return $metadata;
362
    }
363
364
    public function testNonIntegerIdentifierType()
365
    {
366
        $uuid = new NonIntegerIdentifierTestClass('efbcfc4b-8c43-4d42-aa4c-d707e55151ac');
367
        $entity = new UuidEntity($uuid);
368
369
        $meta = $this->createMock(ClassMetadata::class);
370
        $meta->expects($this->any())
371
            ->method('getIdentifierValues')
372
            ->willReturn([$entity->getId()]);
373
        $meta->expects($this->any())
374
            ->method('getTypeOfField')
375
            ->willReturn(UuidType::NAME);
376
377
        $mf = $this->createMock(ClassMetadataFactory::class);
378
        $mf->expects($this->any())
379
            ->method('getMetadataFor')
380
            ->willReturn($meta);
381
382
        $platform = $this->createMock(PostgreSqlPlatform::class);
383
384
        $conn = $this->createMock(Connection::class);
385
        $conn->expects($this->any())
386
            ->method('getDatabasePlatform')
387
            ->willReturn($platform);
388
389
        $em = $this->createMock(EntityManager::class);
390
        $em->expects($this->any())
391
            ->method('getMetadataFactory')
392
            ->willReturn($mf);
393
        $em->expects($this->any())
394
            ->method('getConnection')
395
            ->willReturn($conn);
396
397
        $registry = $this->createMock(RegistryInterface::class);
398
        $registry->expects($this->any())
399
            ->method('getManagerForClass')
400
            ->willReturn($em);
401
402
        $manager = new ModelManager($registry);
403
        $result = $manager->getIdentifierValues($entity);
404
405
        $this->assertEquals($entity->getId()->toString(), $result[0]);
406
    }
407
408
    public function testAssociationIdentifierType()
409
    {
410
        $entity = new ContainerEntity(new AssociatedEntity(42, new EmbeddedEntity()), new EmbeddedEntity());
411
412
        $meta = $this->createMock(ClassMetadata::class);
413
        $meta->expects($this->any())
414
            ->method('getIdentifierValues')
415
            ->willReturn([$entity->getAssociatedEntity()->getPlainField()]);
416
        $meta->expects($this->any())
417
            ->method('getTypeOfField')
418
            ->willReturn(null);
419
420
        $mf = $this->createMock(ClassMetadataFactory::class);
421
        $mf->expects($this->any())
422
            ->method('getMetadataFor')
423
            ->willReturn($meta);
424
425
        $platform = $this->createMock(PostgreSqlPlatform::class);
426
427
        $conn = $this->createMock(Connection::class);
428
        $conn->expects($this->any())
429
            ->method('getDatabasePlatform')
430
            ->willReturn($platform);
431
432
        $em = $this->createMock(EntityManager::class);
433
        $em->expects($this->any())
434
            ->method('getMetadataFactory')
435
            ->willReturn($mf);
436
        $em->expects($this->any())
437
            ->method('getConnection')
438
            ->willReturn($conn);
439
440
        $registry = $this->createMock(RegistryInterface::class);
441
        $registry->expects($this->any())
442
            ->method('getManagerForClass')
443
            ->willReturn($em);
444
445
        $manager = new ModelManager($registry);
446
        $result = $manager->getIdentifierValues($entity);
447
448
        $this->assertSame(42, $result[0]);
449
    }
450
451
    /**
452
     * [sortBy, sortOrder, isAddOrderBy].
453
     *
454
     * @return array
455
     */
456
    public function getSortableInDataSourceIteratorDataProvider()
457
    {
458
        return [
459
            [null, null, false],
460
            ['', 'ASC', false],
461
            ['field', 'ASC', true],
462
            ['field', null, true],
463
        ];
464
    }
465
466
    /**
467
     * @dataProvider getSortableInDataSourceIteratorDataProvider
468
     *
469
     * @param string|null $sortBy
470
     * @param string|null $sortOrder
471
     * @param bool        $isAddOrderBy
472
     */
473
    public function testSortableInDataSourceIterator($sortBy, $sortOrder, $isAddOrderBy)
474
    {
475
        $datagrid = $this->getMockForAbstractClass(DatagridInterface::class);
476
        $configuration = $this->getMockBuilder(Configuration::class)->getMock();
477
        $configuration->expects($this->any())
478
            ->method('getDefaultQueryHints')
479
            ->willReturn([]);
480
481
        $em = $this->getMockBuilder(EntityManager::class)
482
            ->disableOriginalConstructor()
483
            ->getMock();
484
485
        $em->expects($this->any())
486
            ->method('getConfiguration')
487
            ->willReturn($configuration);
488
489
        $queryBuilder = $this->getMockBuilder(QueryBuilder::class)
490
            ->setConstructorArgs([$em])
491
            ->getMock();
492
        $query = new Query($em);
493
494
        $proxyQuery = $this->getMockBuilder(ProxyQuery::class)
495
            ->setConstructorArgs([$queryBuilder])
496
            ->setMethods(['getSortBy', 'getSortOrder', 'getRootAliases'])
497
            ->getMock();
498
499
        $proxyQuery->expects($this->any())
500
            ->method('getSortOrder')
501
            ->willReturn($sortOrder);
502
503
        $proxyQuery->expects($this->any())
504
            ->method('getSortBy')
505
            ->willReturn($sortBy);
506
507
        $queryBuilder->expects($isAddOrderBy ? $this->atLeastOnce() : $this->never())
508
            ->method('addOrderBy');
509
510
        $proxyQuery->expects($this->any())
511
            ->method('getRootAliases')
512
            ->willReturn(['a']);
513
514
        $queryBuilder->expects($this->any())
515
            ->method('getQuery')
516
            ->willReturn($query);
517
518
        $datagrid->expects($this->any())
519
            ->method('getQuery')
520
            ->willReturn($proxyQuery);
521
522
        $registry = $this->getMockBuilder(RegistryInterface::class)->getMock();
523
        $manager = new ModelManager($registry);
524
        $manager->getDataSourceIterator($datagrid, []);
525
526
        if ($isAddOrderBy) {
527
            $this->assertArrayHasKey($key = 'doctrine.customTreeWalkers', $hints = $query->getHints());
528
            $this->assertContains(OrderByToSelectWalker::class, $hints[$key]);
529
        }
530
    }
531
532
    public function testModelReverseTransform()
533
    {
534
        $class = SimpleEntity::class;
535
536
        $metadataFactory = $this->createMock(ClassMetadataFactory::class);
537
        $modelManager = $this->createMock(ObjectManager::class);
538
        $registry = $this->createMock(RegistryInterface::class);
539
540
        $classMetadata = new ClassMetadata($class);
541
        $classMetadata->reflClass = new \ReflectionClass($class);
542
543
        $modelManager->expects($this->once())
544
            ->method('getMetadataFactory')
545
            ->willReturn($metadataFactory);
546
        $metadataFactory->expects($this->once())
547
            ->method('getMetadataFor')
548
            ->with($class)
549
            ->willReturn($classMetadata);
550
        $registry->expects($this->once())
551
            ->method('getManagerForClass')
552
            ->with($class)
553
            ->willReturn($modelManager);
554
555
        $manager = new ModelManager($registry);
556
        $this->assertInstanceOf($class, $object = $manager->modelReverseTransform(
557
            $class,
558
            [
559
                'schmeckles' => 42,
560
                'multi_word_property' => 'hello',
561
            ]
562
        ));
563
        $this->assertSame(42, $object->getSchmeckles());
564
        $this->assertSame('hello', $object->getMultiWordProperty());
565
    }
566
567
    public function testCollections()
568
    {
569
        $registry = $this->createMock(RegistryInterface::class);
570
        $model = new ModelManager($registry);
571
572
        $collection = $model->getModelCollectionInstance('whyDoWeEvenHaveThisParameter');
573
        $this->assertInstanceOf(ArrayCollection::class, $collection);
574
575
        $item1 = 'item1';
576
        $item2 = 'item2';
577
        $model->collectionAddElement($collection, $item1);
578
        $model->collectionAddElement($collection, $item2);
579
580
        $this->assertTrue($model->collectionHasElement($collection, $item1));
581
582
        $model->collectionRemoveElement($collection, $item1);
583
584
        $this->assertFalse($model->collectionHasElement($collection, $item1));
585
586
        $model->collectionClear($collection);
587
588
        $this->assertTrue($collection->isEmpty());
589
    }
590
591
    public function testModelTransform()
592
    {
593
        $registry = $this->createMock(RegistryInterface::class);
594
        $model = new ModelManager($registry);
595
596
        $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...
597
598
        $this->assertSame('doWeNeedThisMethod', $result);
599
    }
600
601
    public function testGetPaginationParameters()
602
    {
603
        $datagrid = $this->createMock(DatagridInterface::class);
604
        $filter = $this->createMock(FilterInterface::class);
605
        $registry = $this->createMock(RegistryInterface::class);
606
607
        $datagrid->expects($this->once())
608
            ->method('getValues')
609
            ->willReturn(['_sort_by' => $filter]);
610
611
        $filter->expects($this->once())
612
            ->method('getName')
613
            ->willReturn($name = 'test');
614
615
        $model = new ModelManager($registry);
616
617
        $result = $model->getPaginationParameters($datagrid, $page = 5);
618
619
        $this->assertSame($page, $result['filter']['_page']);
620
        $this->assertSame($name, $result['filter']['_sort_by']);
621
    }
622
623
    public function testGetModelInstanceException()
624
    {
625
        $registry = $this->createMock(RegistryInterface::class);
626
627
        $model = new ModelManager($registry);
628
629
        $this->expectException(\RuntimeException::class);
630
631
        $model->getModelInstance(AbstractEntity::class);
632
    }
633
634
    public function testGetEntityManagerException()
635
    {
636
        $registry = $this->createMock(RegistryInterface::class);
637
638
        $model = new ModelManager($registry);
639
640
        $this->expectException(\RuntimeException::class);
641
642
        $model->getEntityManager(VersionedEntity::class);
643
    }
644
645
    public function testGetNewFieldDescriptionInstanceException()
646
    {
647
        $registry = $this->createMock(RegistryInterface::class);
648
649
        $model = new ModelManager($registry);
650
651
        $this->expectException(\RuntimeException::class);
652
653
        $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...
654
    }
655
656
    /**
657
     * @dataProvider createUpdateRemoveData
658
     */
659
    public function testCreate($exception)
660
    {
661
        $registry = $this->createMock(RegistryInterface::class);
662
663
        $entityManger = $this->createMock(EntityManager::class);
664
665
        $registry->expects($this->once())
666
            ->method('getManagerForClass')
667
            ->willReturn($entityManger);
668
669
        $entityManger->expects($this->once())
670
            ->method('persist');
671
672
        $entityManger->expects($this->once())
673
            ->method('flush')
674
            ->willThrowException($exception);
675
676
        $model = new ModelManager($registry);
677
678
        $this->expectException(ModelManagerException::class);
679
680
        $model->create(new VersionedEntity());
681
    }
682
683
    public function createUpdateRemoveData()
684
    {
685
        return [
686
            'PDOException' => [
687
                new \PDOException(),
688
            ],
689
            'DBALException' => [
690
                new DBALException(),
691
            ],
692
        ];
693
    }
694
695
    /**
696
     * @dataProvider createUpdateRemoveData
697
     */
698
    public function testUpdate($exception)
699
    {
700
        $registry = $this->createMock(RegistryInterface::class);
701
702
        $entityManger = $this->createMock(EntityManager::class);
703
704
        $registry->expects($this->once())
705
            ->method('getManagerForClass')
706
            ->willReturn($entityManger);
707
708
        $entityManger->expects($this->once())
709
            ->method('persist');
710
711
        $entityManger->expects($this->once())
712
            ->method('flush')
713
            ->willThrowException($exception);
714
715
        $model = new ModelManager($registry);
716
717
        $this->expectException(ModelManagerException::class);
718
719
        $model->update(new VersionedEntity());
720
    }
721
722
    /**
723
     * @dataProvider createUpdateRemoveData
724
     */
725
    public function testRemove($exception)
726
    {
727
        $registry = $this->createMock(RegistryInterface::class);
728
729
        $entityManger = $this->createMock(EntityManager::class);
730
731
        $registry->expects($this->once())
732
            ->method('getManagerForClass')
733
            ->willReturn($entityManger);
734
735
        $entityManger->expects($this->once())
736
            ->method('remove');
737
738
        $entityManger->expects($this->once())
739
            ->method('flush')
740
            ->willThrowException($exception);
741
742
        $model = new ModelManager($registry);
743
744
        $this->expectException(ModelManagerException::class);
745
746
        $model->delete(new VersionedEntity());
747
    }
748
749
    public function testFindBadId()
750
    {
751
        $registry = $this->createMock(RegistryInterface::class);
752
753
        $model = new ModelManager($registry);
754
755
        $this->assertNull($model->find('notImportant', null));
756
    }
757
758
    public function testGetUrlsafeIdentifierException()
759
    {
760
        $registry = $this->createMock(RegistryInterface::class);
761
762
        $model = new ModelManager($registry);
763
764
        $this->expectException(\RuntimeException::class);
765
766
        $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...
767
    }
768
769
    public function testGetUrlsafeIdentifierNull()
770
    {
771
        $registry = $this->createMock(RegistryInterface::class);
772
773
        $model = new ModelManager($registry);
774
775
        $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...
776
    }
777
778
    private function getMetadata($class, $isVersioned)
779
    {
780
        $metadata = new ClassMetadata($class);
781
782
        $metadata->isVersioned = $isVersioned;
783
784
        if ($isVersioned) {
785
            $versionField = 'version';
786
            $metadata->versionField = $versionField;
787
            $metadata->reflFields[$versionField] = new \ReflectionProperty($class, $versionField);
788
        }
789
790
        return $metadata;
791
    }
792
}
793