Passed
Pull Request — 2.8.x (#7928)
by Oliver
08:12
created

EntityRepositoryTest::testDeprecatedClear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 4
c 1
b 0
f 1
dl 0
loc 7
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Tests\ORM\Functional;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\LockMode;
9
use Doctrine\ORM\EntityRepository;
10
use Doctrine\ORM\OptimisticLockException;
11
use Doctrine\ORM\ORMException;
12
use Doctrine\ORM\Query;
13
use Doctrine\ORM\TransactionRequiredException;
14
use Doctrine\Tests\Models\CMS\CmsAddress;
15
use Doctrine\Tests\Models\CMS\CmsEmail;
16
use Doctrine\Tests\Models\CMS\CmsUser;
17
use Doctrine\Tests\Models\DDC753\DDC753CustomRepository;
18
use Doctrine\Tests\Models\DDC753\DDC753DefaultRepository;
19
use Doctrine\Tests\Models\DDC753\DDC753EntityWithCustomRepository;
20
use Doctrine\Tests\Models\DDC753\DDC753EntityWithDefaultCustomRepository;
21
use Doctrine\Tests\Models\DDC753\DDC753InvalidRepository;
22
use Doctrine\Tests\OrmFunctionalTestCase;
23
use Doctrine\Tests\VerifyDeprecations;
24
25
/**
26
 * @author robo
27
 */
28
class EntityRepositoryTest extends OrmFunctionalTestCase
29
{
30
    use VerifyDeprecations;
31
32
    protected function setUp()
33
    {
34
        $this->useModelSet('cms');
35
        parent::setUp();
36
    }
37
38
    public function tearDown()
39
    {
40
        if ($this->_em) {
41
            $this->_em->getConfiguration()->setEntityNamespaces([]);
42
        }
43
        parent::tearDown();
44
    }
45
46
    public function loadFixture()
47
    {
48
        $user = new CmsUser;
49
        $user->name = 'Roman';
50
        $user->username = 'romanb';
51
        $user->status = 'freak';
52
        $this->_em->persist($user);
53
54
        $user2 = new CmsUser;
55
        $user2->name = 'Guilherme';
56
        $user2->username = 'gblanco';
57
        $user2->status = 'dev';
58
        $this->_em->persist($user2);
59
60
        $user3 = new CmsUser;
61
        $user3->name = 'Benjamin';
62
        $user3->username = 'beberlei';
63
        $user3->status = null;
64
        $this->_em->persist($user3);
65
66
        $user4 = new CmsUser;
67
        $user4->name = 'Alexander';
68
        $user4->username = 'asm89';
69
        $user4->status = 'dev';
70
        $this->_em->persist($user4);
71
72
        $this->_em->flush();
73
74
        $user1Id = $user->getId();
75
76
        unset($user);
77
        unset($user2);
78
        unset($user3);
79
        unset($user4);
80
81
        $this->_em->clear();
82
83
        return $user1Id;
84
    }
85
86
    public function loadAssociatedFixture()
87
    {
88
        $address = new CmsAddress();
89
        $address->city = "Berlin";
90
        $address->country = "Germany";
91
        $address->street = "Foostreet";
92
        $address->zip = "12345";
93
94
        $user = new CmsUser();
95
        $user->name = 'Roman';
96
        $user->username = 'romanb';
97
        $user->status = 'freak';
98
        $user->setAddress($address);
99
100
        $this->_em->persist($user);
101
        $this->_em->persist($address);
102
        $this->_em->flush();
103
        $this->_em->clear();
104
105
        return [$user->id, $address->id];
106
    }
107
108
    public function loadFixtureUserEmail()
109
    {
110
        $user1 = new CmsUser();
111
        $user2 = new CmsUser();
112
        $user3 = new CmsUser();
113
114
        $email1 = new CmsEmail();
115
        $email2 = new CmsEmail();
116
        $email3 = new CmsEmail();
117
118
        $user1->name     = 'Test 1';
119
        $user1->username = 'test1';
120
        $user1->status   = 'active';
121
122
        $user2->name     = 'Test 2';
123
        $user2->username = 'test2';
124
        $user2->status   = 'active';
125
126
        $user3->name     = 'Test 3';
127
        $user3->username = 'test3';
128
        $user3->status   = 'active';
129
130
        $email1->email   = '[email protected]';
131
        $email2->email   = '[email protected]';
132
        $email3->email   = '[email protected]';
133
134
        $user1->setEmail($email1);
135
        $user2->setEmail($email2);
136
        $user3->setEmail($email3);
137
138
        $this->_em->persist($user1);
139
        $this->_em->persist($user2);
140
        $this->_em->persist($user3);
141
142
        $this->_em->persist($email1);
143
        $this->_em->persist($email2);
144
        $this->_em->persist($email3);
145
146
        $this->_em->flush();
147
        $this->_em->clear();
148
149
        return [$user1, $user2, $user3];
150
    }
151
152
    public function buildUser($name, $username, $status, $address)
153
    {
154
        $user = new CmsUser();
155
        $user->name     = $name;
156
        $user->username = $username;
157
        $user->status   = $status;
158
        $user->setAddress($address);
159
160
        $this->_em->persist($user);
161
        $this->_em->flush();
162
163
        return $user;
164
    }
165
166
    public function buildAddress($country, $city, $street, $zip)
167
    {
168
        $address = new CmsAddress();
169
        $address->country = $country;
170
        $address->city    = $city;
171
        $address->street  = $street;
172
        $address->zip     = $zip;
173
174
        $this->_em->persist($address);
175
        $this->_em->flush();
176
177
        return $address;
178
    }
179
180
    public function testBasicFind()
181
    {
182
        $user1Id = $this->loadFixture();
183
        $repos = $this->_em->getRepository(CmsUser::class);
184
185
        $user = $repos->find($user1Id);
186
        $this->assertInstanceOf(CmsUser::class,$user);
187
        $this->assertEquals('Roman', $user->name);
188
        $this->assertEquals('freak', $user->status);
189
    }
190
191
    public function testFindByField()
192
    {
193
        $user1Id = $this->loadFixture();
0 ignored issues
show
Unused Code introduced by
The assignment to $user1Id is dead and can be removed.
Loading history...
194
        $repos = $this->_em->getRepository(CmsUser::class);
195
196
        $users = $repos->findBy(['status' => 'dev']);
197
        $this->assertEquals(2, count($users));
198
        $this->assertInstanceOf(CmsUser::class,$users[0]);
199
        $this->assertEquals('Guilherme', $users[0]->name);
200
        $this->assertEquals('dev', $users[0]->status);
201
    }
202
203
    public function testFindByAssociationWithIntegerAsParameter()
204
    {
205
        $address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456');
206
        $user1    = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1);
207
208
        $address2 = $this->buildAddress('Brazil', 'São Paulo', 'Bar st.', '654321');
209
        $user2    = $this->buildUser('Guilherme', 'guilhermeblanco', 'freak', $address2);
210
211
        $address3 = $this->buildAddress('USA', 'Nashville', 'Woo st.', '321654');
212
        $user3    = $this->buildUser('Jonathan', 'jwage', 'dev', $address3);
0 ignored issues
show
Unused Code introduced by
The assignment to $user3 is dead and can be removed.
Loading history...
213
214
        unset($address1);
215
        unset($address2);
216
        unset($address3);
217
218
        $this->_em->clear();
219
220
        $repository = $this->_em->getRepository(CmsAddress::class);
221
        $addresses  = $repository->findBy(['user' => [$user1->getId(), $user2->getId()]]);
222
223
        $this->assertEquals(2, count($addresses));
224
        $this->assertInstanceOf(CmsAddress::class,$addresses[0]);
225
    }
226
227
    public function testFindByAssociationWithObjectAsParameter()
228
    {
229
        $address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456');
230
        $user1    = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1);
231
232
        $address2 = $this->buildAddress('Brazil', 'São Paulo', 'Bar st.', '654321');
233
        $user2    = $this->buildUser('Guilherme', 'guilhermeblanco', 'freak', $address2);
234
235
        $address3 = $this->buildAddress('USA', 'Nashville', 'Woo st.', '321654');
236
        $user3    = $this->buildUser('Jonathan', 'jwage', 'dev', $address3);
0 ignored issues
show
Unused Code introduced by
The assignment to $user3 is dead and can be removed.
Loading history...
237
238
        unset($address1);
239
        unset($address2);
240
        unset($address3);
241
242
        $this->_em->clear();
243
244
        $repository = $this->_em->getRepository(CmsAddress::class);
245
        $addresses  = $repository->findBy(['user' => [$user1, $user2]]);
246
247
        $this->assertEquals(2, count($addresses));
248
        $this->assertInstanceOf(CmsAddress::class,$addresses[0]);
249
    }
