Failed Conditions
Push — master ( 2b8acb...aa13e4 )
by Luís
14s
created

Doctrine/Tests/ORM/Functional/SQLFilterTest.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Doctrine\Tests\ORM\Functional;
4
5
use Doctrine\Common\Cache\ArrayCache;
6
use Doctrine\DBAL\Connection;
7
use Doctrine\DBAL\Types\Type as DBALType;
8
use Doctrine\ORM\Configuration;
9
use Doctrine\ORM\EntityManager;
10
use Doctrine\ORM\Mapping\ClassMetadata;
11
use Doctrine\ORM\Mapping\ClassMetadataInfo;
12
use Doctrine\ORM\Query\Filter\SQLFilter;
13
use Doctrine\ORM\Query\FilterCollection;
14
use Doctrine\Tests\Models\CMS\CmsAddress;
15
use Doctrine\Tests\Models\CMS\CmsArticle;
16
use Doctrine\Tests\Models\CMS\CmsGroup;
17
use Doctrine\Tests\Models\CMS\CmsUser;
18
use Doctrine\Tests\Models\Company\CompanyAuction;
19
use Doctrine\Tests\Models\Company\CompanyContract;
20
use Doctrine\Tests\Models\Company\CompanyEvent;
21
use Doctrine\Tests\Models\Company\CompanyFlexContract;
22
use Doctrine\Tests\Models\Company\CompanyFlexUltraContract;
23
use Doctrine\Tests\Models\Company\CompanyManager;
24
use Doctrine\Tests\Models\Company\CompanyOrganization;
25
use Doctrine\Tests\Models\Company\CompanyPerson;
26
use Doctrine\Tests\OrmFunctionalTestCase;
27
28
/**
29
 * Tests SQLFilter functionality.
30
 *
31
 * @author Alexander <[email protected]>
32
 *
33
 * @group non-cacheable
34
 */
