Passed
Pull Request — master (#68)
by David
03:59 queued 44s
created

TDBMServiceTest::testFindObjects()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 0
1
<?php
2
3
/*
4
 Copyright (C) 2006-2014 David Négrier - THE CODING MACHINE
5
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
10
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
GNU General Public License for more details.
15
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
*/
20
21
namespace TheCodingMachine\TDBM;
22
23
use Psr\Log\LogLevel;
24
use Wa72\SimpleLogger\ArrayLogger;
25
26
class TDBMServiceTest extends TDBMAbstractServiceTest
27
{
28
    public function testGetLinkBetweenInheritedTables()
29
    {
30
        $this->assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['contact', 'users']));
31
        $this->assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['users', 'contact']));
32
        $this->assertEquals(['contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['person', 'contact']));
33
        $this->assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['users']));
34
        $this->assertEquals(['person'], $this->tdbmService->_getLinkBetweenInheritedTables(['person']));
35
    }
36
37
    public function testGetRelatedTablesByInheritance()
38
    {
39
        $contactRelatedTables = $this->tdbmService->_getRelatedTablesByInheritance('contact');
40
        $this->assertCount(3, $contactRelatedTables);
41
        $this->assertContains('users', $contactRelatedTables);
42
        $this->assertContains('contact', $contactRelatedTables);
43
        $this->assertContains('person', $contactRelatedTables);
44
        $this->assertEquals(['person', 'contact', 'users'], $this->tdbmService->_getRelatedTablesByInheritance('users'));
45
        $this->assertEquals(['person', 'contact', 'users'], $this->tdbmService->_getRelatedTablesByInheritance('person'));
46
    }
47
48
    /**
49
     * @expectedException \TheCodingMachine\TDBM\TDBMException
50
     *
51
     * @throws TDBMException
52
     */
53
    public function testGetPrimaryKeysFromIndexedPrimaryKeysException()
54
    {
55
        $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys('users', [5, 4]);
56
    }
57
58
    /**
59
     * @expectedException \TheCodingMachine\TDBM\TDBMException
60
     *
61
     * @throws TDBMException
62
     */
63
    public function testGetLinkBetweenInheritedTablesExceptions()
64
    {
65
        $this->tdbmService->_getLinkBetweenInheritedTables(['contact', 'country']);
66
    }
67
68
    public function testHashPrimaryKey()
69
    {
70
        $reflection = new \ReflectionClass(get_class($this->tdbmService));
71
        $method = $reflection->getMethod('getObjectHash');
72
        $method->setAccessible(true);
73
74
        $result = $method->invokeArgs($this->tdbmService, [
75
            ['id' => 42],
76
        ]);
77
        $this->assertEquals(42, $result);
78
79
        // Check that multiple primary keys are insensitive to column order
80
        $result1 = $method->invokeArgs($this->tdbmService, [
81
            ['id1' => 42, 'id2' => 24],
82
        ]);
83
        $result2 = $method->invokeArgs($this->tdbmService, [
84
            ['id2' => 24, 'id1' => 42],
85
        ]);
86
        $this->assertEquals($result1, $result2);
87
    }
88
89
    public function testInsertAndUpdateAndDelete()
90
    {
91
        $object = new TDBMObject('users');
92
        $object->setProperty('login', 'john.doe');
93
        $object->setProperty('country_id', 3);
94
        $object->setProperty('name', 'John Doe', 'person');
95
        $object->setProperty('email', '[email protected]', 'contact');
96
97
        $this->tdbmService->save($object);
98
99
        $this->assertNotEmpty($object->getProperty('id', 'person'));
100
        $this->assertNotEmpty($object->getProperty('id', 'users'));
101
        $this->assertEquals($object->getProperty('id', 'person'), $object->getProperty('id', 'users'));
102
103
        $object->setProperty('country_id', 2, 'users');
104
105
        $this->tdbmService->save($object);
106
107
        $this->tdbmService->delete($object);
108
    }
109
110
    public function testInsertMultipleDataAtOnceInInheritance()
111
    {
112
        $object = new TDBMObject();
113
        $object->setProperty('login', 'jane.doe', 'users');
114
        $object->setProperty('name', 'Jane Doe', 'person');
115
        $object->setProperty('country_id', 1, 'users');
116
        $object->setProperty('email', '[email protected]', 'contact');
117
118
        $this->tdbmService->save($object);
119
120
        $this->assertNotEmpty($object->getProperty('id', 'person'));
121
        $this->assertNotEmpty($object->getProperty('id', 'users'));
122
        $this->assertEquals($object->getProperty('id', 'person'), $object->getProperty('id', 'users'));
123
    }