250
251
    public function testFindFieldByMagicCall()
252
    {
253
        $user1Id = $this->loadFixture();
0 ignored issues
show
Unused Code introduced by
The assignment to $user1Id is dead and can be removed.
Loading history...
254
        $repos = $this->_em->getRepository(CmsUser::class);
255
256
        $users = $repos->findByStatus('dev');
0 ignored issues
show
Bug introduced by
The method findByStatus() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

256
        /** @scrutinizer ignore-call */ 
257
        $users = $repos->findByStatus('dev');

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...
257
        $this->assertEquals(2, count($users));
258
        $this->assertInstanceOf(CmsUser::class,$users[0]);
259
        $this->assertEquals('Guilherme', $users[0]->name);
260
        $this->assertEquals('dev', $users[0]->status);
261
    }
262
263
    public function testFindAll()
264
    {
265
        $user1Id = $this->loadFixture();
0 ignored issues
show
Unused Code introduced by
The assignment to $user1Id is dead and can be removed.
Loading history...
266
        $repos = $this->_em->getRepository(CmsUser::class);
267
268
        $users = $repos->findAll();
269
        $this->assertEquals(4, count($users));
270
    }
271
272
    public function testFindByAlias()
273
    {
274
        $user1Id = $this->loadFixture();
0 ignored issues
show
Unused Code introduced by
The assignment to $user1Id is dead and can be removed.
Loading history...
275
        $repos = $this->_em->getRepository(CmsUser::class);
0 ignored issues
show
Unused Code introduced by
The assignment to $repos is dead and can be removed.
Loading history...
276
277
        $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS');
278
279
        $repos = $this->_em->getRepository('CMS:CmsUser');
280
281
        $users = $repos->findAll();
282
        $this->assertEquals(4, count($users));
283
    }