35
class SQLFilterTest extends OrmFunctionalTestCase
36
{
37
    private $userId, $userId2, $articleId, $articleId2;
38
    private $groupId, $groupId2;
39
    private $managerId, $managerId2, $contractId1, $contractId2;
40
    private $organizationId, $eventId1, $eventId2;
41
42
    public function setUp()
43
    {
44
        $this->useModelSet('cms');
45
        $this->useModelSet('company');
46
        parent::setUp();
47
    }
48
49
    public function tearDown()
50
    {
51
        parent::tearDown();
52
53
        $class = $this->_em->getClassMetadata(CmsUser::class);
54
        $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
55
        $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
56
    }
57
58
    public function testConfigureFilter()
59
    {
60
        $config = new Configuration();
61
62
        $config->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter");
63
64
        $this->assertEquals("\Doctrine\Tests\ORM\Functional\MyLocaleFilter", $config->getFilterClassName("locale"));
65
        $this->assertNull($config->getFilterClassName("foo"));
66
    }
67
68
    public function testEntityManagerEnableFilter()
69
    {
70
        $em = $this->_getEntityManager();
71
        $this->configureFilters($em);
72
73
        // Enable an existing filter
74
        $filter = $em->getFilters()->enable("locale");
75
        $this->assertTrue($filter instanceof MyLocaleFilter);
76
77
        // Enable the filter again
78
        $filter2 = $em->getFilters()->enable("locale");
79
        $this->assertEquals($filter, $filter2);
80
81
        // Enable a non-existing filter
82
        $exceptionThrown = false;
83
        try {
84
            $filter = $em->getFilters()->enable("foo");
85
        } catch (\InvalidArgumentException $e) {
86
            $exceptionThrown = true;
87
        }
88
        $this->assertTrue($exceptionThrown);
89
    }
90
91
    public function testEntityManagerEnabledFilters()
92
    {
93
        $em = $this->_getEntityManager();
94
95
        // No enabled filters
96
        $this->assertEquals([], $em->getFilters()->getEnabledFilters());
97
98
        $this->configureFilters($em);
99
        $filter = $em->getFilters()->enable("locale");
100
        $filter = $em->getFilters()->enable("soft_delete");
101
102
        // Two enabled filters
103
        $this->assertEquals(2, count($em->getFilters()->getEnabledFilters()));
104
105
    }
106
107
    public function testEntityManagerDisableFilter()
108
    {
109
        $em = $this->_getEntityManager();
110
        $this->configureFilters($em);
111
112
        // Enable the filter
113
        $filter = $em->getFilters()->enable("locale");
114
115
        // Disable it
116
        $this->assertEquals($filter, $em->getFilters()->disable("locale"));
117
        $this->assertEquals(0, count($em->getFilters()->getEnabledFilters()));
118
119
        // Disable a non-existing filter
120
        $exceptionThrown = false;
121
        try {
122
            $filter = $em->getFilters()->disable("foo");
123
        } catch (\InvalidArgumentException $e) {
124
            $exceptionThrown = true;
125
        }
126
        $this->assertTrue($exceptionThrown);
127
128
        // Disable a non-enabled filter
129
        $exceptionThrown = false;
130
        try {
131
            $filter = $em->getFilters()->disable("locale");
132
        } catch (\InvalidArgumentException $e) {
133
            $exceptionThrown = true;
134
        }
135
        $this->assertTrue($exceptionThrown);
136
    }
137
138
    public function testEntityManagerGetFilter()
139
    {
140
        $em = $this->_getEntityManager();
141
        $this->configureFilters($em);
142
143
        // Enable the filter
144
        $filter = $em->getFilters()->enable("locale");
145
146
        // Get the filter
147
        $this->assertEquals($filter, $em->getFilters()->getFilter("locale"));
148
149
        // Get a non-enabled filter
150
        $exceptionThrown = false;
151
        try {
152
            $filter = $em->getFilters()->getFilter("soft_delete");
153
        } catch (\InvalidArgumentException $e) {
154
            $exceptionThrown = true;
155
        }
156
        $this->assertTrue($exceptionThrown);
157
    }
158
159
    /**
160
     * @group DDC-2203
161
     */
162
    public function testEntityManagerIsFilterEnabled()
163
    {
164
        $em = $this->_getEntityManager();
165
        $this->configureFilters($em);
166
167
        // Check for an enabled filter
168
        $em->getFilters()->enable("locale");
169
        $this->assertTrue($em->getFilters()->isEnabled("locale"));
170
171
        // Check for a disabled filter
172
        $em->getFilters()->disable("locale");
173
        $this->assertFalse($em->getFilters()->isEnabled("locale"));
174
175
        // Check a non-existing filter
176
        $this->assertFalse($em->getFilters()->isEnabled("foo_filter"));
177
    }
178
179
    protected function configureFilters($em)
180
    {
181
        // Add filters to the configuration of the EM
182
        $config = $em->getConfiguration();
183
        $config->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter");
184
        $config->addFilter("soft_delete", "\Doctrine\Tests\ORM\Functional\MySoftDeleteFilter");
185
    }
186
187
    protected function getMockConnection()
188
    {
189
        // Setup connection mock
190
        $conn = $this->getMockBuilder(Connection::class)
191
            ->disableOriginalConstructor()
192
            ->getMock();
193
194
        return $conn;
195
    }
196
197
    protected function getMockEntityManager()
198
    {
199
        // Setup connection mock
200
        $em = $this->getMockBuilder(EntityManager::class)
201
            ->disableOriginalConstructor()
202
            ->getMock();
203
204
        return $em;
205
    }
206
207
    protected function addMockFilterCollection($em)
208
    {
209
        $filterCollection = $this->getMockBuilder(FilterCollection::class)
210
            ->disableOriginalConstructor()
211
            ->getMock();
212
213
        $em->expects($this->any())
214
            ->method('getFilters')
215
            ->will($this->returnValue($filterCollection));
216
217
        return $filterCollection;
218
    }
219
220 View Code Duplication
    public function testSQLFilterGetSetParameter()
221
    {
222
        // Setup mock connection
223
        $conn = $this->getMockConnection();
224
        $conn->expects($this->once())
225
            ->method('quote')
226
            ->with($this->equalTo('en'))
227
            ->will($this->returnValue("'en'"));
228
229
        $em = $this->getMockEntityManager();
230
        $em->expects($this->once())
231
            ->method('getConnection')
232
            ->will($this->returnValue($conn));
233
234
        $filterCollection = $this->addMockFilterCollection($em);
235
        $filterCollection
236
            ->expects($this->once())
237
            ->method('setFiltersStateDirty');
238
239
        $filter = new MyLocaleFilter($em);
240
241
        $filter->setParameter('locale', 'en', DBALType::STRING);
242
243
        $this->assertEquals("'en'", $filter->getParameter('locale'));
244
    }
245
246
    /**
247
     * @group DDC-3161
248
     * @group 1054
249
     */
250
    public function testSQLFilterGetConnection()
251
    {
252
        // Setup mock connection
253
        $conn = $this->getMockConnection();
254
255
        $em = $this->getMockEntityManager();
256
        $em->expects($this->once())
257
            ->method('getConnection')
258
            ->will($this->returnValue($conn));
259
260
        $filter = new MyLocaleFilter($em);
261
262
        $reflMethod = new \ReflectionMethod(SQLFilter::class, 'getConnection');
263
        $reflMethod->setAccessible(true);
264
265
        $this->assertSame($conn, $reflMethod->invoke($filter));
266
    }
267
268 View Code Duplication
    public function testSQLFilterSetParameterInfersType()
269
    {
270
        // Setup mock connection
271
        $conn = $this->getMockConnection();
272
        $conn->expects($this->once())
273
            ->method('quote')
274
            ->with($this->equalTo('en'))
275
            ->will($this->returnValue("'en'"));
276
277
        $em = $this->getMockEntityManager();
278
        $em->expects($this->once())
279
            ->method('getConnection')
280
            ->will($this->returnValue($conn));
281
282
        $filterCollection = $this->addMockFilterCollection($em);
283
        $filterCollection
284
            ->expects($this->once())
285
            ->method('setFiltersStateDirty');
286
287
        $filter = new MyLocaleFilter($em);
288
289
        $filter->setParameter('locale', 'en');
290
291
        $this->assertEquals("'en'", $filter->getParameter('locale'));
292
    }
293
294
    public function testSQLFilterAddConstraint()
295
    {
296
        // Set up metadata mock
297
        $targetEntity = $this->getMockBuilder(ClassMetadata::class)
298
            ->disableOriginalConstructor()
299
            ->getMock();
300
301
        $filter = new MySoftDeleteFilter($this->getMockEntityManager());
302
303
        // Test for an entity that gets extra filter data
304
        $targetEntity->name = 'MyEntity\SoftDeleteNewsItem';
305
        $this->assertEquals('t1_.deleted = 0', $filter->addFilterConstraint($targetEntity, 't1_'));
306
307
        // Test for an entity that doesn't get extra filter data
308
        $targetEntity->name = 'MyEntity\NoSoftDeleteNewsItem';
309
        $this->assertEquals('', $filter->addFilterConstraint($targetEntity, 't1_'));
310
311
    }
312
313
    public function testSQLFilterToString()
314
    {
315
        $em = $this->getMockEntityManager();
316
        $filterCollection = $this->addMockFilterCollection($em);
0 ignored issues
show
$filterCollection is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
317
318
        $filter = new MyLocaleFilter($em);
319
        $filter->setParameter('locale', 'en', DBALType::STRING);
320
        $filter->setParameter('foo', 'bar', DBALType::STRING);
321
322
        $filter2 = new MyLocaleFilter($em);
323
        $filter2->setParameter('foo', 'bar', DBALType::STRING);
324
        $filter2->setParameter('locale', 'en', DBALType::STRING);
325
326
        $parameters = [
327
            'foo' => ['value' => 'bar', 'type' => DBALType::STRING],
328
            'locale' => ['value' => 'en', 'type' => DBALType::STRING],
329
        ];
330
331
        $this->assertEquals(serialize($parameters), ''.$filter);
332
        $this->assertEquals(''.$filter, ''.$filter2);
333
    }
334
335
    public function testQueryCache_DependsOnFilters()
336
    {
337
        $cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data");
338
        $cacheDataReflection->setAccessible(true);
339
340
        $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
341
342
        $cache = new ArrayCache();
343
        $query->setQueryCacheDriver($cache);
344
345
        $query->getResult();
346
        $this->assertEquals(1, sizeof($cacheDataReflection->getValue($cache)));
347
348
        $conf = $this->_em->getConfiguration();
349
        $conf->addFilter("locale", "\Doctrine\Tests\ORM\Functional\MyLocaleFilter");
350
        $this->_em->getFilters()->enable("locale");
351
352
        $query->getResult();
353
        $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache)));