124
125
    public function testCompleteSave()
126
    {
127
        $beans = $this->tdbmService->findObjects('users', 'users.login = :login', ['login' => 'jane.doe'], null, [], null, TDBMObject::class);
128
        $jane = $beans[0];
129
        $jane->setProperty('country_id', 2, 'users');
130
131
        $this->tdbmService->completeSave();
132
    }
133
134
    public function testCompleteSave2()
135
    {
136
        $beans = $this->tdbmService->findObjects('users', 'users.login = :login', ['login' => 'jane.doe'], null, [], null, TDBMObject::class);
137
        $jane = $beans[0];
138
139
        $this->assertEquals(2, $jane->getProperty('country_id', 'users'));
140
    }
141
142
    public function testUpdatePrimaryKey()
143
    {
144
        $object = new TDBMObject('rights');
145
        $object->setProperty('label', 'CAN_EDIT_BOUK');
146
147
        $this->tdbmService->save($object);
148
149
        $object->setProperty('label', 'CAN_EDIT_BOOK');
150
151
        $this->tdbmService->save($object);
152
    }
153
154
    /**
155
     * @expectedException \TheCodingMachine\TDBM\TDBMInvalidOperationException
156
     *
157
     * @throws TDBMInvalidOperationException
158
     */
159
    public function testCannotDeleteDetachedObjects()
160
    {
161
        $object = new TDBMObject('rights');
162
        $object->setProperty('label', 'CAN_DELETE');
163
164
        $this->tdbmService->delete($object);
165
    }
166
167
    public function testDeleteNewObject()
168
    {
169
        $object = new TDBMObject('rights');
170
        $object->setProperty('label', 'CAN_DELETE');
171
172
        $this->tdbmService->attach($object);
173
174
        $this->tdbmService->delete($object);
175
176
        $exceptionRaised = false;
177
        try {
178
            $this->tdbmService->save($object);
179
        } catch (TDBMInvalidOperationException $e) {
180
            $exceptionRaised = true;
181
        }
182
        $this->assertTrue($exceptionRaised);
183
    }
184
185
    public function testDeleteLoadedObject()
186
    {
187
        $object = new TDBMObject('rights');
188
        $object->setProperty('label', 'CAN_DELETE');
189
190
        $this->tdbmService->save($object);
191
192
        $object->setProperty('label', 'CAN_DELETE2');
193
194
        $this->tdbmService->delete($object);
195
196
        // Try to delete a deleted object (this should do nothing)
197
        $this->tdbmService->delete($object);
198
    }
199
200
    public function testFindObjects()
201
    {
202
        /*$magicQuery = new MagicQuery($this->tdbmService->getConnection());
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
203
        $result = $magicQuery->parse("SELECT DISTINCT users.id, users.login FROM users");
204
        var_dump($result);*/
205
206
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
207
        $beans2 = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
208
209
        foreach ($beans as $bean) {
210
            $bean1 = $bean;
211
            break;
212
        }
213
214
        foreach ($beans2 as $bean) {
215
            $bean2 = $bean;
216
            break;
217
        }
218
219
        $this->assertTrue($bean1 === $bean2);
220
        $this->assertEquals(5, $beans->count());
221
        $this->assertEquals(1, $beans2->count());
222
223
        //$this->assertTrue($beans[0] === $beans2[0]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
224
        //var_dump($beans);
225
    }
226
227
    public function testRawSqlFilterCountriesByUserCount()
228
    {
229
        $this->onlyMySql();
230
231
        $sql = <<<SQL
232
SELECT country.*, GROUP_CONCAT(users.id) AS ids
233
FROM country
234
JOIN users ON country.id= users.country_id
235
GROUP BY country.id
236
HAVING COUNT(users.id) > 1;
237
SQL;
238
        /** @var Test\Dao\Bean\CountryBean[]|\Porpaginas\Result $beans */
239
        $beans = $this->tdbmService->findObjectsFromRawSql('country', $sql, [], null, Test\Dao\Bean\CountryBean::class);
240
241
        $count = 0;
242
        foreach ($beans as $country) {
243
            $this->assertGreaterThan(1, count($country->getUsers()));
244
            $count++;
245
        }
246
        $this->assertEquals($count, $beans->count());
247
    }