284
285
    public function testCount()
286
    {
287
        $this->loadFixture();
288
        $repos = $this->_em->getRepository(CmsUser::class);
289
290
        $userCount = $repos->count([]);
291
        $this->assertSame(4, $userCount);
292
293
        $userCount = $repos->count(['status' => 'dev']);
294
        $this->assertSame(2, $userCount);
295
296
        $userCount = $repos->count(['status' => 'nonexistent']);
297
        $this->assertSame(0, $userCount);
298
    }
299
300
    public function testCountBy()
301
    {
302
        $this->loadFixture();
303
        $repos = $this->_em->getRepository(CmsUser::class);
304
305
        $userCount = $repos->countByStatus('dev');
306
        $this->assertSame(2, $userCount);
307
    }
308
309
    /**
310
     * @expectedException \Doctrine\ORM\ORMException
311
     */
312
    public function testExceptionIsThrownWhenCallingFindByWithoutParameter() {
313
        $this->_em->getRepository(CmsUser::class)
314
                  ->findByStatus();
315
    }
316
317
    /**
318
     * @expectedException \Doctrine\ORM\ORMException
319
     */
320
    public function testExceptionIsThrownWhenUsingInvalidFieldName() {
321
        $this->_em->getRepository(CmsUser::class)
322
                  ->findByThisFieldDoesNotExist('testvalue');
0 ignored issues
show
Bug introduced by
The method findByThisFieldDoesNotExist() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

322
                  ->/** @scrutinizer ignore-call */ findByThisFieldDoesNotExist('testvalue');

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...
323
    }
324
325
    /**
326
     * @group locking
327
     * @group DDC-178
328
     */
329
    public function testPessimisticReadLockWithoutTransaction_ThrowsException()
330
    {
331
        $this->expectException(TransactionRequiredException::class);
332
333
        $this->_em->getRepository(CmsUser::class)
334
                  ->find(1, LockMode::PESSIMISTIC_READ);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\Common\Persiste...bjectRepository::find() has too many arguments starting with Doctrine\DBAL\LockMode::PESSIMISTIC_READ. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

334
                  ->/** @scrutinizer ignore-call */ find(1, LockMode::PESSIMISTIC_READ);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
335
    }
336
337
    /**
338
     * @group locking
339
     * @group DDC-178
340
     */
341
    public function testPessimisticWriteLockWithoutTransaction_ThrowsException()
342
    {
343
        $this->expectException(TransactionRequiredException::class);
344
345
        $this->_em->getRepository(CmsUser::class)
346
                  ->find(1, LockMode::PESSIMISTIC_WRITE);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\Common\Persiste...bjectRepository::find() has too many arguments starting with Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

346
                  ->/** @scrutinizer ignore-call */ find(1, LockMode::PESSIMISTIC_WRITE);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
347
    }
348
349
    /**
350
     * @group locking
351
     * @group DDC-178
352
     */
353
    public function testOptimisticLockUnversionedEntity_ThrowsException()
354
    {
355
        $this->expectException(OptimisticLockException::class);
356
357
        $this->_em->getRepository(CmsUser::class)
358
                  ->find(1, LockMode::OPTIMISTIC);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\Common\Persiste...bjectRepository::find() has too many arguments starting with Doctrine\DBAL\LockMode::OPTIMISTIC. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

358
                  ->/** @scrutinizer ignore-call */ find(1, LockMode::OPTIMISTIC);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
359
    }
360
361
    /**
362
     * @group locking
363
     * @group DDC-178
364
     */
365
    public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsException()
366
    {
367
        $user = new CmsUser;
368
        $user->name = 'Roman';
369
        $user->username = 'romanb';
370
        $user->status = 'freak';
371
        $this->_em->persist($user);
372
        $this->_em->flush();
373
374
        $userId = $user->id;
375
376
        $this->_em->find(CmsUser::class, $userId);
377
378
        $this->expectException(OptimisticLockException::class);
379
380
        $this->_em->find(CmsUser::class, $userId, LockMode::OPTIMISTIC);
381
    }
382
383
    /**
384
     * @group DDC-819
385
     */
386
    public function testFindMagicCallByNullValue()
387
    {
388
        $this->loadFixture();
389
390
        $repos = $this->_em->getRepository(CmsUser::class);
391
392
        $users = $repos->findByStatus(null);
393
        $this->assertEquals(1, count($users));
394
    }
395
396
    /**
397
     * @group DDC-819
398
     */
399
    public function testInvalidMagicCall()
400
    {
401
        $this->expectException(\BadMethodCallException::class);
402
403
        $repos = $this->_em->getRepository(CmsUser::class);
404
        $repos->foo();
405
    }
406
407
    /**
408
     * @group DDC-817
409
     */
410
    public function testFindByAssociationKey_ExceptionOnInverseSide()
411
    {
412
        list($userId, $addressId) = $this->loadAssociatedFixture();
413
        $repos = $this->_em->getRepository(CmsUser::class);
414
415
        $this->expectException(ORMException::class);
416
        $this->expectExceptionMessage("You cannot search for the association field 'Doctrine\Tests\Models\CMS\CmsUser#address', because it is the inverse side of an association. Find methods only work on owning side associations.");
417
418
        $user = $repos->findBy(['address' => $addressId]);
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
419
    }