354
355
        // Another time doesn't add another cache entry
356
        $query->getResult();
357
        $this->assertEquals(2, sizeof($cacheDataReflection->getValue($cache)));
358
    }
359
360
    public function testQueryGeneration_DependsOnFilters()
361
    {
362
        $query = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a');
363
        $firstSQLQuery = $query->getSQL();
364
365
        $conf = $this->_em->getConfiguration();
366
        $conf->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter");
367
        $this->_em->getFilters()->enable("country")
368
            ->setParameter("country", "en", DBALType::STRING);
369
370
        $this->assertNotEquals($firstSQLQuery, $query->getSQL());
371
    }
372
373
    public function testRepositoryFind()
374
    {
375
        $this->loadFixtureData();
376
377
        $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId));
378
        $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2));
379
380
        $this->useCMSGroupPrefixFilter();
381
        $this->_em->clear();
382
383
        $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId));
384
        $this->assertNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2));
385
    }
386
387
    public function testRepositoryFindAll()
388
    {
389
        $this->loadFixtureData();
390
391
        $this->assertCount(2, $this->_em->getRepository(CmsGroup::class)->findAll());
392
393
        $this->useCMSGroupPrefixFilter();
394
        $this->_em->clear();
395
396
        $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findAll());
397
    }
398
399 View Code Duplication
    public function testRepositoryFindBy()
400
    {
401
        $this->loadFixtureData();
402
403
        $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findBy(
404
            ['id' => $this->groupId2]
405
        ));
406
407
        $this->useCMSGroupPrefixFilter();
408
        $this->_em->clear();
409
410
        $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findBy(
411
            ['id' => $this->groupId2]
412
        ));
413
    }
414
415 View Code Duplication
    public function testRepositoryFindByX()
416
    {
417
        $this->loadFixtureData();
418
419
        $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2));
420
421
        $this->useCMSGroupPrefixFilter();
422
        $this->_em->clear();
423
424
        $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2));
425
    }
426
427 View Code Duplication
    public function testRepositoryFindOneBy()
428
    {
429
        $this->loadFixtureData();
430
431
        $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneBy(
432
            ['id' => $this->groupId2]
433
        ));
434
435
        $this->useCMSGroupPrefixFilter();
436
        $this->_em->clear();
437
438
        $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneBy(
439
            ['id' => $this->groupId2]
440
        ));
441
    }
442
443 View Code Duplication
    public function testRepositoryFindOneByX()
444
    {
445
        $this->loadFixtureData();
446
447
        $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2));
448
449
        $this->useCMSGroupPrefixFilter();
450
        $this->_em->clear();
451
452
        $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2));
453
    }
454
455 View Code Duplication
    public function testToOneFilter()
456
    {
457
        //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
458
        $this->loadFixtureData();
459
460
        $query = $this->_em->createQuery('select ux, ua from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.address ua');
461
462
        // We get two users before enabling the filter
463
        $this->assertEquals(2, count($query->getResult()));
464
465
        $conf = $this->_em->getConfiguration();
466
        $conf->addFilter("country", "\Doctrine\Tests\ORM\Functional\CMSCountryFilter");
467
        $this->_em->getFilters()->enable("country")->setParameter("country", "Germany", DBALType::STRING);
468
469
        // We get one user after enabling the filter
470
        $this->assertEquals(1, count($query->getResult()));
471
    }