248
249
    public function testRawSqlOrderCountriesByUserCount()
250
    {
251
        $this->onlyMySql();
252
253
        $sql = <<<SQL
254
SELECT country.*, GROUP_CONCAT(users.id) AS ids
255
FROM country
256
JOIN users ON country.id= users.country_id
257
GROUP BY country.id
258
ORDER BY COUNT(users.id);
259
SQL;
260
261
        /** @var Test\Dao\Bean\CountryBean[]|\Porpaginas\Result $beans */
262
        $beans = $this->tdbmService->findObjectsFromRawSql('country', $sql, [], null, Test\Dao\Bean\CountryBean::class);
263
264
        $count = 0;
265
        foreach ($beans as $country) {
266
            $count++;
267
        }
268
        $this->assertEquals($count, $beans->count());
269
270
        for ($i = 1; $i < count($beans); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
271
            $this->assertLessThanOrEqual(count($beans[$i]->getUsers()), count($beans[$i - 1]->getUsers()));
272
        }
273
    }
274
275
    public function testRawSqlOrderUsersByCustomRoleOrder()
276
    {
277
        $this->onlyMySql();
278
279
        $sql = <<<SQL
280
SELECT `person`.*, `contact`.*, `users`.*
281
FROM `contact`
282
JOIN `users` ON `users`.`id` = `contact`.`id`
283
JOIN `person` ON `person`.`id` = `users`.`id`
284
JOIN `users_roles` ON users.id = users_roles.user_id
285
JOIN `roles` ON roles.id = users_roles.role_id
286
GROUP BY users.id
287
ORDER BY MAX(IF(roles.name = 'Admins', 3, IF(roles.name = 'Writers', 2, IF(roles.name = 'Singers', 1, 0)))) DESC
288
SQL;
289
290
        /** @var Test\Dao\Bean\UserBean[]|\Porpaginas\Result $beans */
291
        $beans = $this->tdbmService->findObjectsFromRawSql('contact', $sql, [], null, Test\Dao\Bean\UserBean::class);
292
293
        function getCustomOrder(Test\Dao\Bean\UserBean $contact)
294
        {
295
            $max = 0;
296
            foreach ($contact->getRoles() as $role) {
297
                $max = max($max, [
298
                    'Admins' => 3,
299
                    'Writers' => 2,
300
                    'Singers' => 1,
301
                ][$role->getName()]);
302
            }
303
            return $max;
304
        }
305
306
        $this->assertCount(4, $beans);
307
308
        for ($i = 1; $i < count($beans); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
309
            $this->assertGreaterThanOrEqual(getCustomOrder($beans[$i]), getCustomOrder($beans[$i - 1]), 'Beans order does not comply with expected result.');
310
        }
311
    }
312
313
    public function testArrayAccess()
314
    {
315
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
316
317
        $this->assertTrue(isset($beans[0]));
318
        $this->assertFalse(isset($beans[42]));
319
        $this->assertEquals(1, $beans[0]->getProperty('id', 'person'));
320
321
        $result1 = [];
322
        foreach ($beans as $bean) {
323
            $result1[] = $bean;
324
        }
325
326
        $result2 = [];
327
        foreach ($beans as $bean) {
328
            $result2[] = $bean;
329
        }
330
331
        $this->assertEquals($result1, $result2);
332
        $this->assertTrue($result1[0] === $result2[0]);
333
    }
334
335
    /**
336
     * @expectedException \TheCodingMachine\TDBM\TDBMInvalidOffsetException
337
     *
338
     * @throws TDBMInvalidOffsetException
339
     */
340
    public function testArrayAccessException()
341
    {
342
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
343
344
        $beans[-1];
345
    }
346
347
    /**
348
     * @expectedException \TheCodingMachine\TDBM\TDBMInvalidOffsetException
349
     *
350
     * @throws TDBMInvalidOffsetException
351
     */
352
    public function testArrayAccessException2()
353
    {
354
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
355
356
        $beans['foo'];
357
    }
358
359
    /**
360
     * @expectedException \TheCodingMachine\TDBM\TDBMException
361
     *
362
     * @throws TDBMException
363
     */
364
    public function testBeanGetException()