420
421
    /**
422
     * @group DDC-817
423
     */
424
    public function testFindOneByAssociationKey()
425
    {
426
        list($userId, $addressId) = $this->loadAssociatedFixture();
427
        $repos = $this->_em->getRepository(CmsAddress::class);
428
        $address = $repos->findOneBy(['user' => $userId]);
429
430
        $this->assertInstanceOf(CmsAddress::class, $address);
431
        $this->assertEquals($addressId, $address->id);
432
    }
433
434
    /**
435
     * @group DDC-1241
436
     */
437
    public function testFindOneByOrderBy()
438
    {
439
    	$this->loadFixture();
440
441
    	$repos = $this->_em->getRepository(CmsUser::class);
442
    	$userAsc = $repos->findOneBy([], ["username" => "ASC"]);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\Common\Persiste...Repository::findOneBy() has too many arguments starting with array('username' => 'ASC'). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

442
    	/** @scrutinizer ignore-call */ 
443
     $userAsc = $repos->findOneBy([], ["username" => "ASC"]);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
443
    	$userDesc = $repos->findOneBy([], ["username" => "DESC"]);
444
445
    	$this->assertNotSame($userAsc, $userDesc);
446
    }
447
448
    /**
449
     * @group DDC-817
450
     */
451
    public function testFindByAssociationKey()
452
    {
453
        list($userId, $addressId) = $this->loadAssociatedFixture();
454
        $repos = $this->_em->getRepository(CmsAddress::class);
455
        $addresses = $repos->findBy(['user' => $userId]);
456
457
        $this->assertContainsOnly(CmsAddress::class, $addresses);
458
        $this->assertEquals(1, count($addresses));
459
        $this->assertEquals($addressId, $addresses[0]->id);
460
    }
461
462
    /**
463
     * @group DDC-817
464
     */
465
    public function testFindAssociationByMagicCall()
466
    {
467
        list($userId, $addressId) = $this->loadAssociatedFixture();
468
        $repos = $this->_em->getRepository(CmsAddress::class);
469
        $addresses = $repos->findByUser($userId);
0 ignored issues
show
Bug introduced by
The method findByUser() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

469
        /** @scrutinizer ignore-call */ 
470
        $addresses = $repos->findByUser($userId);

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...
470
471
        $this->assertContainsOnly(CmsAddress::class, $addresses);
472
        $this->assertEquals(1, count($addresses));
473
        $this->assertEquals($addressId, $addresses[0]->id);
474
    }
475
476
    /**
477
     * @group DDC-817
478
     */
479
    public function testFindOneAssociationByMagicCall()
480
    {
481
        list($userId, $addressId) = $this->loadAssociatedFixture();
482
        $repos = $this->_em->getRepository(CmsAddress::class);
483
        $address = $repos->findOneByUser($userId);
0 ignored issues
show
Bug introduced by
The method findOneByUser() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

483
        /** @scrutinizer ignore-call */ 
484
        $address = $repos->findOneByUser($userId);

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...
484
485
        $this->assertInstanceOf(CmsAddress::class, $address);
486
        $this->assertEquals($addressId, $address->id);
487
    }
488
489
    public function testValidNamedQueryRetrieval()
490
    {
491
        $repos = $this->_em->getRepository(CmsUser::class);
492
493
        $query = $repos->createNamedQuery('all');
494
495
        $this->assertInstanceOf(Query::class, $query);
496
        $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL());
497
    }
498
499
    public function testInvalidNamedQueryRetrieval()
500
    {
501
        $repos = $this->_em->getRepository(CmsUser::class);
502
503
        $this->expectException(\Doctrine\ORM\Mapping\MappingException::class);
504
505
        $repos->createNamedQuery('invalidNamedQuery');
506
    }
507
508
    /**
509
     * @group DDC-1087
510
     */
511
    public function testIsNullCriteriaDoesNotGenerateAParameter()
512
    {
513
        $repos = $this->_em->getRepository(CmsUser::class);
514
        $users = $repos->findBy(['status' => null, 'username' => 'romanb']);
0 ignored issues
show
Unused Code introduced by
The assignment to $users is dead and can be removed.
Loading history...
515
516
        $params = $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'];
517
        $this->assertEquals(1, count($params), "Should only execute with one parameter.");
518
        $this->assertEquals(['romanb'], $params);
519
    }
520
521
    public function testIsNullCriteria()
522
    {
523
        $this->loadFixture();
524
525
        $repos = $this->_em->getRepository(CmsUser::class);
526
527
        $users = $repos->findBy(['status' => null]);
528
        $this->assertEquals(1, count($users));
529
    }
530
531
    /**
532
     * @group DDC-1094
533
     */
534
    public function testFindByLimitOffset()
535
    {
536
        $this->loadFixture();
537
538
        $repos = $this->_em->getRepository(CmsUser::class);
539
540
        $users1 = $repos->findBy([], null, 1, 0);
541
        $users2 = $repos->findBy([], null, 1, 1);
542
543
        $this->assertEquals(4, count($repos->findBy([])));
544
        $this->assertEquals(1, count($users1));
545
        $this->assertEquals(1, count($users2));
546
        $this->assertNotSame($users1[0], $users2[0]);
547
    }