472
473 View Code Duplication
    public function testManyToManyFilter()
474
    {
475
        $this->loadFixtureData();
476
        $query = $this->_em->createQuery('select ux, ug from Doctrine\Tests\Models\CMS\CmsUser ux JOIN ux.groups ug');
477
478
        // We get two users before enabling the filter
479
        $this->assertEquals(2, count($query->getResult()));
480
481
        $conf = $this->_em->getConfiguration();
482
        $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter");
483
        $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING);
484
485
        // We get one user after enabling the filter
486
        $this->assertEquals(1, count($query->getResult()));
487
488
    }
489
490 View Code Duplication
    public function testWhereFilter()
491
    {
492
        $this->loadFixtureData();
493
        $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1');
494
495
        // We get two users before enabling the filter
496
        $this->assertEquals(2, count($query->getResult()));
497
498
        $conf = $this->_em->getConfiguration();
499
        $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter");
500
        $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING);
501
502
        // We get one user after enabling the filter
503
        $this->assertEquals(1, count($query->getResult()));
504
    }
505
506 View Code Duplication
    public function testWhereOrFilter()
507
    {
508
        $this->loadFixtureData();
509
        $query = $this->_em->createQuery('select ug from Doctrine\Tests\Models\CMS\CmsGroup ug WHERE 1=1 OR 1=1');
510
511
        // We get two users before enabling the filter
512
        $this->assertEquals(2, count($query->getResult()));
513
514
        $conf = $this->_em->getConfiguration();
515
        $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter");
516
        $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "bar_%", DBALType::STRING);
517
518
        // We get one user after enabling the filter
519
        $this->assertEquals(1, count($query->getResult()));
520
    }
521
522
523
    private function loadLazyFixtureData()
524
    {
525
        $class = $this->_em->getClassMetadata(CmsUser::class);
526
        $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
527
        $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
528
        $this->loadFixtureData();
529
    }
530
531
    private function useCMSArticleTopicFilter()
532
    {
533
        $conf = $this->_em->getConfiguration();
534
        $conf->addFilter("article_topic", "\Doctrine\Tests\ORM\Functional\CMSArticleTopicFilter");
535
        $this->_em->getFilters()->enable("article_topic")->setParameter("topic", "Test1", DBALType::STRING);
536
    }
537
538 View Code Duplication
    public function testOneToMany_ExtraLazyCountWithFilter()
539
    {
540
        $this->loadLazyFixtureData();
541
        $user = $this->_em->find(CmsUser::class, $this->userId);
542
543
        $this->assertFalse($user->articles->isInitialized());
544
        $this->assertEquals(2, count($user->articles));
545
546
        $this->useCMSArticleTopicFilter();
547
548
        $this->assertEquals(1, count($user->articles));
549
    }
550
551 View Code Duplication
    public function testOneToMany_ExtraLazyContainsWithFilter()
552
    {
553
        $this->loadLazyFixtureData();
554
        $user = $this->_em->find(CmsUser::class, $this->userId);
555
        $filteredArticle = $this->_em->find(CmsArticle::class, $this->articleId2);
556
557
        $this->assertFalse($user->articles->isInitialized());
558
        $this->assertTrue($user->articles->contains($filteredArticle));
559
560
        $this->useCMSArticleTopicFilter();
561
562
        $this->assertFalse($user->articles->contains($filteredArticle));
563
    }
564
565 View Code Duplication
    public function testOneToMany_ExtraLazySliceWithFilter()
566
    {
567
        $this->loadLazyFixtureData();
568
        $user = $this->_em->find(CmsUser::class, $this->userId);
569
570
        $this->assertFalse($user->articles->isInitialized());
571
        $this->assertEquals(2, count($user->articles->slice(0,10)));
572
573
        $this->useCMSArticleTopicFilter();
574
575
        $this->assertEquals(1, count($user->articles->slice(0,10)));
576
    }
577
578
    private function useCMSGroupPrefixFilter()
579
    {
580
        $conf = $this->_em->getConfiguration();
581
        $conf->addFilter("group_prefix", "\Doctrine\Tests\ORM\Functional\CMSGroupPrefixFilter");
582
        $this->_em->getFilters()->enable("group_prefix")->setParameter("prefix", "foo%", DBALType::STRING);
583
    }
584
585 View Code Duplication
    public function testManyToMany_ExtraLazyCountWithFilter()
586
    {
587
        $this->loadLazyFixtureData();
588
589
        $user = $this->_em->find(CmsUser::class, $this->userId2);
590
591
        $this->assertFalse($user->groups->isInitialized());
592
        $this->assertEquals(2, count($user->groups));
593
594
        $this->useCMSGroupPrefixFilter();
595
596
        $this->assertEquals(1, count($user->groups));
597
    }
598
599 View Code Duplication
    public function testManyToMany_ExtraLazyContainsWithFilter()