365
    {
366
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
367
        $bean = $beans[0];
368
369
        // we don't specify the table on inheritance table => exception.
370
        $bean->getProperty('id');
371
    }
372
373
    /**
374
     * @expectedException \TheCodingMachine\TDBM\TDBMException
375
     *
376
     * @throws TDBMException
377
     */
378
    public function testBeanSetException()
379
    {
380
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
381
        $bean = $beans[0];
382
383
        // we don't specify the table on inheritance table => exception.
384
        $bean->setProperty('name', 'foo');
385
    }
386
387
    public function testTake()
388
    {
389
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
390
391
        $page = $beans->take(0, 2);
392
393
        $this->assertEquals(2, $page->count());
394
395
        $results = [];
396
        foreach ($page as $result) {
397
            $results[] = $result;
398
        }
399
        $this->assertCount(2, $results);
400
401
        $this->assertEquals(5, $page->totalCount());
402
403
        $page = $beans->take(1, 1);
404
405
        $this->assertEquals(1, $page->count());
406
407
        $resultArray = $page->toArray();
408
        $this->assertCount(1, $resultArray);
409
        $this->assertTrue($resultArray[0] === $page[0]);
410
        // Test page isset
411
        $this->assertTrue(isset($page[0]));
412
    }
413
414
    public function testTakeInCursorMode()
415
    {
416
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], TDBMService::MODE_CURSOR, TDBMObject::class);
417
418
        $page = $beans->take(0, 2);
419
420
        $this->assertEquals(2, $page->count());
421
        $this->assertEquals(0, $page->getCurrentOffset());
422
        $this->assertEquals(2, $page->getCurrentLimit());
423
        $this->assertEquals(1, $page->getCurrentPage());
424
425
        $results = [];
426
        foreach ($page as $result) {
427
            $results[] = $result;
428
        }
429
        $this->assertCount(2, $results);
430
431
        $this->assertEquals(5, $page->totalCount());
432
433
        $page = $beans->take(1, 1);
434
        $this->assertEquals(1, $page->getCurrentOffset());
435
        $this->assertEquals(1, $page->getCurrentLimit());
436
        $this->assertEquals(2, $page->getCurrentPage());
437
438
        $this->assertEquals(1, $page->count());
439
    }
440
441
    public function testMap()
442
    {
443
        $beans = $this->tdbmService->findObjects('person', null, [], 'person.id ASC', [], null, TDBMObject::class);
444
445
        $results = $beans->map(function ($item) {
446
            return $item->getProperty('id', 'person');
447
        })->toArray();
448
449
        $this->assertEquals([1, 2, 3, 4, 6], $results);
450
451
        // Same test with page
452
        $page = $beans->take(0, 2);
453
454
        $results = $page->map(function ($item) {
455
            return $item->getProperty('id', 'person');
456
        })->toArray();
457
458
        $this->assertEquals([1, 2], $results);
459
    }
460
461
    /**
462
     * @expectedException \TheCodingMachine\TDBM\TDBMException
463
     *
464
     * @throws TDBMException
465
     */
466
    public function testUnsetException()
467
    {
468
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
469
470
        unset($beans[0]);
471
    }
472
473
    /**
474
     * @expectedException \TheCodingMachine\TDBM\TDBMException
475
     *
476
     * @throws TDBMException
477
     */
478
    public function testSetException()
479
    {
480
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
481
482
        $beans[0] = 'foo';
483
    }
484
485
    /**
486
     * @expectedException \TheCodingMachine\TDBM\TDBMException
487
     *
488
     * @throws TDBMException
489
     */
490
    public function testPageUnsetException()
491
    {
492
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
493
        $page = $beans->take(0, 1);
494
        unset($page[0]);
495
    }
496
497
    /**
498
     * @expectedException \TheCodingMachine\TDBM\TDBMException
499
     *
500
     * @throws TDBMException
501
     */
502
    public function testPageSetException()
503
    {
504
        $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
505
        $page = $beans->take(0, 1);
506
        $page[0] = 'foo';
507
    }
508
509
    public function testToArray()
510
    {
511
        $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
512
513
        $beanArray = $beans->toArray();
514
515
        $this->assertCount(1, $beanArray);
516
        $this->assertEquals(1, $beanArray[0]->getProperty('id', 'contact'));
517
    }
518
519
    public function testCursorMode()
520
    {
521
        $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], TDBMService::MODE_CURSOR, TDBMObject::class);