548
549
    /**
550
     * @group DDC-1094
551
     */
552
    public function testFindByOrderBy()
553
    {
554
        $this->loadFixture();
555
556
        $repos = $this->_em->getRepository(CmsUser::class);
557
        $usersAsc = $repos->findBy([], ["username" => "ASC"]);
558
        $usersDesc = $repos->findBy([], ["username" => "DESC"]);
559
560
        $this->assertEquals(4, count($usersAsc), "Pre-condition: only four users in fixture");
561
        $this->assertEquals(4, count($usersDesc), "Pre-condition: only four users in fixture");
562
        $this->assertSame($usersAsc[0], $usersDesc[3]);
563
        $this->assertSame($usersAsc[3], $usersDesc[0]);
564
    }
565
566
    /**
567
     * @group DDC-1376
568
     */
569
    public function testFindByOrderByAssociation()
570
    {
571
        $this->loadFixtureUserEmail();
572
573
        $repository = $this->_em->getRepository(CmsUser::class);
574
        $resultAsc  = $repository->findBy([], ['email' => 'ASC']);
575
        $resultDesc = $repository->findBy([], ['email' => 'DESC']);
576
577
        $this->assertCount(3, $resultAsc);
578
        $this->assertCount(3, $resultDesc);
579
580
        $this->assertEquals($resultAsc[0]->getEmail()->getId(), $resultDesc[2]->getEmail()->getId());
581
        $this->assertEquals($resultAsc[2]->getEmail()->getId(), $resultDesc[0]->getEmail()->getId());
582
    }
583
584
    /**
585
     * @group DDC-1426
586
     */
587
    public function testFindFieldByMagicCallOrderBy()
588
    {
589
        $this->loadFixture();
590
        $repos = $this->_em->getRepository(CmsUser::class);
591
592
        $usersAsc = $repos->findByStatus('dev', ['username' => "ASC"]);
593
        $usersDesc = $repos->findByStatus('dev', ['username' => "DESC"]);
594
595
        $this->assertEquals(2, count($usersAsc));
596
        $this->assertEquals(2, count($usersDesc));
597
598
        $this->assertInstanceOf(CmsUser::class,$usersAsc[0]);
599
        $this->assertEquals('Alexander', $usersAsc[0]->name);
600
        $this->assertEquals('dev', $usersAsc[0]->status);
601
602
        $this->assertSame($usersAsc[0], $usersDesc[1]);
603
        $this->assertSame($usersAsc[1], $usersDesc[0]);
604
    }
605
606
    /**
607
     * @group DDC-1426
608
     */
609
    public function testFindFieldByMagicCallLimitOffset()
610
    {
611
        $this->loadFixture();
612
        $repos = $this->_em->getRepository(CmsUser::class);
613
614
        $users1 = $repos->findByStatus('dev', [], 1, 0);
615
        $users2 = $repos->findByStatus('dev', [], 1, 1);
616
617
        $this->assertEquals(1, count($users1));
618
        $this->assertEquals(1, count($users2));
619
        $this->assertNotSame($users1[0], $users2[0]);
620
    }
621
622
    /**
623
     * @group DDC-753
624
     */
625
    public function testDefaultRepositoryClassName()
626
    {
627
        $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class);
628
        $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753DefaultRepository::class);
629
        $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class);
630
631
        $repos = $this->_em->getRepository(DDC753EntityWithDefaultCustomRepository::class);
632
        $this->assertInstanceOf(DDC753DefaultRepository::class, $repos);
633
        $this->assertTrue($repos->isDefaultRepository());
634
635
636
        $repos = $this->_em->getRepository(DDC753EntityWithCustomRepository::class);
637
        $this->assertInstanceOf(DDC753CustomRepository::class, $repos);
638
        $this->assertTrue($repos->isCustomRepository());
639
640
        $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class);
641
        $this->_em->getConfiguration()->setDefaultRepositoryClassName(EntityRepository::class);
642
        $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class);
643
644
    }
645
646
    /**
647
     * @group DDC-753
648
     * @expectedException Doctrine\ORM\ORMException
649
     * @expectedExceptionMessage Invalid repository class 'Doctrine\Tests\Models\DDC753\DDC753InvalidRepository'. It must be a Doctrine\Common\Persistence\ObjectRepository.
650
     */
651
    public function testSetDefaultRepositoryInvalidClassError()
652
    {
653
        $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class);
654
        $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753InvalidRepository::class);
655
    }
656
657
    /**
658
     * @group DDC-3257
659
     */
660
    public function testSingleRepositoryInstanceForDifferentEntityAliases()
661
    {
662
        $config = $this->_em->getConfiguration();
663
664
        $config->addEntityNamespace('Aliased', 'Doctrine\Tests\Models\CMS');
665
        $config->addEntityNamespace('AliasedAgain', 'Doctrine\Tests\Models\CMS');
666
667
        $repository = $this->_em->getRepository(CmsUser::class);
668
669
        $this->assertSame($repository, $this->_em->getRepository('Aliased:CmsUser'));
670
        $this->assertSame($repository, $this->_em->getRepository('AliasedAgain:CmsUser'));
671
    }
672
673
    /**
674
     * @group DDC-3257
675
     */