600
    {
601
        $this->loadLazyFixtureData();
602
        $user = $this->_em->find(CmsUser::class, $this->userId2);
603
        $filteredArticle = $this->_em->find(CmsGroup::class, $this->groupId2);
604
605
        $this->assertFalse($user->groups->isInitialized());
606
        $this->assertTrue($user->groups->contains($filteredArticle));
607
608
        $this->useCMSGroupPrefixFilter();
609
610
        $this->assertFalse($user->groups->contains($filteredArticle));
611
    }
612
613 View Code Duplication
    public function testManyToMany_ExtraLazySliceWithFilter()
614
    {
615
        $this->loadLazyFixtureData();
616
        $user = $this->_em->find(CmsUser::class, $this->userId2);
617
618
        $this->assertFalse($user->groups->isInitialized());
619
        $this->assertEquals(2, count($user->groups->slice(0,10)));
620
621
        $this->useCMSGroupPrefixFilter();
622
623
        $this->assertEquals(1, count($user->groups->slice(0,10)));
624
    }
625
626
    private function loadFixtureData()
627
    {
628
        $user = new CmsUser;
629
        $user->name = 'Roman';
630
        $user->username = 'romanb';
631
        $user->status = 'developer';
632
633
        $address = new CmsAddress;
634
        $address->country = 'Germany';
635
        $address->city = 'Berlin';
636
        $address->zip = '12345';
637
638
        $user->address = $address; // inverse side
639
        $address->user = $user; // owning side!
640
641
        $group = new CmsGroup;
642
        $group->name = 'foo_group';
643
        $user->addGroup($group);
644
645
        $article1 = new CmsArticle;
646
        $article1->topic = "Test1";
647
        $article1->text = "Test";
648
        $article1->setAuthor($user);
649
650
        $article2 = new CmsArticle;
651
        $article2->topic = "Test2";
652
        $article2->text = "Test";
653
        $article2->setAuthor($user);
654
655
        $this->_em->persist($article1);
656
        $this->_em->persist($article2);
657
658
        $this->_em->persist($user);
659
660
        $user2 = new CmsUser;
661
        $user2->name = 'Guilherme';
662
        $user2->username = 'gblanco';
663
        $user2->status = 'developer';
664
665
        $address2 = new CmsAddress;
666
        $address2->country = 'France';
667
        $address2->city = 'Paris';
668
        $address2->zip = '12345';
669
670
        $user->address = $address2; // inverse side
671
        $address2->user = $user2; // owning side!
672
673
        $user2->addGroup($group);
674
        $group2 = new CmsGroup;
675
        $group2->name = 'bar_group';
676
        $user2->addGroup($group2);
677
678
        $this->_em->persist($user2);
679
        $this->_em->flush();
680
        $this->_em->clear();
681
682
        $this->userId = $user->getId();
683
        $this->userId2 = $user2->getId();
684
        $this->articleId = $article1->id;
685
        $this->articleId2 = $article2->id;
686
        $this->groupId = $group->id;
687
        $this->groupId2 = $group2->id;
688
    }
689
690 View Code Duplication
    public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEntity()
691
    {
692
        $this->loadCompanyJoinedSubclassFixtureData();
693
        // Persister
694
        $this->assertEquals(2, count($this->_em->getRepository(CompanyManager::class)->findAll()));
695
        // SQLWalker
696
        $this->assertEquals(2, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult()));
697
698
        // Enable the filter
699
        $this->usePersonNameFilter('Guilh%');
700
701
        $managers = $this->_em->getRepository(CompanyManager::class)->findAll();
702
        $this->assertEquals(1, count($managers));
703
        $this->assertEquals("Guilherme", $managers[0]->getName());
704
705
        $this->assertEquals(1, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult()));
706
    }
707
708 View Code Duplication
    public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingRootEntity()
709
    {
710
        $this->loadCompanyJoinedSubclassFixtureData();
711
        $this->assertEquals(3, count($this->_em->getRepository(CompanyPerson::class)->findAll()));
712
        $this->assertEquals(3, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult()));
713
714
        // Enable the filter
715
        $this->usePersonNameFilter('Guilh%');
716
717
        $persons = $this->_em->getRepository(CompanyPerson::class)->findAll();
718
        $this->assertEquals(1, count($persons));
719
        $this->assertEquals("Guilherme", $persons[0]->getName());
720
721
        $this->assertEquals(1, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult()));
722
    }
723
724
    private function loadCompanyJoinedSubclassFixtureData()
725
    {
726
        $manager = new CompanyManager;
727
        $manager->setName('Roman');
728
        $manager->setTitle('testlead');
729
        $manager->setSalary(42);
730
        $manager->setDepartment('persisters');
731
732
        $manager2 = new CompanyManager;
733
        $manager2->setName('Guilherme');
734
        $manager2->setTitle('devlead');
735
        $manager2->setSalary(42);
736
        $manager2->setDepartment('parsers');
737
738
        $person = new CompanyPerson;
739
        $person->setName('Benjamin');
740
741
        $this->_em->persist($manager);
742
        $this->_em->persist($manager2);
743
        $this->_em->persist($person);
744
        $this->_em->flush();
745
        $this->_em->clear();
746
    }
747
748 View Code Duplication
    public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubEntity()
749
    {
750
        $this->loadCompanySingleTableInheritanceFixtureData();
751
        // Persister
752
        $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll()));
753
        // SQLWalker
