Test Failed
Push — uuid_annotation ( d6506f )
by David
06:37
created

TDBMDaoGeneratorTest::testFindOrderBy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 13

Duplication

Lines 18
Ratio 100 %

Importance

Changes 0
Metric Value
dl 18
loc 18
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 13
nc 2
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 Doctrine\Common\Cache\ArrayCache;
24
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
25
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
26
use TheCodingMachine\TDBM\Dao\TestCountryDao;
27
use TheCodingMachine\TDBM\Dao\TestRoleDao;
28
use TheCodingMachine\TDBM\Dao\TestUserDao;
29
use TheCodingMachine\TDBM\Test\Dao\AllNullableDao;
30
use TheCodingMachine\TDBM\Test\Dao\AnimalDao;
31
use TheCodingMachine\TDBM\Test\Dao\Bean\AllNullableBean;
32
use TheCodingMachine\TDBM\Test\Dao\Bean\ArticleBean;
33
use TheCodingMachine\TDBM\Test\Dao\Bean\BoatBean;
34
use TheCodingMachine\TDBM\Test\Dao\Bean\CatBean;
35
use TheCodingMachine\TDBM\Test\Dao\Bean\CategoryBean;
36
use TheCodingMachine\TDBM\Test\Dao\Bean\CountryBean;
37
use TheCodingMachine\TDBM\Test\Dao\Bean\DogBean;
38
use TheCodingMachine\TDBM\Test\Dao\Bean\PersonBean;
39
use TheCodingMachine\TDBM\Test\Dao\Bean\RoleBean;
40
use TheCodingMachine\TDBM\Test\Dao\Bean\UserBean;
41
use TheCodingMachine\TDBM\Test\Dao\BoatDao;
42
use TheCodingMachine\TDBM\Test\Dao\CatDao;
43
use TheCodingMachine\TDBM\Test\Dao\CategoryDao;
44
use TheCodingMachine\TDBM\Test\Dao\ContactDao;
45
use TheCodingMachine\TDBM\Test\Dao\CountryDao;
46
use TheCodingMachine\TDBM\Test\Dao\DogDao;
47
use TheCodingMachine\TDBM\Test\Dao\Generated\UserBaseDao;
48
use TheCodingMachine\TDBM\Test\Dao\RoleDao;
49
use TheCodingMachine\TDBM\Test\Dao\UserDao;
50
use TheCodingMachine\TDBM\Utils\PathFinder\NoPathFoundException;
51
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
52
use Symfony\Component\Process\Process;
53
54
class TDBMDaoGeneratorTest extends TDBMAbstractServiceTest
55
{
56
    /** @var TDBMDaoGenerator $tdbmDaoGenerator */
57
    protected $tdbmDaoGenerator;
58
59
    private $rootPath;
60
61
    protected function setUp()
62
    {
63
        parent::setUp();
64
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
65
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
66
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
67
        $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
68
        $this->rootPath = __DIR__.'/../';
69
        //$this->tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
70
    }
71
72
    public function testDaoGeneration()
73
    {
74
        // Remove all previously generated files.
75
        $this->recursiveDelete($this->rootPath.'src/Test/Dao/');
76
77
        $this->tdbmDaoGenerator->generateAllDaosAndBeans();
78
79
        // Let's require all files to check they are valid PHP!
80
        // Test the daoFactory
81
        require_once $this->rootPath.'src/Test/Dao/Generated/DaoFactory.php';
82
        // Test the others
83
84
        $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
85
86
        foreach ($beanDescriptors as $beanDescriptor) {
87
            $daoName = $beanDescriptor->getDaoClassName();
88
            $daoBaseName = $beanDescriptor->getBaseDaoClassName();
89
            $beanName = $beanDescriptor->getBeanClassName();
90
            $baseBeanName = $beanDescriptor->getBaseBeanClassName();
91
            require_once $this->rootPath.'src/Test/Dao/Bean/Generated/'.$baseBeanName.'.php';
92
            require_once $this->rootPath.'src/Test/Dao/Bean/'.$beanName.'.php';
93
            require_once $this->rootPath.'src/Test/Dao/Generated/'.$daoBaseName.'.php';
94
            require_once $this->rootPath.'src/Test/Dao/'.$daoName.'.php';
95
        }
96
97
        // Check that pivot tables do not generate DAOs or beans.
98
        $this->assertFalse(class_exists('TheCodingMachine\\TDBM\\Test\\Dao\\RolesRightDao'));
99
    }
100
101
    public function testGenerationException()
102
    {
103
        $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', $this->dbConnection, $this->getNamingStrategy());
104
105
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
106
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
107
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
108
        $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
109
        $this->rootPath = __DIR__.'/../../../../';
110
        //$tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
111
112
        $this->expectException(NoPathFoundException::class);
113
        $tdbmDaoGenerator->generateAllDaosAndBeans();
114
    }
115
116
    /**
117
     * Delete a file or recursively delete a directory.
118
     *
119
     * @param string $str Path to file or directory
120
     * @return bool
121
     */
122
    private function recursiveDelete(string $str) : bool
123
    {
124
        if (is_file($str)) {
125
            return @unlink($str);
126
        } elseif (is_dir($str)) {
127
            $scan = glob(rtrim($str, '/') . '/*');
128
            foreach ($scan as $index => $path) {
129
                $this->recursiveDelete($path);
130
            }
131
132
            return @rmdir($str);
133
        }
134
        return false;
135
    }
136
137
    /**
138
     * @depends testDaoGeneration
139
     */
140
    public function testGetBeanClassName()
141
    {
142
        $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
143
    }
144
145
    /**
146
     * @depends testDaoGeneration
147
     */
148
    public function testGetBeanClassNameException()
149
    {
150
        $this->expectException(TDBMInvalidArgumentException::class);
151
        $this->tdbmService->getBeanClassName('not_exists');
152
    }
153
154
    /**
155
     * @depends testDaoGeneration
156
     */
157
    public function testGeneratedGetById()
158
    {
159
        $contactDao = new ContactDao($this->tdbmService);
160
        $contactBean = $contactDao->getById(1);
161
        $this->assertEquals(1, $contactBean->getId());
162
        $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
163
164
        // FIXME: Question: que faire du paramètre stockage "UTC"????
165
    }
166
167
    /**
168
     * @depends testDaoGeneration
169
     */
170
    public function testGeneratedGetByIdLazyLoaded()
171
    {
172
        $roleDao = new RoleDao($this->tdbmService);
173
        $roleBean = $roleDao->getById(1, true);
174
        $this->assertEquals(1, $roleBean->getId());
175
        $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
176
177
        $roleBean2 = $roleDao->getById(1, true);
178
        $this->assertTrue($roleBean === $roleBean2);
179
    }
180
181
    /**
182
     * @depends testDaoGeneration
183
     */
184
    public function testDefaultValueOnNewBean()
185
    {
186
        $roleBean = new RoleBean('my_role');
187
        $this->assertEquals(1, $roleBean->getStatus());
188
    }
189
190
    /**
191
     * @depends testDaoGeneration
192
     */
193 View Code Duplication
    public function testForeignKeyInBean()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194
    {
195
        $userDao = new UserDao($this->tdbmService);
196
        $userBean = $userDao->getById(1);
197
        $country = $userBean->getCountry();
198
199
        $this->assertEquals('UK', $country->getLabel());
200
201
        $userBean2 = $userDao->getById(1);
202
        $this->assertTrue($userBean === $userBean2);
203
204
        $contactDao = new ContactDao($this->tdbmService);
205
        $contactBean = $contactDao->getById(1);
206
207
        $this->assertTrue($userBean === $contactBean);
208
    }
209
210
    /**
211
     * @depends testDaoGeneration
212
     */
213
    public function testNewBeans()
214
    {
215
        $countryDao = new CountryDao($this->tdbmService);
216
        $userDao = new UserDao($this->tdbmService);
217
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
218
        $userBean->setOrder(1); // Let's set a "protected keyword" column.
219
220
        $userDao->save($userBean);
221
222
        $this->assertNull($userBean->getManager());
223
    }
224
225
    /**
226
     * @depends testDaoGeneration
227
     */
228
    public function testDateTimeImmutableGetter()
229
    {
230
        $userDao = new UserDao($this->tdbmService);
231
        $user = $userDao->getById(1);
232
233
        $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
234
    }
235
236
    /**
237
     * @depends testDaoGeneration
238
     */
239 View Code Duplication
    public function testAssigningNewBeans()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
240
    {
241
        $userDao = new UserDao($this->tdbmService);
242
        $countryBean = new CountryBean('Mexico');
243
        $userBean = new UserBean('Speedy Gonzalez', '[email protected]', $countryBean, 'speedy.gonzalez');
244
        $this->assertEquals($countryBean, $userBean->getCountry());
245
246
        $userDao->save($userBean);
247
    }
248
249
    /**
250
     * @depends testAssigningNewBeans
251
     */
252
    public function testUpdatingProtectedColumn()
253
    {
254
        $userDao = new UserDao($this->tdbmService);
255
        $userBean = $userDao->findOneByLogin('speedy.gonzalez');
256
        $userBean->setOrder(2);
257
        $userDao->save($userBean);
258
    }
259
260
    /**
261
     * @depends testDaoGeneration
262
     */
263 View Code Duplication
    public function testAssigningExistingRelationship()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
    {
265
        $userDao = new UserDao($this->tdbmService);
266
        $user = $userDao->getById(1);
267
        $countryDao = new CountryDao($this->tdbmService);
268
        $country = $countryDao->getById(2);
269
270
        $user->setCountry($country);
271
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
272
    }
273
274
    /**
275
     * @depends testDaoGeneration
276
     */
277
    public function testDirectReversedRelationship()
278
    {
279
        $countryDao = new CountryDao($this->tdbmService);
280
        $country = $countryDao->getById(1);
281
        $users = $country->getUsers();
282
283
        $arr = $users->toArray();
284
285
        $this->assertCount(1, $arr);
286
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
287
        $this->assertEquals('jean.dupont', $arr[0]->getLogin());
288
289
        $newUser = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
0 ignored issues
show
Unused Code introduced by
$newUser 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...
290
        $users = $country->getUsers();
291
292
        $arr = $users->toArray();
293
294
        $this->assertCount(2, $arr);
295
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
296
        $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
297
    }
298
299
    /**
300
     * @depends testDaoGeneration
301
     */
302
    public function testDeleteInDirectReversedRelationship()
303
    {
304
        $countryDao = new CountryDao($this->tdbmService);
305
        $country = $countryDao->getById(1);
306
307
        $userDao = new UserDao($this->tdbmService);
308
        $newUser = new UserBean('John Snow', '[email protected]', $country, 'john.snow');
309
        $userDao->save($newUser);
310
311
        $users = $country->getUsers();
312
313
        $arr = $users->toArray();
314
315
        $this->assertCount(2, $arr);
316
317
        $userDao->delete($arr[1]);
318
319
        $users = $country->getUsers();
320
        $arr = $users->toArray();
321
        $this->assertCount(1, $arr);
322
    }
323
324
    /**
325
     * @depends testDaoGeneration
326
     */
327
    public function testJointureGetters()
328
    {
329
        $roleDao = new RoleDao($this->tdbmService);
330
        $role = $roleDao->getById(1);
331
        $users = $role->getUsers();
332
333
        $this->assertCount(2, $users);
334
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
335
336
        $rights = $role->getRights();
337
338
        $this->assertCount(2, $rights);
339
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
340
    }
341
342
    /**
343
     * @depends testDaoGeneration
344
     */
345
    public function testNewBeanConstructor()
346
    {
347
        $role = new RoleBean('Newrole');
348
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
349
    }
350
351
    /**
352
     * @depends testDaoGeneration
353
     */
354
    public function testJointureAdderOnNewBean()
355
    {
356
        $countryDao = new CountryDao($this->tdbmService);
357
        $country = $countryDao->getById(1);
358
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
359
        $role = new RoleBean('Mouse');
360
        $user->addRole($role);
361
        $roles = $user->getRoles();
362
        $this->assertCount(1, $roles);
363
        $role = $roles[0];
364
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
365
        $users = $role->getUsers();
366
        $this->assertCount(1, $users);
367
        $this->assertEquals($user, $users[0]);
368
369
        $role->removeUser($user);
370
        $this->assertCount(0, $role->getUsers());
371
        $this->assertCount(0, $user->getRoles());
372
    }
373
374
    /**
375
     * @depends testDaoGeneration
376
     */
377 View Code Duplication
    public function testJointureDeleteBeforeGetters()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
378
    {
379
        $roleDao = new RoleDao($this->tdbmService);
380
        $userDao = new UserDao($this->tdbmService);
381
        $role = $roleDao->getById(1);
382
        $user = $userDao->getById(1);
383
384
        // We call removeUser BEFORE calling getUsers
385
        // This should work as expected.
386
        $role->removeUser($user);
387
        $users = $role->getUsers();
388
389
        $this->assertCount(1, $users);
390
    }
391
392
    /**
393
     * @depends testDaoGeneration
394
     */
395
    public function testJointureMultiAdd()
396
    {
397
        $countryDao = new CountryDao($this->tdbmService);
398
        $country = $countryDao->getById(1);
399
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
400
        $role = new RoleBean('Mouse');
401
        $user->addRole($role);
402
        $role->addUser($user);
403
        $user->addRole($role);
404
405
        $this->assertCount(1, $user->getRoles());
406
    }
407
408
    /**
409
     * Step 1: we remove the role 1 from user 1 but save role 1.
410
     * Expected result: no save done.
411
     *
412
     * @depends testDaoGeneration
413
     */
414
    public function testJointureSave1()
415
    {
416
        $roleDao = new RoleDao($this->tdbmService);
417
        $role = $roleDao->getById(1);
418
        $userDao = new UserDao($this->tdbmService);
419
        $user = $userDao->getById(1);
420
421
        $this->assertTrue($user->hasRole($role));
422
        $this->assertTrue($role->hasUser($user));
423
        $user->removeRole($role);
424
        $this->assertFalse($user->hasRole($role));
425
        $this->assertFalse($role->hasUser($user));
426
        $roleDao->save($role);
427
428
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
429
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
430
    }
431
432
    /**
433
     * Step 2: we check that nothing was saved
434
     * Expected result: no save done.
435
     *
436
     * @depends testJointureSave1
437
     */
438
    public function testJointureSave2()
439
    {
440
        $roleDao = new RoleDao($this->tdbmService);
441
        $role = $roleDao->getById(1);
442
        $this->assertCount(2, $role->getUsers());
443
    }
444
445
    /**
446
     * Step 3: we remove the role 1 from user 1 and save user 1.
447
     * Expected result: save done.
448
     *
449
     * @depends testJointureSave2
450
     */
451
    public function testJointureSave3()
452
    {
453
        $roleDao = new RoleDao($this->tdbmService);
454
        $role = $roleDao->getById(1);
455
        $userDao = new UserDao($this->tdbmService);
456
        $user = $userDao->getById(1);
457
458
        $this->assertCount(1, $user->getRoles());
459
        $user->removeRole($role);
460
        $this->assertCount(0, $user->getRoles());
461
        $userDao->save($user);
462
        $this->assertCount(0, $user->getRoles());
463
    }
464
465
    /**
466
     * Step 4: we check that save was done
467
     * Expected result: save done.
468
     *
469
     * @depends testJointureSave3
470
     */
471 View Code Duplication
    public function testJointureSave4()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
472
    {
473
        $roleDao = new RoleDao($this->tdbmService);
474
        $role = $roleDao->getById(1);
475
        $this->assertCount(1, $role->getUsers());
476
        $userDao = new UserDao($this->tdbmService);
477
        $user = $userDao->getById(1);
478
        $this->assertCount(0, $user->getRoles());
479
    }
480
481
    /**
482
     * Step 5: we add the role 1 from user 1 and save user 1.
483
     * Expected result: save done.
484
     *
485
     * @depends testJointureSave4
486
     */
487 View Code Duplication
    public function testJointureSave5()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
488
    {
489
        $roleDao = new RoleDao($this->tdbmService);
490
        $role = $roleDao->getById(1);
491
        $userDao = new UserDao($this->tdbmService);
492
        $user = $userDao->getById(1);
493
494
        $user->addRole($role);
495
        $this->assertCount(1, $user->getRoles());
496
        $userDao->save($user);
497
    }
498
499
    /**
500
     * Step 6: we check that save was done
501
     * Expected result: save done.
502
     *
503
     * @depends testJointureSave5
504
     */
505 View Code Duplication
    public function testJointureSave6()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
506
    {
507
        $roleDao = new RoleDao($this->tdbmService);
508
        $role = $roleDao->getById(1);
509
        $this->assertCount(2, $role->getUsers());
510
        $userDao = new UserDao($this->tdbmService);
511
        $user = $userDao->getById(1);
512
        $this->assertCount(1, $user->getRoles());
513
    }
514
515
    /**
516
     * Step 7: we add a new role to user 1 and save user 1.
517
     * Expected result: save done, including the new role.
518
     *
519
     * @depends testJointureSave6
520
     */
521
    public function testJointureSave7()
522
    {
523
        $role = new RoleBean('my new role');
524
        $userDao = new UserDao($this->tdbmService);
525
        $user = $userDao->getById(1);
526
527
        $user->addRole($role);
528
        $userDao->save($user);
529
530
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
531
    }
532
533
    /**
534
     * Step 8: we check that save was done
535
     * Expected result: save done.
536
     *
537
     * @depends testJointureSave7
538
     */
539 View Code Duplication
    public function testJointureSave8()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
540
    {
541
        $roleDao = new RoleDao($this->tdbmService);
542
        $userDao = new UserDao($this->tdbmService);
543
        $user = $userDao->getById(1);
544
545
        $roles = $user->getRoles();
546
        foreach ($roles as $role) {
547
            if ($role->getName() === 'my new role') {
548
                $selectedRole = $role;
549
                break;
550
            }
551
        }
552
        $this->assertNotNull($selectedRole);
0 ignored issues
show
Bug introduced by
The variable $selectedRole does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
553
554
        $this->assertCount(2, $user->getRoles());
555
556
        // Expected: relationship removed!
557
        $roleDao->delete($selectedRole);
558
559
        $this->assertCount(1, $user->getRoles());
560
    }
561
562
    /**
563
     * Step 9: Let's test the setXXX method.
564
     *
565
     * @depends testJointureSave8
566
     */
567
    public function testJointureSave9()
568
    {
569
        $roleDao = new RoleDao($this->tdbmService);
570
        $userDao = new UserDao($this->tdbmService);
571
        $user = $userDao->getById(1);
572
573
        // At this point, user 1 is linked to role 1.
574
        // Let's bind it to role 2.
575
        $user->setRoles([$roleDao->getById(2)]);
576
        $userDao->save($user);
577
    }
578
579
    /**
580
     * Step 10: Let's check results of 9.
581
     *
582
     * @depends testJointureSave9
583
     */
584
    public function testJointureSave10()
585
    {
586
        $userDao = new UserDao($this->tdbmService);
587
        $user = $userDao->getById(1);
588
589
        $roles = $user->getRoles();
590
591
        $this->assertCount(1, $roles);
592
        $this->assertEquals(2, $roles[0]->getId());
593
    }
594
595
    /**
596
     * @depends testDaoGeneration
597
     */
598 View Code Duplication
    public function testFindOrderBy()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
599
    {
600
        $userDao = new TestUserDao($this->tdbmService);
601
        $users = $userDao->getUsersByAlphabeticalOrder();
602
603
        $this->assertCount(6, $users);
604
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
605
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
606
607
        $users = $userDao->getUsersByCountryOrder();
608
        $this->assertCount(6, $users);
609
        $countryName1 = $users[0]->getCountry()->getLabel();
610
        for ($i = 1; $i < 6; $i++) {
611
            $countryName2 = $users[$i]->getCountry()->getLabel();
612
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
613
            $countryName1 = $countryName2;
614
        }
615
    }
616
617
    /**
618
     * @depends testDaoGeneration
619
     */
620 View Code Duplication
    public function testFindFromSqlOrderBy()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
621
    {
622
        $userDao = new TestUserDao($this->tdbmService);
623
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
624
625
        $this->assertCount(6, $users);
626
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
627
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
628
629
        $users = $userDao->getUsersFromSqlByCountryOrder();
630
        $this->assertCount(6, $users);
631
        $countryName1 = $users[0]->getCountry()->getLabel();
632
        for ($i = 1; $i < 6; $i++) {
633
            $countryName2 = $users[$i]->getCountry()->getLabel();
634
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
635
            $countryName1 = $countryName2;
636
        }
637
    }
638
639
    /**
640
     * @depends testDaoGeneration
641
     */
642
    public function testFindFromSqlOrderByJoinRole()
643
    {
644
        $roleDao = new TestRoleDao($this->tdbmService);
645
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
646
647
        $this->assertCount(2, $roles);
648
        $this->assertEquals('Singers', $roles[0]->getName());
649
        $this->assertEquals('Admins', $roles[1]->getName());
650
    }
651
652
    /**
653
     * @depends testDaoGeneration
654
     */
655
    public function testFindFromRawSqlOrderByUserCount()
656
    {
657
        $countryDao = new TestCountryDao($this->tdbmService);
658
        $countries = $countryDao->getCountriesByUserCount();
659
660
        $this->assertCount(4, $countries);
661
        for ($i = 1; $i < count($countries); $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...
662
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
663
        }
664
    }
665
666
    /**
667
     * @depends testDaoGeneration
668
     */
669 View Code Duplication
    public function testFindFilters()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
670
    {
671
        $userDao = new TestUserDao($this->tdbmService);
672
        $users = $userDao->getUsersByLoginStartingWith('bill');
673
674
        $this->assertCount(1, $users);
675
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
676
    }
677
678
    /**
679
     * @expectedException \TheCodingMachine\TDBM\TDBMException
680
     * @depends testDaoGeneration
681
     */
682
    public function testFindMode()
683
    {
684
        $userDao = new TestUserDao($this->tdbmService);
685
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
686
687
        $users[0];
688
    }
689
690
    /**
691
     * @depends testDaoGeneration
692
     */
693
    public function testFindAll()
694
    {
695
        $userDao = new TestUserDao($this->tdbmService);
696
        $users = $userDao->findAll();
697
698
        $this->assertCount(6, $users);
699
    }
700
701
    /**
702
     * @depends testDaoGeneration
703
     */
704
    public function testFindOne()
705
    {
706
        $userDao = new TestUserDao($this->tdbmService);
707
        $user = $userDao->getUserByLogin('bill.shakespeare');
708
709
        $this->assertEquals('bill.shakespeare', $user->getLogin());
710
    }
711
712
    /**
713
     * @depends testDaoGeneration
714
     */
715
    public function testJsonEncodeBean()
716
    {
717
        $userDao = new TestUserDao($this->tdbmService);
718
        $user = $userDao->getUserByLogin('bill.shakespeare');
719
720
        $jsonEncoded = json_encode($user);
721
        $userDecoded = json_decode($jsonEncoded, true);
722
723
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
724
725
        // test serialization of dates.
726
        $this->assertTrue(is_string($userDecoded['createdAt']));
727
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
728
        $this->assertNull($userDecoded['modifiedAt']);
729
730
        // testing many to 1 relationships
731
        $this->assertEquals('UK', $userDecoded['country']['label']);
732
733
        // testing many to many relationships
734
        $this->assertCount(1, $userDecoded['roles']);
735
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
736
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
737
    }
738
739
    /**
740
     * @depends testDaoGeneration
741
     */
742
    public function testNullableForeignKey()
743
    {
744
        $userDao = new TestUserDao($this->tdbmService);
745
        $user = $userDao->getUserByLogin('john.smith');
746
747
        $this->assertNull(null, $user->getManager());
748
749
        $jsonEncoded = json_encode($user);
750
        $userDecoded = json_decode($jsonEncoded, true);
751
752
        $this->assertNull(null, $userDecoded['manager']);
753
    }
754
755
    /**
756
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
757
     *
758
     * @depends testDaoGeneration
759
     */
760
    public function testSetToNullForeignKey()
761
    {
762
        $userDao = new TestUserDao($this->tdbmService);
763
        $user = $userDao->getUserByLogin('john.smith');
764
        $manager = $userDao->getUserByLogin('jean.dupont');
765
766
        $user->setManager($manager);
767
        $userDao->save($user);
768
769
        $user->setManager(null);
770
        $userDao->save($user);
771
    }
772
773
    /**
774
     * @depends testDaoGeneration
775
     * @expectedException \Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException
776
     * @expectedExceptionMessage Could not find table 'contacts'. Did you mean 'contact'?
777
     */
778
    public function testQueryOnWrongTableName()
779
    {
780
        $userDao = new TestUserDao($this->tdbmService);
781
        $users = $userDao->getUsersWrongTableName();
782
        $users->count();
783
    }
784
785
    /**
786
     * @depends testDaoGeneration
787
     */
788
    /*public function testQueryNullForeignKey()
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
789
    {
790
        $userDao = new TestUserDao($this->tdbmService);
791
        $users = $userDao->getUsersByManagerId(null);
792
        $this->assertCount(3, $users);
793
    }*/
794
795
    /**
796
     * @depends testDaoGeneration
797
     */
798
    public function testInnerJsonEncode()
799
    {
800
        $userDao = new TestUserDao($this->tdbmService);
801
        $user = $userDao->getUserByLogin('bill.shakespeare');
802
803
        $jsonEncoded = json_encode(['user' => $user]);
804
        $msgDecoded = json_decode($jsonEncoded, true);
805
806
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
807
    }
808
809
    /**
810
     * @depends testDaoGeneration
811
     */
812 View Code Duplication
    public function testArrayJsonEncode()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
813
    {
814
        $userDao = new TestUserDao($this->tdbmService);
815
        $users = $userDao->getUsersByLoginStartingWith('bill');
816
817
        $jsonEncoded = json_encode($users);
818
        $msgDecoded = json_decode($jsonEncoded, true);
819
820
        $this->assertCount(1, $msgDecoded);
821
    }
822
823
    /**
824
     * @depends testDaoGeneration
825
     */
826 View Code Duplication
    public function testCursorJsonEncode()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
827
    {
828
        $userDao = new TestUserDao($this->tdbmService);
829
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
830
831
        $jsonEncoded = json_encode($users);
832
        $msgDecoded = json_decode($jsonEncoded, true);
833
834
        $this->assertCount(1, $msgDecoded);
835
    }
836
837
    /**
838
     * @depends testDaoGeneration
839
     */
840 View Code Duplication
    public function testPageJsonEncode()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
841
    {
842
        $userDao = new TestUserDao($this->tdbmService);
843
        $users = $userDao->getUsersByLoginStartingWith('bill');
844
845
        $jsonEncoded = json_encode($users->take(0, 1));
846
        $msgDecoded = json_decode($jsonEncoded, true);
847
848
        $this->assertCount(1, $msgDecoded);
849
    }
850
851
    /**
852
     * @depends testDaoGeneration
853
     */
854 View Code Duplication
    public function testFirst()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
855
    {
856
        $userDao = new TestUserDao($this->tdbmService);
857
        $users = $userDao->getUsersByLoginStartingWith('bill');
858
859
        $bill = $users->first();
860
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
861
    }
862
863
    /**
864
     * @depends testDaoGeneration
865
     */
866
    public function testFirstNull()
867
    {
868
        $userDao = new TestUserDao($this->tdbmService);
869
        $users = $userDao->getUsersByLoginStartingWith('mike');
870
871
        $user = $users->first();
872
        $this->assertNull($user);
873
    }
874
875
    /**
876
     * @depends testDaoGeneration
877
     */
878
    public function testCloneBeanAttachedBean()
879
    {
880
        $userDao = new TestUserDao($this->tdbmService);
881
        $user = $userDao->getUserByLogin('bill.shakespeare');
882
        $this->assertEquals(4, $user->getId());
883
        $user2 = clone $user;
884
        $this->assertNull($user2->getId());
885
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
886
        $this->assertEquals('Bill Shakespeare', $user2->getName());
887
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
888
889
        // MANY 2 MANY must be duplicated
890
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
891
892
        // Let's test saving this clone
893
        $user2->setLogin('william.shakespeare');
894
        $userDao->save($user2);
895
896
        $user3 = $userDao->getUserByLogin('william.shakespeare');
897
        $this->assertTrue($user3 === $user2);
898
        $userDao->delete($user3);
899
900
        // Finally, let's test the origin user still exists!
901
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
902
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
903
    }
904
905
    /**
906
     * @depends testDaoGeneration
907
     */
908
    public function testCloneNewBean()
909
    {
910
        $countryDao = new CountryDao($this->tdbmService);
911
        $roleDao = new RoleDao($this->tdbmService);
912
        $role = $roleDao->getById(1);
913
914
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
915
        $userBean->addRole($role);
916
917
        $user2 = clone $userBean;
918
919
        $this->assertNull($user2->getId());
920
        $this->assertEquals('john.doe', $user2->getLogin());
921
        $this->assertEquals('John Doe', $user2->getName());
922
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
923
924
        // MANY 2 MANY must be duplicated
925
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
926
    }
927
928
    /**
929
     * @depends testDaoGeneration
930
     */
931
    public function testCascadeDelete()
932
    {
933
        $userDao = new TestUserDao($this->tdbmService);
934
        $countryDao = new CountryDao($this->tdbmService);
935
936
        $spain = new CountryBean('Spain');
937
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
938
939
        $countryDao->save($spain);
940
        $userDao->save($sanchez);
941
942
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
943
        $this->assertTrue($sanchez === $speedy2);
944
945
        $exceptionTriggered = false;
946
        try {
947
            $countryDao->delete($spain);
948
        } catch (ForeignKeyConstraintViolationException $e) {
949
            $exceptionTriggered = true;
950
        }
951
        $this->assertTrue($exceptionTriggered);
952
953
        $countryDao->delete($spain, true);
954
955
        // Let's check that speed gonzalez was removed.
956
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
957
        $this->assertNull($speedy3);
958
    }
959
960
    /**
961
     * @depends testDaoGeneration
962
     */
963
    public function testDiscardChanges()
964
    {
965
        $contactDao = new ContactDao($this->tdbmService);
966
        $contactBean = $contactDao->getById(1);
967
968
        $oldName = $contactBean->getName();
969
970
        $contactBean->setName('MyNewName');
971
972
        $contactBean->discardChanges();
973
974
        $this->assertEquals($oldName, $contactBean->getName());
975
    }
976
977
    /**
978
     * @expectedException \TheCodingMachine\TDBM\TDBMException
979
     * @depends testDaoGeneration
980
     */
981
    public function testDiscardChangesOnNewBeanFails()
982
    {
983
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
984
        $person->discardChanges();
985
    }
986
987
    /**
988
     * @expectedException \TheCodingMachine\TDBM\TDBMException
989
     * @depends testDaoGeneration
990
     */
991
    public function testDiscardChangesOnDeletedBeanFails()
992
    {
993
        $userDao = new TestUserDao($this->tdbmService);
994
        $countryDao = new CountryDao($this->tdbmService);
995
996
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
997
998
        $userDao->save($sanchez);
999
1000
        $userDao->delete($sanchez);
1001
1002
        // Cannot discard changes on a bean that is already deleted.
1003
        $sanchez->discardChanges();
1004
    }
1005
1006
    /**
1007
     * @depends testDaoGeneration
1008
     */
1009 View Code Duplication
    public function testUniqueIndexBasedSearch()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1010
    {
1011
        $userDao = new UserDao($this->tdbmService);
1012
        $user = $userDao->findOneByLogin('bill.shakespeare');
1013
1014
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1015
        $this->assertEquals('Bill Shakespeare', $user->getName());
1016
    }
1017
1018
    /**
1019
     * @depends testDaoGeneration
1020
     */
1021 View Code Duplication
    public function testMultiColumnsIndexBasedSearch()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1022
    {
1023
        $countryDao = new CountryDao($this->tdbmService);
1024
        $userDao = new UserDao($this->tdbmService);
1025
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1026
1027
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1028
    }
1029
1030
    /**
1031
     * @depends testDaoGeneration
1032
     */
1033
    public function testCreationInNullableDate()
1034
    {
1035
        $roleDao = new RoleDao($this->tdbmService);
1036
1037
        $role = new RoleBean('newbee');
1038
        $roleDao->save($role);
1039
1040
        $this->assertNull($role->getCreatedAt());
1041
    }
1042
1043
    /**
1044
     * @depends testDaoGeneration
1045
     */
1046
    public function testUpdateInNullableDate()
1047
    {
1048
        $roleDao = new RoleDao($this->tdbmService);
1049
1050
        $role = new RoleBean('newbee');
1051
        $roleDao->save($role);
1052
1053
        $role->setCreatedAt(null);
1054
        $roleDao->save($role);
1055
        $this->assertNull($role->getCreatedAt());
1056
    }
1057
1058
    /**
1059
     * @depends testDaoGeneration
1060
     */
1061
    public function testFindFromSql()
1062
    {
1063
        $roleDao = new TestRoleDao($this->tdbmService);
1064
1065
        $roles = $roleDao->getRolesByRightCanSing();
1066
        $this->assertCount(2, $roles);
1067
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1068
    }
1069
1070
    /**
1071
     * @depends testDaoGeneration
1072
     */
1073
    public function testFindOneFromSql()
1074
    {
1075
        $roleDao = new TestRoleDao($this->tdbmService);
1076
1077
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1078
        $this->assertInstanceOf(RoleBean::class, $role);
1079
    }
1080
1081
    /**
1082
     * @depends testDaoGeneration
1083
     */
1084
    public function testCreateEmptyExtendedBean()
1085
    {
1086
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1087
1088
        $dogDao = new DogDao($this->tdbmService);
1089
1090
        // We are not filling no field that is part of dog table.
1091
        $dog = new DogBean('Youki');
1092
        $dog->setOrder(1);
1093
1094
        $dogDao->save($dog);
1095
    }
1096
1097
    /**
1098
     * @depends testCreateEmptyExtendedBean
1099
     */
1100
    public function testFetchEmptyExtendedBean()
1101
    {
1102
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1103
1104
        $animalDao = new AnimalDao($this->tdbmService);
1105
1106
        // We are not filling no field that is part of dog table.
1107
        $animalBean = $animalDao->getById(1);
1108
1109
        $this->assertInstanceOf(DogBean::class, $animalBean);
1110
    }
1111
1112
    /**
1113
     * @depends testDaoGeneration
1114
     */
1115
    public function testTwoBranchesHierarchy()
1116
    {
1117
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1118
1119
        $catDao = new CatDao($this->tdbmService);
1120
1121
        // We are not filling no field that is part of dog table.
1122
        $cat = new CatBean('Mew');
1123
        $cat->setOrder(2);
1124
1125
        $catDao->save($cat);
1126
    }
1127
1128
    /**
1129
     * @depends testTwoBranchesHierarchy
1130
     */
1131
    public function testFetchTwoBranchesHierarchy()
1132
    {
1133
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1134
1135
        $animalDao = new AnimalDao($this->tdbmService);
1136
1137
        $animalBean = $animalDao->getById(2);
1138
1139
        $this->assertInstanceOf(CatBean::class, $animalBean);
1140
        /* @var $animalBean CatBean */
1141
        $animalBean->setCutenessLevel(999);
1142
1143
        $animalDao->save($animalBean);
1144
    }
1145
1146
    /**
1147
     * @depends testDaoGeneration
1148
     */
1149
    public function testExceptionOnGetById()
1150
    {
1151
        $countryDao = new CountryDao($this->tdbmService);
1152
        $this->expectException(\TypeError::class);
1153
        $countryDao->getById(null);
1154
    }
1155
1156
    /**
1157
     * @depends testDaoGeneration
1158
     */
1159
    public function testDisconnectedManyToOne()
1160
    {
1161
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1162
1163
        $country = new CountryBean('Spain');
1164
1165
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1166
1167
        $this->assertCount(1, $country->getUsers());
1168
        $this->assertSame($user, $country->getUsers()[0]);
1169
    }
1170
1171
    /**
1172
     * @depends testDaoGeneration
1173
     */
1174 View Code Duplication
    public function testOrderByExternalCol()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1175
    {
1176
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1177
1178
        $userDao = new TestUserDao($this->tdbmService);
1179
        $users = $userDao->getUsersByCountryName();
1180
1181
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1182
    }
1183
1184
    /**
1185
     * @depends testDaoGeneration
1186
     */
1187
    public function testResultIteratorSort()
1188
    {
1189
        $userDao = new UserDao($this->tdbmService);
1190
        $users = $userDao->findAll()->withOrder('country.label DESC');
1191
1192
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1193
1194
        $users = $users->withOrder('country.label ASC');
1195
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1196
    }
1197
1198
    /**
1199
     * @depends testDaoGeneration
1200
     */
1201
    public function testResultIteratorWithParameters()
1202
    {
1203
        $userDao = new TestUserDao($this->tdbmService);
1204
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1205
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1206
1207
        $users = $users->withParameters(['login' => 'jean%']);
1208
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1209
    }
1210
1211
    /**
1212
     * @depends testDaoGeneration
1213
     */
1214 View Code Duplication
    public function testOrderByExpression()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1215
    {
1216
        $userDao = new TestUserDao($this->tdbmService);
1217
        $users = $userDao->getUsersByReversedCountryName();
1218
1219
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1220
    }
1221
1222
    /**
1223
     * @depends testDaoGeneration
1224
     */
1225
    public function testOrderByException()
1226
    {
1227
        $userDao = new TestUserDao($this->tdbmService);
1228
        $users = $userDao->getUsersByInvalidOrderBy();
1229
        $this->expectException(TDBMInvalidArgumentException::class);
1230
        $user = $users[0];
0 ignored issues
show
Unused Code introduced by
$user 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...
1231
    }
1232
1233
    /**
1234
     * @depends testDaoGeneration
1235
     */
1236
    public function testOrderByProtectedColumn()
1237
    {
1238
        $animalDao = new AnimalDao($this->tdbmService);
1239
        $animals = $animalDao->findAll();
1240
        $animals = $animals->withOrder('`order` ASC');
1241
1242
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1243
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1244
1245
        $animals = $animals->withOrder('`order` DESC');
1246
1247
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1248
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1249
    }
1250
1251
    /**
1252
     * @depends testDaoGeneration
1253
     */
1254
    public function testGetOnAllNullableValues()
1255
    {
1256
        // Tests that a get performed on a column that has only nullable fields succeeds.
1257
        $allNullable = new AllNullableBean();
1258
        $this->assertNull($allNullable->getId());
1259
        $this->assertNull($allNullable->getLabel());
1260
        $this->assertNull($allNullable->getCountry());
1261
    }
1262
1263
    /**
1264
     * @depends testDaoGeneration
1265
     */
1266
    public function testExceptionOnMultipleInheritance()
1267
    {
1268
        $this->dbConnection->insert('animal', [
1269
            'id' => 99, 'name' => 'Snoofield',
1270
        ]);
1271
        $this->dbConnection->insert('dog', [
1272
            'id' => 99, 'race' => 'dog',
1273
        ]);
1274
        $this->dbConnection->insert('cat', [
1275
            'id' => 99, 'cuteness_level' => 0,
1276
        ]);
1277
1278
        $catched = false;
1279
        try {
1280
            $animalDao = new AnimalDao($this->tdbmService);
1281
            $animalDao->getById(99);
1282
        } catch (TDBMInheritanceException $e) {
1283
            $catched = true;
1284
        }
1285
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not catched');
1286
1287
        $this->dbConnection->delete('cat', ['id' => 99]);
1288
        $this->dbConnection->delete('dog', ['id' => 99]);
1289
        $this->dbConnection->delete('animal', ['id' => 99]);
1290
    }
1291
1292
    /**
1293
     * @depends testDaoGeneration
1294
     */
1295
    public function testReferenceNotSaved()
1296
    {
1297
        $boatDao = new BoatDao($this->tdbmService);
1298
1299
        $country = new CountryBean('Atlantis');
1300
        $boat = new BoatBean($country, 'Titanic');
1301
1302
        $boatDao->save($boat);
1303
    }
1304
1305
    /**
1306
     * @depends testDaoGeneration
1307
     */
1308
    public function testReferenceDeleted()
1309
    {
1310
        $countryDao = new CountryDao($this->tdbmService);
1311
        $boatDao = new BoatDao($this->tdbmService);
1312
1313
        $country = new CountryBean('Atlantis');
1314
        $countryDao->save($country);
1315
1316
        $boat = new BoatBean($country, 'Titanic');
1317
        $countryDao->delete($country);
1318
1319
        $this->expectException(TDBMMissingReferenceException::class);
1320
        $boatDao->save($boat);
1321
    }
1322
1323
    /**
1324
     * @depends testDaoGeneration
1325
     */
1326 View Code Duplication
    public function testCyclicReferenceWithInheritance()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1327
    {
1328
        $userDao = new UserDao($this->tdbmService);
1329
1330
        $country = new CountryBean('Norrisland');
1331
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1332
1333
        $user->setManager($user);
1334
1335
        $this->expectException(TDBMCyclicReferenceException::class);
1336
        $userDao->save($user);
1337
    }
1338
1339
    /**
1340
     * @depends testDaoGeneration
1341
     */
1342
    public function testCyclicReference()
1343
    {
1344
        $categoryDao = new CategoryDao($this->tdbmService);
1345
1346
        $category = new CategoryBean('Root');
1347
1348
        $category->setParent($category);
1349
1350
        $this->expectException(TDBMCyclicReferenceException::class);
1351
        $categoryDao->save($category);
1352
    }
1353
1354
    /**
1355
     * @depends testDaoGeneration
1356
     */
1357
    public function testCorrectTypeForPrimaryKeyAfterSave()
1358
    {
1359
        $allNullableDao = new AllNullableDao($this->tdbmService);
1360
        $allNullable = new AllNullableBean();
1361
        $allNullableDao->save($allNullable);
1362
        $id = $allNullable->getId();
1363
1364
        $this->assertTrue(is_int($id));
1365
    }
1366
1367
    /**
1368
     * @depends testDaoGeneration
1369
     */
1370
    public function testPSR2Compliance()
1371
    {
1372
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
1373
        $process->run();
1374
1375
        // executes after the command finishes
1376
        if (!$process->isSuccessful()) {
1377
            echo $process->getOutput();
1378
            $this->fail('Generated code is not PRS2 compliant');
1379
        }
1380
    }
1381
1382
    /**
1383
     * @depends testDaoGeneration
1384
     */
1385
    public function testFindOneByGeneration()
1386
    {
1387
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1388
        $parameters = $reflectionMethod->getParameters();
1389
1390
        $this->assertCount(2, $parameters);
1391
        $this->assertSame('login', $parameters[0]->getName());
0 ignored issues
show
Bug introduced by
Consider using $parameters[0]->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
1392
        $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
0 ignored issues
show
Bug introduced by
Consider using $parameters[1]->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
1393
    }
1394
1395
    /**
1396
     * @depends testDaoGeneration
1397
     */
1398
    public function testUuid()
1399
    {
1400
        $article = new ArticleBean('content');
1401
        $this->assertSame('content', $article->getContent());
1402
        $this->assertNotEmpty($article->getId());
1403
    }
1404
}
1405