676
    public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash()
677
    {
678
        $this->assertSame(
679
            $this->_em->getRepository('\\' . CmsUser::class),
680
            $this->_em->getRepository(CmsUser::class)
681
        );
682
    }
683
684
    /**
685
     * @group DDC-1376
686
     *
687
     * @expectedException Doctrine\ORM\ORMException
688
     * @expectedExceptionMessage You cannot search for the association field 'Doctrine\Tests\Models\CMS\CmsUser#address', because it is the inverse side of an association.
689
     */
690
    public function testInvalidOrderByAssociation()
691
    {
692
        $this->_em->getRepository(CmsUser::class)
693
            ->findBy(['status' => 'test'], ['address' => 'ASC']);
694
    }
695
696
    /**
697
     * @group DDC-1500
698
     */
699
    public function testInvalidOrientation()
700
    {
701
        $this->expectException(ORMException::class);
702
        $this->expectExceptionMessage('Invalid order by orientation specified for Doctrine\Tests\Models\CMS\CmsUser#username');
703
704
        $repo = $this->_em->getRepository(CmsUser::class);
705
        $repo->findBy(['status' => 'test'], ['username' => 'INVALID']);
706
    }
707
708
    /**
709
     * @group DDC-1713
710
     */
711
    public function testFindByAssociationArray()
712
    {
713
        $repo = $this->_em->getRepository(CmsAddress::class);
714
        $data = $repo->findBy(['user' => [1, 2, 3]]);
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
715
716
        $query = array_pop($this->_sqlLoggerStack->queries);
717
        $this->assertEquals([1,2,3], $query['params'][0]);
718
        $this->assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]);
719
    }
720
721
    /**
722
     * @group DDC-1637
723
     */
724
    public function testMatchingEmptyCriteria()
725
    {
726
        $this->loadFixture();
727
728
        $repository = $this->_em->getRepository(CmsUser::class);
729
        $users = $repository->matching(new Criteria());
730
731
        $this->assertEquals(4, count($users));
732
    }
733
734
    /**
735
     * @group DDC-1637
736
     */
737
    public function testMatchingCriteriaEqComparison()
738
    {
739
        $this->loadFixture();
740
741
        $repository = $this->_em->getRepository(CmsUser::class);
742
        $users = $repository->matching(new Criteria(
743
            Criteria::expr()->eq('username', 'beberlei')
744
        ));
745
746
        $this->assertEquals(1, count($users));
747
    }
748
749
    /**
750
     * @group DDC-1637
751
     */
752
    public function testMatchingCriteriaNeqComparison()
753
    {
754
        $this->loadFixture();
755
756
        $repository = $this->_em->getRepository(CmsUser::class);
757
        $users = $repository->matching(new Criteria(
758
            Criteria::expr()->neq('username', 'beberlei')
759
        ));
760
761
        $this->assertEquals(3, count($users));
762
    }
763
764
    /**
765
     * @group DDC-1637
766
     */
767
    public function testMatchingCriteriaInComparison()
768
    {
769
        $this->loadFixture();
770
771
        $repository = $this->_em->getRepository(CmsUser::class);
772
        $users = $repository->matching(new Criteria(
773
            Criteria::expr()->in('username', ['beberlei', 'gblanco'])
774
        ));
775
776
        $this->assertEquals(2, count($users));
777
    }
778
779
    /**
780
     * @group DDC-1637
781
     */
782
    public function testMatchingCriteriaNotInComparison()
783
    {
784
        $this->loadFixture();
785
786
        $repository = $this->_em->getRepository(CmsUser::class);
787
        $users = $repository->matching(new Criteria(
788
            Criteria::expr()->notIn('username', ['beberlei', 'gblanco', 'asm89'])
789
        ));
790
791
        $this->assertEquals(1, count($users));
792
    }
793
794
    /**
795
     * @group DDC-1637
796
     */
797
    public function testMatchingCriteriaLtComparison()
798
    {
799
        $firstUserId = $this->loadFixture();
800
801
        $repository = $this->_em->getRepository(CmsUser::class);
802
        $users = $repository->matching(new Criteria(
803
            Criteria::expr()->lt('id', $firstUserId + 1)
804
        ));
805
806
        $this->assertEquals(1, count($users));
807
    }
808
809
    /**
810
     * @group DDC-1637
811
     */
812
    public function testMatchingCriteriaLeComparison()
813
    {
814
        $firstUserId = $this->loadFixture();
815
816
        $repository = $this->_em->getRepository(CmsUser::class);
817
        $users = $repository->matching(new Criteria(
818
            Criteria::expr()->lte('id', $firstUserId + 1)
819
        ));
820
821
        $this->assertEquals(2, count($users));
822
    }
823
824
    /**
825
     * @group DDC-1637
826
     */
827
    public function testMatchingCriteriaGtComparison()
828
    {
829
        $firstUserId = $this->loadFixture();
830
831
        $repository = $this->_em->getRepository(CmsUser::class);
832
        $users = $repository->matching(new Criteria(
833
            Criteria::expr()->gt('id', $firstUserId)
834
        ));
835
836
        $this->assertEquals(3, count($users));
837
    }
838
839
    /**
840
     * @group DDC-1637
841
     */
842
    public function testMatchingCriteriaGteComparison()