754
        $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult()));
755
756
        // Enable the filter
757
        $conf = $this->_em->getConfiguration();
758
        $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter");
759
        $this->_em->getFilters()
760
            ->enable("completed_contract")
761
            ->setParameter("completed", true, DBALType::BOOLEAN);
762
763
        $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll()));
764
        $this->assertEquals(1, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult()));
765
    }
766
767 View Code Duplication
    public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRootEntity()
768
    {
769
        $this->loadCompanySingleTableInheritanceFixtureData();
770
        $this->assertEquals(4, count($this->_em->getRepository(CompanyFlexContract::class)->findAll()));
771
        $this->assertEquals(4, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult()));
772
773
        // Enable the filter
774
        $conf = $this->_em->getConfiguration();
775
        $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter");
776
        $this->_em->getFilters()
777
            ->enable("completed_contract")
778
            ->setParameter("completed", true, DBALType::BOOLEAN);
779
780
        $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexContract::class)->findAll()));
781
        $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult()));
782
    }
783
784
    private function loadCompanySingleTableInheritanceFixtureData()
785
    {
786
        $contract1 = new CompanyFlexUltraContract;
787
        $contract2 = new CompanyFlexUltraContract;
788
        $contract2->markCompleted();
789
790
        $contract3 = new CompanyFlexContract;
791
        $contract4 = new CompanyFlexContract;
792
        $contract4->markCompleted();
793
794
        $manager = new CompanyManager;
795
        $manager->setName('Alexander');
796
        $manager->setSalary(42);
797
        $manager->setDepartment('Doctrine');
798
        $manager->setTitle('Filterer');
799
800
        $manager2 = new CompanyManager;
801
        $manager2->setName('Benjamin');
802
        $manager2->setSalary(1337);
803
        $manager2->setDepartment('Doctrine');
804
        $manager2->setTitle('Maintainer');
805
806
        $contract1->addManager($manager);
807
        $contract2->addManager($manager);
808
        $contract3->addManager($manager);
809
        $contract4->addManager($manager);
810
811
        $contract1->addManager($manager2);
812
813
        $contract1->setSalesPerson($manager);
814
        $contract2->setSalesPerson($manager);
815
816
        $this->_em->persist($manager);
817
        $this->_em->persist($manager2);
818
        $this->_em->persist($contract1);
819
        $this->_em->persist($contract2);
820
        $this->_em->persist($contract3);
821
        $this->_em->persist($contract4);
822
        $this->_em->flush();
823
        $this->_em->clear();
824
825
        $this->managerId = $manager->getId();
826
        $this->managerId2 = $manager2->getId();
827
        $this->contractId1 = $contract1->getId();
828
        $this->contractId2 = $contract2->getId();
829
    }
830
831 View Code Duplication
    private function useCompletedContractFilter()
832
    {
833
        $conf = $this->_em->getConfiguration();
834
        $conf->addFilter("completed_contract", "\Doctrine\Tests\ORM\Functional\CompletedContractFilter");
835
        $this->_em->getFilters()
836
            ->enable("completed_contract")
837
            ->setParameter("completed", true, DBALType::BOOLEAN);
838
    }
839
840 View Code Duplication
    public function testManyToMany_ExtraLazyCountWithFilterOnSTI()
841
    {
842
        $this->loadCompanySingleTableInheritanceFixtureData();
843
844
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
845
846
        $this->assertFalse($manager->managedContracts->isInitialized());
847
        $this->assertEquals(4, count($manager->managedContracts));
848
849
        // Enable the filter
850
        $this->useCompletedContractFilter();
851
852
        $this->assertFalse($manager->managedContracts->isInitialized());
853
        $this->assertEquals(2, count($manager->managedContracts));
854
    }
855
856 View Code Duplication
    public function testManyToMany_ExtraLazyContainsWithFilterOnSTI()
857
    {
858
        $this->loadCompanySingleTableInheritanceFixtureData();
859
860
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
861
        $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1);
862
        $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2);
863
864
        $this->assertFalse($manager->managedContracts->isInitialized());
865
        $this->assertTrue($manager->managedContracts->contains($contract1));
866
        $this->assertTrue($manager->managedContracts->contains($contract2));
867
868
        // Enable the filter
869
        $this->useCompletedContractFilter();
870
871
        $this->assertFalse($manager->managedContracts->isInitialized());
872
        $this->assertFalse($manager->managedContracts->contains($contract1));
873
        $this->assertTrue($manager->managedContracts->contains($contract2));
874
    }
875
876 View Code Duplication
    public function testManyToMany_ExtraLazySliceWithFilterOnSTI()
877
    {
878
        $this->loadCompanySingleTableInheritanceFixtureData();
879
880
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
881
882
        $this->assertFalse($manager->managedContracts->isInitialized());
883
        $this->assertEquals(4, count($manager->managedContracts->slice(0, 10)));
884
885
        // Enable the filter
886
        $this->useCompletedContractFilter();
887
888
        $this->assertFalse($manager->managedContracts->isInitialized());
889
        $this->assertEquals(2, count($manager->managedContracts->slice(0, 10)));
890
    }
891
892 View Code Duplication
    private function usePersonNameFilter($name)