522
523
        $this->assertInstanceOf('\\TheCodingMachine\\TDBM\\ResultIterator', $beans);
524
525
        $result = [];
526
        foreach ($beans as $bean) {
527
            $result[] = $bean;
528
        }
529
530
        $this->assertCount(1, $result);
531
532
        // In cursor mode, access by array causes an exception.
533
        $exceptionTriggered = false;
534
        try {
535
            $beans[0];
536
        } catch (TDBMInvalidOperationException $e) {
537
            $exceptionTriggered = true;
538
        }
539
        $this->assertTrue($exceptionTriggered);
540
541
        $exceptionTriggered = false;
542
        try {
543
            isset($beans[0]);
544
        } catch (TDBMInvalidOperationException $e) {
545
            $exceptionTriggered = true;
546
        }
547
        $this->assertTrue($exceptionTriggered);
548
    }
549
550
    public function testSetFetchMode()
551
    {
552
        $this->tdbmService->setFetchMode(TDBMService::MODE_CURSOR);
553
        $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
554
555
        $this->assertInstanceOf('\\TheCodingMachine\\TDBM\\ResultIterator', $beans);
556
557
        // In cursor mode, access by array causes an exception.
558
        $exceptionTriggered = false;
559
        try {
560
            $beans[0];
561
        } catch (TDBMInvalidOperationException $e) {
562
            $exceptionTriggered = true;
563
        }
564
        $this->assertTrue($exceptionTriggered);
565
    }
566
567
    /**
568
     * @expectedException \TheCodingMachine\TDBM\TDBMException
569
     *
570
     * @throws TDBMException
571
     */
572
    public function testInvalidSetFetchMode()
573
    {
574
        $this->tdbmService->setFetchMode('foo');
575
    }
576
577
    /**
578
     * @expectedException \TheCodingMachine\TDBM\TDBMException
579
     *
580
     * @throws TDBMException
581
     */
582
    public function testCursorModeException()
583
    {
584
        $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], 'foobaz');
585
    }
586
587
    /**
588
     * @expectedException \TheCodingMachine\TDBM\TDBMException
589
     *
590
     * @throws TDBMException
591
     */
592
    public function testTableNameException()
593
    {
594
        $beans = $this->tdbmService->findObjects('foo bar');
595
    }
596
597
    public function testLinkedTableFetch()
598
    {
599
        $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, ['country'], null, TDBMObject::class);
600
    }
601
602
    public function testFindObject()
603
    {
604
        $bean = $this->tdbmService->findObject('contact', 'contact.id = :id', ['id' => -42], [], TDBMObject::class);
605
        $this->assertNull($bean);
606
    }
607
608
    /**
609
     * @expectedException \TheCodingMachine\TDBM\NoBeanFoundException
610
     *
611
     * @throws NoBeanFoundException
612
     */
613
    public function testFindObjectOrFail()
614
    {
615
        $bean = $this->tdbmService->findObjectOrFail('contact', 'contact.id = :id', ['id' => -42], [], TDBMObject::class);
616
    }
617
618
    /**
619
     * @expectedException \TheCodingMachine\TDBM\DuplicateRowException
620
     *
621
     * @throws DuplicateRowException
622
     */
623
    public function testFindObjectDuplicateRow()
624
    {
625
        $bean = $this->tdbmService->findObject('contact');
626
    }
627
628
    public function testFindObjectsByBean()
629
    {
630
        $countryBean = $this->tdbmService->findObject('country', 'id = :id', ['id' => 1], [], TDBMObject::class);
631
632
        $users = $this->tdbmService->findObjects('users', $countryBean, [], null, [], null, TDBMObject::class);
633
        $this->assertCount(1, $users);
634
        $this->assertEquals('jean.dupont', $users[0]->getProperty('login', 'users'));
635
    }
636
637
    /**
638
     * @expectedException \TheCodingMachine\TDBM\TDBMException
639
     *
640
     * @throws TDBMException
641
     * @throws TDBMInvalidOperationException
642
     */
643
    public function testBeanWithoutStatus()
644
    {
645
        $object = new TDBMObject('users');
646
        $object->setProperty('login', 'john.doe');
647
        $object->setProperty('country_id', 3);
648
        $object->setProperty('name', 'John Doe', 'person');
649
        $object->setProperty('email', '[email protected]', 'contact');
650
        $object->_setStatus(null);
651
        $this->tdbmService->save($object);
652
    }