843
    {
844
        $firstUserId = $this->loadFixture();
845
846
        $repository = $this->_em->getRepository(CmsUser::class);
847
        $users = $repository->matching(new Criteria(
848
            Criteria::expr()->gte('id', $firstUserId)
849
        ));
850
851
        $this->assertEquals(4, count($users));
852
    }
853
854
    /**
855
     * @group DDC-2430
856
     */
857
    public function testMatchingCriteriaAssocationByObjectInMemory()
858
    {
859
        list($userId, $addressId) = $this->loadAssociatedFixture();
860
861
        $user = $this->_em->find(CmsUser::class, $userId);
862
863
        $criteria = new Criteria(
864
            Criteria::expr()->eq('user', $user)
865
        );
866
867
        $repository = $this->_em->getRepository(CmsAddress::class);
868
        $addresses = $repository->matching($criteria);
869
870
        $this->assertEquals(1, count($addresses));
871
872
        $addresses = new ArrayCollection($repository->findAll());
873
874
        $this->assertEquals(1, count($addresses->matching($criteria)));
875
    }
876
877
    /**
878
     * @group DDC-2430
879
     */
880
    public function testMatchingCriteriaAssocationInWithArray()
881
    {
882
        list($userId, $addressId) = $this->loadAssociatedFixture();
883
884
        $user = $this->_em->find(CmsUser::class, $userId);
885
886
        $criteria = new Criteria(
887
            Criteria::expr()->in('user', [$user])
888
        );
889
890
        $repository = $this->_em->getRepository(CmsAddress::class);
891
        $addresses = $repository->matching($criteria);
892
893
        $this->assertEquals(1, count($addresses));
894
895
        $addresses = new ArrayCollection($repository->findAll());
896
897
        $this->assertEquals(1, count($addresses->matching($criteria)));
898
    }
899
900
    public function testMatchingCriteriaContainsComparison()
901
    {
902
        $this->loadFixture();
903
904
        $repository = $this->_em->getRepository(CmsUser::class);
905
906
        $users = $repository->matching(new Criteria(Criteria::expr()->contains('name', 'Foobar')));
907
        $this->assertEquals(0, count($users));
908
909
        $users = $repository->matching(new Criteria(Criteria::expr()->contains('name', 'Rom')));
910
        $this->assertEquals(1, count($users));
911
912
        $users = $repository->matching(new Criteria(Criteria::expr()->contains('status', 'dev')));
913
        $this->assertEquals(2, count($users));
914
    }
915
916
    public function testMatchingCriteriaStartsWithComparison()
917
    {
918
        $this->loadFixture();
919
920
        $repository = $this->_em->getRepository(CmsUser::class);
921
922
        $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'Foo')));
923
        $this->assertCount(0, $users);
924
925
        $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'R')));
926
        $this->assertCount(1, $users);
927
928
        $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('status', 'de')));
929
        $this->assertCount(2, $users);
930
    }
931
932
    public function testMatchingCriteriaEndsWithComparison()
933
    {
934
        $this->loadFixture();
935
936
        $repository = $this->_em->getRepository(CmsUser::class);
937
938
        $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'foo')));
939
        $this->assertCount(0, $users);
940
941
        $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'oman')));
942
        $this->assertCount(1, $users);
943
944
        $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('status', 'ev')));
945
        $this->assertCount(2, $users);
946
    }
947
948
    /**
949
     * @group DDC-2478
950
     */
951
    public function testMatchingCriteriaNullAssocComparison()
952
    {
953
        $fixtures       = $this->loadFixtureUserEmail();
954
        $user           = $this->_em->merge($fixtures[0]);
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\ORM\EntityManager::merge() has been deprecated: 2.7 This method is being removed from the ORM and won't have any replacement ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

954
        $user           = /** @scrutinizer ignore-deprecated */ $this->_em->merge($fixtures[0]);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
955
        $repository     = $this->_em->getRepository(CmsUser::class);
956
        $criteriaIsNull = Criteria::create()->where(Criteria::expr()->isNull('email'));
957
        $criteriaEqNull = Criteria::create()->where(Criteria::expr()->eq('email', null));
958
959
        $user->setEmail(null);
960
        $this->_em->persist($user);
961
        $this->_em->flush();
962
        $this->_em->clear();
963
964
        $usersIsNull = $repository->matching($criteriaIsNull);
965
        $usersEqNull = $repository->matching($criteriaEqNull);
966
967
        $this->assertCount(1, $usersIsNull);
968
        $this->assertCount(1, $usersEqNull);
969
970
        $this->assertInstanceOf(CmsUser::class, $usersIsNull[0]);
971
        $this->assertInstanceOf(CmsUser::class, $usersEqNull[0]);
972
973
        $this->assertNull($usersIsNull[0]->getEmail());
974
        $this->assertNull($usersEqNull[0]->getEmail());
975
        $this->assertHasDeprecationMessages();
976
    }
977
978
    /**
979
     * @group DDC-2055
980
     */
981
    public function testCreateResultSetMappingBuilder()
982
    {
983
        $repository = $this->_em->getRepository(CmsUser::class);
984
        $rsm = $repository->createResultSetMappingBuilder('u');
985
986
        $this->assertInstanceOf(Query\ResultSetMappingBuilder::class, $rsm);
987
        $this->assertEquals(['u' => CmsUser::class], $rsm->aliasMap);
988
    }