893
    {
894
        // Enable the filter
895
        $conf = $this->_em->getConfiguration();
896
        $conf->addFilter("person_name", "\Doctrine\Tests\ORM\Functional\CompanyPersonNameFilter");
897
        $this->_em->getFilters()
898
            ->enable("person_name")
899
            ->setParameter("name", $name, DBALType::STRING);
900
    }
901
902 View Code Duplication
    public function testManyToMany_ExtraLazyCountWithFilterOnCTI()
903
    {
904
        $this->loadCompanySingleTableInheritanceFixtureData();
905
906
        $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1);
907
908
        $this->assertFalse($contract->managers->isInitialized());
909
        $this->assertEquals(2, count($contract->managers));
910
911
        // Enable the filter
912
        $this->usePersonNameFilter('Benjamin');
913
914
        $this->assertFalse($contract->managers->isInitialized());
915
        $this->assertEquals(1, count($contract->managers));
916
    }
917
918 View Code Duplication
    public function testManyToMany_ExtraLazyContainsWithFilterOnCTI()
919
    {
920
        $this->loadCompanySingleTableInheritanceFixtureData();
921
922
        $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1);
923
        $manager1 = $this->_em->find(CompanyManager::class, $this->managerId);
924
        $manager2 = $this->_em->find(CompanyManager::class, $this->managerId2);
925
926
        $this->assertFalse($contract->managers->isInitialized());
927
        $this->assertTrue($contract->managers->contains($manager1));
928
        $this->assertTrue($contract->managers->contains($manager2));
929
930
        // Enable the filter
931
        $this->usePersonNameFilter('Benjamin');
932
933
        $this->assertFalse($contract->managers->isInitialized());
934
        $this->assertFalse($contract->managers->contains($manager1));
935
        $this->assertTrue($contract->managers->contains($manager2));
936
    }
937
938 View Code Duplication
    public function testManyToMany_ExtraLazySliceWithFilterOnCTI()
939
    {
940
        $this->loadCompanySingleTableInheritanceFixtureData();
941
942
        $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1);
943
944
        $this->assertFalse($contract->managers->isInitialized());
945
        $this->assertEquals(2, count($contract->managers->slice(0, 10)));
946
947
        // Enable the filter
948
        $this->usePersonNameFilter('Benjamin');
949
950
        $this->assertFalse($contract->managers->isInitialized());
951
        $this->assertEquals(1, count($contract->managers->slice(0, 10)));
952
    }
953
954 View Code Duplication
    public function testOneToMany_ExtraLazyCountWithFilterOnSTI()
955
    {
956
        $this->loadCompanySingleTableInheritanceFixtureData();
957
958
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
959
960
        $this->assertFalse($manager->soldContracts->isInitialized());
961
        $this->assertEquals(2, count($manager->soldContracts));
962
963
        // Enable the filter
964
        $this->useCompletedContractFilter();
965
966
        $this->assertFalse($manager->soldContracts->isInitialized());
967
        $this->assertEquals(1, count($manager->soldContracts));
968
    }
969
970 View Code Duplication
    public function testOneToMany_ExtraLazyContainsWithFilterOnSTI()
971
    {
972
        $this->loadCompanySingleTableInheritanceFixtureData();
973
974
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
975
        $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1);
976
        $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2);
977
978
        $this->assertFalse($manager->soldContracts->isInitialized());
979
        $this->assertTrue($manager->soldContracts->contains($contract1));
980
        $this->assertTrue($manager->soldContracts->contains($contract2));
981
982
        // Enable the filter
983
        $this->useCompletedContractFilter();
984
985
        $this->assertFalse($manager->soldContracts->isInitialized());
986
        $this->assertFalse($manager->soldContracts->contains($contract1));
987
        $this->assertTrue($manager->soldContracts->contains($contract2));
988
    }
989
990 View Code Duplication
    public function testOneToMany_ExtraLazySliceWithFilterOnSTI()
991
    {
992
993
        $this->loadCompanySingleTableInheritanceFixtureData();
994
995
        $manager = $this->_em->find(CompanyManager::class, $this->managerId);
996
997
        $this->assertFalse($manager->soldContracts->isInitialized());
998
        $this->assertEquals(2, count($manager->soldContracts->slice(0, 10)));
999
1000
        // Enable the filter
1001
        $this->useCompletedContractFilter();
1002
1003
        $this->assertFalse($manager->soldContracts->isInitialized());
1004
        $this->assertEquals(1, count($manager->soldContracts->slice(0, 10)));
1005
    }
1006
    private function loadCompanyOrganizationEventJoinedSubclassFixtureData()
1007
    {
1008
        $organization = new CompanyOrganization;
1009
1010
        $event1 = new CompanyAuction;
1011
        $event1->setData('foo');
1012
1013
        $event2 = new CompanyAuction;
1014
        $event2->setData('bar');
1015
1016
        $organization->addEvent($event1);
1017
        $organization->addEvent($event2);
1018
1019
        $this->_em->persist($organization);
1020
        $this->_em->flush();
1021
        $this->_em->clear();
1022
1023
        $this->organizationId = $organization->getId();
1024
        $this->eventId1 = $event1->getId();
1025
        $this->eventId2 = $event2->getId();
1026
    }
1027
1028
    private function useCompanyEventIdFilter()