653
654
    public function testFindObjectsFromSql()
655
    {
656
        $roles = $this->tdbmService->findObjectsFromSql(
657
            'roles',
658
            'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
659
            'rights.label = :right',
660
            array('right' => 'CAN_SING'),
661
            'roles.name DESC'
662
        );
663
        $this->assertCount(2, $roles);
664
        $this->assertInstanceOf(AbstractTDBMObject::class, $roles[0]);
665
    }
666
667
    /**
668
     * @expectedException \TheCodingMachine\TDBM\TDBMException
669
     *
670
     * @throws TDBMException
671
     */
672
    public function testFindObjectsFromSqlBadTableName()
673
    {
674
        $this->tdbmService->findObjectsFromSql(
675
            '#{azerty',
676
            'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
677
            'rights.label = :right',
678
            array('right' => 'CAN_SING'),
679
            'name DESC'
680
        );
681
    }
682
683
    /**
684
     * @expectedException \TheCodingMachine\TDBM\TDBMException
685
     *
686
     * @throws TDBMException
687
     */
688
    public function testFindObjectsFromSqlGroupBy()
689
    {
690
        $roles = $this->tdbmService->findObjectsFromSql(
691
            'roles',
692
            'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
693
            'rights.label = :right GROUP BY roles.name',
694
            array('right' => 'CAN_SING'),
695
            'name DESC'
696
        );
697
        $role = $roles[0];
698
    }
699
700
    public function testFindObjectFromSql()
701
    {
702
        $role = $this->tdbmService->findObjectFromSql(
703
            'roles',
704
            'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
705
            'rights.label = :right AND name = :name',
706
            array('right' => 'CAN_SING', 'name' => 'Singers')
707
        );
708
        $this->assertInstanceOf(AbstractTDBMObject::class, $role);
709
    }
710
711
    /**
712
     * @expectedException \TheCodingMachine\TDBM\DuplicateRowException
713
     *
714
     * @throws DuplicateRowException
715
     */
716
    public function testFindObjectFromSqlException()
717
    {
718
        $this->tdbmService->findObjectFromSql(
719
            'roles',
720
            'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
721
            'rights.label = :right',
722
            array('right' => 'CAN_SING')
723
        );
724
    }
725
726
    public function testFindObjectsFromSqlHierarchyDown()
727
    {
728
        $users = $this->tdbmService->findObjectsFromSql(
729
            'person',
730
            'person',
731
            'name LIKE :name OR name LIKE :name2',
732
            array('name' => 'Robert Marley', 'name2' => 'Bill Shakespeare'),
733
            null,
734
            null,
735
            TDBMObject::class
736
        );
737
        $this->assertCount(2, $users);
738
        $this->assertSame('robert.marley', $users[0]->getProperty('login', 'users'));
739
    }
740
741
    public function testFindObjectsFromSqlHierarchyUp()
742
    {
743
        $users = $this->tdbmService->findObjectsFromSql(
744
            'users',
745
            'users',
746
            'login LIKE :login OR login LIKE :login2',
747
            array('login' => 'robert.marley', 'login2' => 'bill.shakespeare'),
748
            null,
749
            null,
750
            TDBMObject::class
751
        );
752
        $this->assertCount(2, $users);
753
        $this->assertSame('Robert Marley', $users[0]->getProperty('name', 'person'));
754
    }
755
756
    public function testLogger()
757
    {
758
        $arrayLogger = new ArrayLogger();
759
        $tdbmService = new TDBMService(new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), $this->getNamingStrategy(), null, null, $arrayLogger));
760
761
        $tdbmService->setLogLevel(LogLevel::DEBUG);
762
        $beans = $tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
763
        $beans->first();
764
765
        $this->assertNotEmpty($arrayLogger->get());
766
    }
767
768
    public function testFindObjectsCountWithOneToManyLink()
769
    {
770
        $countries = $this->tdbmService->findObjects('country', "users.status = 'on' OR users.status = 'off'");
771
772
        $this->assertEquals(3, $countries->count());
773
    }
774
775
    public function testFindObjectsFromSqlCountWithOneToManyLink()
776
    {
777
        $countries = $this->tdbmService->findObjectsFromSql('country', 'country LEFT JOIN users ON country.id = users.country_id', "users.status = 'on' OR users.status = 'off'");
778
779
        $this->assertEquals(3, $countries->count());
780
    }
781
}
782