989
990
    /**
991
     * @group DDC-3045
992
     */
993
    public function testFindByFieldInjectionPrevented()
994
    {
995
        $this->expectException(ORMException::class);
996
        $this->expectExceptionMessage('Unrecognized field: ');
997
998
        $repository = $this->_em->getRepository(CmsUser::class);
999
        $repository->findBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']);
1000
    }
1001
1002
    /**
1003
     * @group DDC-3045
1004
     */
1005
    public function testFindOneByFieldInjectionPrevented()
1006
    {
1007
        $this->expectException(ORMException::class);
1008
        $this->expectExceptionMessage('Unrecognized field: ');
1009
1010
        $repository = $this->_em->getRepository(CmsUser::class);
1011
        $repository->findOneBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']);
1012
    }
1013
1014
    /**
1015
     * @group DDC-3045
1016
     */
1017
    public function testMatchingInjectionPrevented()
1018
    {
1019
        $this->expectException(ORMException::class);
1020
        $this->expectExceptionMessage('Unrecognized field: ');
1021
1022
        $repository = $this->_em->getRepository(CmsUser::class);
1023
        $result     = $repository->matching(new Criteria(
1024
            Criteria::expr()->eq('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1', 'beberlei')
1025
        ));
1026
1027
        // Because repository returns a lazy collection, we call toArray to force initialization
1028
        $result->toArray();
1029
    }
1030
1031
    /**
1032
     * @group DDC-3045
1033
     */
1034
    public function testFindInjectionPrevented()
1035
    {
1036
        $this->expectException(ORMException::class);
1037
        $this->expectExceptionMessage('Unrecognized identifier fields: ');
1038
1039
        $repository = $this->_em->getRepository(CmsUser::class);
1040
        $repository->find(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test', 'id' => 1]);
1041
    }
1042
1043
    /**
1044
     * @group DDC-3056
1045
     */
1046
    public function testFindByNullValueInInCondition()
1047
    {
1048
        $user1 = new CmsUser();
1049
        $user2 = new CmsUser();
1050
1051
        $user1->username = 'ocramius';
1052
        $user1->name = 'Marco';
1053
        $user2->status = null;
1054
        $user2->username = 'deeky666';
1055
        $user2->name = 'Steve';
1056
        $user2->status = 'dbal maintainer';
1057
1058
        $this->_em->persist($user1);
1059
        $this->_em->persist($user2);
1060
        $this->_em->flush();
1061
1062
        $users = $this->_em->getRepository(CmsUser::class)->findBy(['status' => [null]]);
1063
1064
        $this->assertCount(1, $users);
1065
        $this->assertSame($user1, reset($users));
1066
    }
1067
1068
    /**
1069
     * @group DDC-3056
1070
     */
1071
    public function testFindByNullValueInMultipleInCriteriaValues()
1072
    {
1073
        $user1 = new CmsUser();
1074
        $user2 = new CmsUser();
1075
1076
        $user1->username = 'ocramius';
1077
        $user1->name = 'Marco';
1078
        $user2->status = null;
1079
        $user2->username = 'deeky666';
1080
        $user2->name = 'Steve';
1081
        $user2->status = 'dbal maintainer';
1082
1083
        $this->_em->persist($user1);
1084
        $this->_em->persist($user2);
1085
        $this->_em->flush();
1086
1087
        $users = $this
1088
            ->_em
1089
            ->getRepository(CmsUser::class)
1090
            ->findBy(['status' => ['foo', null]]);
1091
1092
        $this->assertCount(1, $users);
1093
        $this->assertSame($user1, reset($users));
1094
    }
1095
1096
    /**
1097
     * @group DDC-3056
1098
     */
1099
    public function testFindMultipleByNullValueInMultipleInCriteriaValues()
1100
    {
1101
        $user1 = new CmsUser();
1102
        $user2 = new CmsUser();
1103
1104
        $user1->username = 'ocramius';
1105
        $user1->name = 'Marco';
1106
        $user2->status = null;
1107
        $user2->username = 'deeky666';
1108
        $user2->name = 'Steve';
1109
        $user2->status = 'dbal maintainer';
1110
1111
        $this->_em->persist($user1);
1112
        $this->_em->persist($user2);
1113
        $this->_em->flush();
1114
1115
        $users = $this
1116
            ->_em
1117
            ->getRepository(CmsUser::class)
1118
            ->findBy(['status' => ['dbal maintainer', null]]);
1119
1120
        $this->assertCount(2, $users);
1121
1122
        foreach ($users as $user) {
1123
            $this->assertTrue(in_array($user, [$user1, $user2]));
1124
        }
1125
    }
1126
1127
    public function testDeprecatedClear() : void
1128
    {
1129
        $repository = $this->_em->getRepository(CmsAddress::class);
1130
1131
        $this->expectDeprecationMessage('Method Doctrine\ORM\EntityRepository::clear() is deprecated and will be removed in Doctrine ORM 3.0.');
1132
        $this->expectDeprecationMessage('Calling Doctrine\ORM\EntityManager::clear() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.');
1133
        $repository->clear();
1134
    }
1135
}
1136
1137