1029
    {
1030
        // Enable the filter
1031
        $conf = $this->_em->getConfiguration();
1032
        $conf->addFilter("event_id", CompanyEventFilter::class);
1033
        $this->_em->getFilters()
1034
            ->enable("event_id")
1035
            ->setParameter("id", $this->eventId2);
1036
    }
1037
1038
1039
    public function testOneToMany_ExtraLazyCountWithFilterOnCTI()
1040
    {
1041
        $this->loadCompanyOrganizationEventJoinedSubclassFixtureData();
1042
1043
        $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId);
1044
1045
        $this->assertFalse($organization->events->isInitialized());
1046
        $this->assertEquals(2, count($organization->events));
1047
1048
        // Enable the filter
1049
        $this->useCompanyEventIdFilter();
1050
1051
        $this->assertFalse($organization->events->isInitialized());
1052
        $this->assertEquals(1, count($organization->events));
1053
    }
1054
1055
    public function testOneToMany_ExtraLazyContainsWithFilterOnCTI()
1056
    {
1057
        $this->loadCompanyOrganizationEventJoinedSubclassFixtureData();
1058
1059
        $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId);
1060
1061
        $event1 = $this->_em->find(CompanyEvent::class, $this->eventId1);
1062
        $event2 = $this->_em->find(CompanyEvent::class, $this->eventId2);
1063
1064
        $this->assertFalse($organization->events->isInitialized());
1065
        $this->assertTrue($organization->events->contains($event1));
1066
        $this->assertTrue($organization->events->contains($event2));
1067
1068
        // Enable the filter
1069
        $this->useCompanyEventIdFilter();
1070
1071
        $this->assertFalse($organization->events->isInitialized());
1072
        $this->assertFalse($organization->events->contains($event1));
1073
        $this->assertTrue($organization->events->contains($event2));
1074
    }
1075
1076 View Code Duplication
    public function testOneToMany_ExtraLazySliceWithFilterOnCTI()
1077
    {
1078
        $this->loadCompanyOrganizationEventJoinedSubclassFixtureData();
1079
1080
        $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId);
1081
1082
        $this->assertFalse($organization->events->isInitialized());
1083
        $this->assertEquals(2, count($organization->events->slice(0, 10)));
1084
1085
        // Enable the filter
1086
        $this->useCompanyEventIdFilter();
1087
1088
        $this->assertFalse($organization->events->isInitialized());
1089
        $this->assertEquals(1, count($organization->events->slice(0, 10)));
1090
    }
1091
}
1092
1093
class MySoftDeleteFilter extends SQLFilter
1094
{
1095
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
1096
    {
1097
        if ($targetEntity->name != "MyEntity\SoftDeleteNewsItem") {
1098
            return "";
1099
        }
1100
1101
        return $targetTableAlias.'.deleted = 0';
1102
    }
1103
}
1104
1105
class MyLocaleFilter extends SQLFilter
1106
{
1107
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
1108
    {
1109
        if (!in_array("LocaleAware", $targetEntity->reflClass->getInterfaceNames())) {
1110
            return "";
1111
        }
1112
1113
        return $targetTableAlias.'.locale = ' . $this->getParameter('locale'); // getParam uses connection to quote the value.
1114
    }
1115
}
1116
1117
class CMSCountryFilter extends SQLFilter
1118
{
1119
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
1120
    {
1121
        if ($targetEntity->name != CmsAddress::class) {
1122
            return "";
1123
        }
1124
1125
        return $targetTableAlias.'.country = ' . $this->getParameter('country'); // getParam uses connection to quote the value.
1126
    }
1127
}
1128
1129
class CMSGroupPrefixFilter extends SQLFilter
1130
{
1131
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
1132
    {
1133
        if ($targetEntity->name != CmsGroup::class) {
1134
            return "";
1135
        }
1136
1137
        return $targetTableAlias.'.name LIKE ' . $this->getParameter('prefix'); // getParam uses connection to quote the value.
1138
    }
1139
}
1140
1141
class CMSArticleTopicFilter extends SQLFilter
1142
{
1143
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
1144
    {
1145
        if ($targetEntity->name != CmsArticle::class) {
1146
            return "";
1147
        }
1148
1149
        return $targetTableAlias.'.topic = ' . $this->getParameter('topic'); // getParam uses connection to quote the value.
1150
    }
1151
}
1152
1153 View Code Duplication
class CompanyPersonNameFilter extends SQLFilter
1154
{
1155
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '')
1156
    {
1157
        if ($targetEntity->name != CompanyPerson::class) {
1158
            return "";
1159
        }
1160
1161
        return $targetTableAlias.'.name LIKE ' . $this->getParameter('name');
1162
    }
1163
}
1164
1165 View Code Duplication
class CompletedContractFilter extends SQLFilter
1166
{
1167
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '')
1168
    {
1169
        if ($targetEntity->name != CompanyContract::class) {
1170
            return "";
1171
        }
1172
1173
        return $targetTableAlias.'.completed = ' . $this->getParameter('completed');
1174
    }
1175
}
1176
1177 View Code Duplication
class CompanyEventFilter extends SQLFilter
1178
{
1179
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '')
1180
    {
1181
        if ($targetEntity->name != CompanyEvent::class) {
1182
            return "";
1183
        }
1184
1185
        return $targetTableAlias.'.id = ' . $this->getParameter('id');
1186
    }
1187
}
1188