Test Failed
Pull Request — master (#61)
by David
04:28
created

TDBMDaoGeneratorTest::testCloningUuidBean()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 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 Doctrine\DBAL\Exception\UniqueConstraintViolationException;
26
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
27
use Ramsey\Uuid\Uuid;
28
use TheCodingMachine\TDBM\Dao\TestArticleDao;
29
use TheCodingMachine\TDBM\Dao\TestCountryDao;
30
use TheCodingMachine\TDBM\Dao\TestRoleDao;
31
use TheCodingMachine\TDBM\Dao\TestUserDao;
32
use TheCodingMachine\TDBM\Test\Dao\AllNullableDao;
33
use TheCodingMachine\TDBM\Test\Dao\AnimalDao;
34
use TheCodingMachine\TDBM\Test\Dao\Bean\AllNullableBean;
35
use TheCodingMachine\TDBM\Test\Dao\Bean\Article2Bean;
36
use TheCodingMachine\TDBM\Test\Dao\Bean\ArticleBean;
37
use TheCodingMachine\TDBM\Test\Dao\Bean\BoatBean;
38
use TheCodingMachine\TDBM\Test\Dao\Bean\CatBean;
39
use TheCodingMachine\TDBM\Test\Dao\Bean\CategoryBean;
40
use TheCodingMachine\TDBM\Test\Dao\Bean\CountryBean;
41
use TheCodingMachine\TDBM\Test\Dao\Bean\DogBean;
42
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\UserBaseBean;
43
use TheCodingMachine\TDBM\Test\Dao\Bean\PersonBean;
44
use TheCodingMachine\TDBM\Test\Dao\Bean\RoleBean;
45
use TheCodingMachine\TDBM\Test\Dao\Bean\UserBean;
46
use TheCodingMachine\TDBM\Test\Dao\BoatDao;
47
use TheCodingMachine\TDBM\Test\Dao\CatDao;
48
use TheCodingMachine\TDBM\Test\Dao\CategoryDao;
49
use TheCodingMachine\TDBM\Test\Dao\ContactDao;
50
use TheCodingMachine\TDBM\Test\Dao\CountryDao;
51
use TheCodingMachine\TDBM\Test\Dao\DogDao;
52
use TheCodingMachine\TDBM\Test\Dao\Generated\UserBaseDao;
53
use TheCodingMachine\TDBM\Test\Dao\RefNoPrimKeyDao;
54
use TheCodingMachine\TDBM\Test\Dao\RoleDao;
55
use TheCodingMachine\TDBM\Test\Dao\UserDao;
56
use TheCodingMachine\TDBM\Utils\PathFinder\NoPathFoundException;
57
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
58
use Symfony\Component\Process\Process;
59
60
class TDBMDaoGeneratorTest extends TDBMAbstractServiceTest
61
{
62
    /** @var TDBMDaoGenerator $tdbmDaoGenerator */
63
    protected $tdbmDaoGenerator;
64
65
    private $rootPath;
66
67
    protected function setUp()
68
    {
69
        parent::setUp();
70
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
71
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
72
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
73
        $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
74
        $this->rootPath = __DIR__.'/../';
75
        //$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...
76
    }
77
78
    public function testDaoGeneration()
79
    {
80
        // Remove all previously generated files.
81
        $this->recursiveDelete($this->rootPath.'src/Test/Dao/');
82
83
        $this->tdbmDaoGenerator->generateAllDaosAndBeans();
84
85
        // Let's require all files to check they are valid PHP!
86
        // Test the daoFactory
87
        require_once $this->rootPath.'src/Test/Dao/Generated/DaoFactory.php';
88
        // Test the others
89
90
        $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
91
92
        foreach ($beanDescriptors as $beanDescriptor) {
93
            $daoName = $beanDescriptor->getDaoClassName();
94
            $daoBaseName = $beanDescriptor->getBaseDaoClassName();
95
            $beanName = $beanDescriptor->getBeanClassName();
96
            $baseBeanName = $beanDescriptor->getBaseBeanClassName();
97
            require_once $this->rootPath.'src/Test/Dao/Bean/Generated/'.$baseBeanName.'.php';
98
            require_once $this->rootPath.'src/Test/Dao/Bean/'.$beanName.'.php';
99
            require_once $this->rootPath.'src/Test/Dao/Generated/'.$daoBaseName.'.php';
100
            require_once $this->rootPath.'src/Test/Dao/'.$daoName.'.php';
101
        }
102
103
        // Check that pivot tables do not generate DAOs or beans.
104
        $this->assertFalse(class_exists('TheCodingMachine\\TDBM\\Test\\Dao\\RolesRightDao'));
105
    }
106
107
    public function testGenerationException()
108
    {
109
        $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', self::getConnection(), $this->getNamingStrategy());
110
111
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
112
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
113
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
114
        $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
115
        $this->rootPath = __DIR__.'/../../../../';
116
        //$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...
117
118
        $this->expectException(NoPathFoundException::class);
119
        $tdbmDaoGenerator->generateAllDaosAndBeans();
120
    }
121
122
    /**
123
     * Delete a file or recursively delete a directory.
124
     *
125
     * @param string $str Path to file or directory
126
     * @return bool
127
     */
128
    private function recursiveDelete(string $str) : bool
129
    {
130
        if (is_file($str)) {
131
            return @unlink($str);
132
        } elseif (is_dir($str)) {
133
            $scan = glob(rtrim($str, '/') . '/*');
134
            foreach ($scan as $index => $path) {
135
                $this->recursiveDelete($path);
136
            }
137
138
            return @rmdir($str);
139
        }
140
        return false;
141
    }
142
143
    /**
144
     * @depends testDaoGeneration
145
     */
146
    public function testGetBeanClassName()
147
    {
148
        $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
149
    }
150
151
    /**
152
     * @depends testDaoGeneration
153
     */
154
    public function testGetBeanClassNameException()
155
    {
156
        $this->expectException(TDBMInvalidArgumentException::class);
157
        $this->tdbmService->getBeanClassName('not_exists');
158
    }
159
160
    /**
161
     * @depends testDaoGeneration
162
     */
163
    public function testGeneratedGetById()
164
    {
165
        $contactDao = new ContactDao($this->tdbmService);
166
        $contactBean = $contactDao->getById(1);
167
        $this->assertEquals(1, $contactBean->getId());
168
        $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
169
170
        // FIXME: Question: que faire du paramètre stockage "UTC"????
171
    }
172
173
    /**
174
     * @depends testDaoGeneration
175
     */
176
    public function testGeneratedGetByIdLazyLoaded()
177
    {
178
        $roleDao = new RoleDao($this->tdbmService);
179
        $roleBean = $roleDao->getById(1, true);
180
        $this->assertEquals(1, $roleBean->getId());
181
        $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
182
183
        $roleBean2 = $roleDao->getById(1, true);
184
        $this->assertTrue($roleBean === $roleBean2);
185
    }
186
187
    /**
188
     * @depends testDaoGeneration
189
     */
190
    public function testDefaultValueOnNewBean()
191
    {
192
        $roleBean = new RoleBean('my_role');
193
        $this->assertEquals(1, $roleBean->getStatus());
194
    }
195
196
    /**
197
     * @depends testDaoGeneration
198
     */
199 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...
200
    {
201
        $userDao = new UserDao($this->tdbmService);
202
        $userBean = $userDao->getById(1);
203
        $country = $userBean->getCountry();
204
205
        $this->assertEquals('UK', $country->getLabel());
206
207
        $userBean2 = $userDao->getById(1);
208
        $this->assertTrue($userBean === $userBean2);
209
210
        $contactDao = new ContactDao($this->tdbmService);
211
        $contactBean = $contactDao->getById(1);
212
213
        $this->assertTrue($userBean === $contactBean);
214
    }
215
216
    /**
217
     * @depends testDaoGeneration
218
     */
219
    public function testNewBeans()
220
    {
221
        $countryDao = new CountryDao($this->tdbmService);
222
        $userDao = new UserDao($this->tdbmService);
223
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
224
        $userBean->setOrder(1); // Let's set a "protected keyword" column.
225
226
        $userDao->save($userBean);
227
228
        $this->assertNull($userBean->getManager());
229
    }
230
231
    /**
232
     * @depends testDaoGeneration
233
     */
234
    public function testDateTimeImmutableGetter()
235
    {
236
        $userDao = new UserDao($this->tdbmService);
237
        $user = $userDao->getById(1);
238
239
        $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
240
    }
241
242
    /**
243
     * @depends testDaoGeneration
244
     */
245 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...
246
    {
247
        $userDao = new UserDao($this->tdbmService);
248
        $countryBean = new CountryBean('Mexico');
249
        $userBean = new UserBean('Speedy Gonzalez', '[email protected]', $countryBean, 'speedy.gonzalez');
250
        $this->assertEquals($countryBean, $userBean->getCountry());
251
252
        $userDao->save($userBean);
253
    }
254
255
    /**
256
     * @depends testAssigningNewBeans
257
     */
258
    public function testUpdatingProtectedColumn()
259
    {
260
        $userDao = new UserDao($this->tdbmService);
261
        $userBean = $userDao->findOneByLogin('speedy.gonzalez');
262
        $userBean->setOrder(2);
263
        $userDao->save($userBean);
264
    }
265
266
    /**
267
     * @depends testDaoGeneration
268
     */
269 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...
270
    {
271
        $userDao = new UserDao($this->tdbmService);
272
        $user = $userDao->getById(1);
273
        $countryDao = new CountryDao($this->tdbmService);
274
        $country = $countryDao->getById(2);
275
276
        $user->setCountry($country);
277
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
278
    }
279
280
    /**
281
     * @depends testDaoGeneration
282
     */
283
    public function testDirectReversedRelationship()
284
    {
285
        $countryDao = new CountryDao($this->tdbmService);
286
        $country = $countryDao->getById(1);
287
        $users = $country->getUsers();
288
289
        $arr = $users->toArray();
290
291
        $this->assertCount(1, $arr);
292
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
293
        $this->assertEquals('jean.dupont', $arr[0]->getLogin());
294
295
        $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...
296
        $users = $country->getUsers();
297
298
        $arr = $users->toArray();
299
300
        $this->assertCount(2, $arr);
301
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
302
        $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
303
    }
304
305
    /**
306
     * @depends testDaoGeneration
307
     */
308
    public function testDeleteInDirectReversedRelationship()
309
    {
310
        $countryDao = new CountryDao($this->tdbmService);
311
        $country = $countryDao->getById(1);
312
313
        $userDao = new UserDao($this->tdbmService);
314
        $newUser = new UserBean('John Snow', '[email protected]', $country, 'john.snow');
315
        $userDao->save($newUser);
316
317
        $users = $country->getUsers();
318
319
        $arr = $users->toArray();
320
321
        $this->assertCount(2, $arr);
322
323
        $userDao->delete($arr[1]);
324
325
        $users = $country->getUsers();
326
        $arr = $users->toArray();
327
        $this->assertCount(1, $arr);
328
    }
329
330
    /**
331
     * @depends testDaoGeneration
332
     */
333
    public function testJointureGetters()
334
    {
335
        $roleDao = new RoleDao($this->tdbmService);
336
        $role = $roleDao->getById(1);
337
        $users = $role->getUsers();
338
339
        $this->assertCount(2, $users);
340
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
341
342
        $rights = $role->getRights();
343
344
        $this->assertCount(2, $rights);
345
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
346
    }
347
348
    /**
349
     * @depends testDaoGeneration
350
     */
351
    public function testNestedIterationOnAlterableResultIterator()
352
    {
353
        $countryDao = new CountryDao($this->tdbmService);
354
        $country = $countryDao->getById(2);
355
356
        $count = 0;
357
        // Let's perform 2 nested calls to check that iterators do not melt.
358
        foreach ($country->getUsers() as $user) {
359
            foreach ($country->getUsers() as $user2) {
360
                $count++;
361
            }
362
        }
363
        // There are 3 users linked to country 2.
364
        $this->assertSame(9, $count);
365
    }
366
367
    /**
368
     * @depends testDaoGeneration
369
     */
370
    public function testNewBeanConstructor()
371
    {
372
        $role = new RoleBean('Newrole');
373
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
374
    }
375
376
    /**
377
     * @depends testDaoGeneration
378
     */
379
    public function testJointureAdderOnNewBean()
380
    {
381
        $countryDao = new CountryDao($this->tdbmService);
382
        $country = $countryDao->getById(1);
383
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
384
        $role = new RoleBean('Mouse');
385
        $user->addRole($role);
386
        $roles = $user->getRoles();
387
        $this->assertCount(1, $roles);
388
        $role = $roles[0];
389
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
390
        $users = $role->getUsers();
391
        $this->assertCount(1, $users);
392
        $this->assertEquals($user, $users[0]);
393
394
        $role->removeUser($user);
395
        $this->assertCount(0, $role->getUsers());
396
        $this->assertCount(0, $user->getRoles());
397
    }
398
399
    /**
400
     * @depends testDaoGeneration
401
     */
402 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...
403
    {
404
        $roleDao = new RoleDao($this->tdbmService);
405
        $userDao = new UserDao($this->tdbmService);
406
        $role = $roleDao->getById(1);
407
        $user = $userDao->getById(1);
408
409
        // We call removeUser BEFORE calling getUsers
410
        // This should work as expected.
411
        $role->removeUser($user);
412
        $users = $role->getUsers();
413
414
        $this->assertCount(1, $users);
415
    }
416
417
    /**
418
     * @depends testDaoGeneration
419
     */
420
    public function testJointureMultiAdd()
421
    {
422
        $countryDao = new CountryDao($this->tdbmService);
423
        $country = $countryDao->getById(1);
424
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
425
        $role = new RoleBean('Mouse');
426
        $user->addRole($role);
427
        $role->addUser($user);
428
        $user->addRole($role);
429
430
        $this->assertCount(1, $user->getRoles());
431
    }
432
433
    /**
434
     * Step 1: we remove the role 1 from user 1 but save role 1.
435
     * Expected result: no save done.
436
     *
437
     * @depends testDaoGeneration
438
     */
439
    public function testJointureSave1()
440
    {
441
        $roleDao = new RoleDao($this->tdbmService);
442
        $role = $roleDao->getById(1);
443
        $userDao = new UserDao($this->tdbmService);
444
        $user = $userDao->getById(1);
445
446
        $this->assertTrue($user->hasRole($role));
447
        $this->assertTrue($role->hasUser($user));
448
        $user->removeRole($role);
449
        $this->assertFalse($user->hasRole($role));
450
        $this->assertFalse($role->hasUser($user));
451
        $roleDao->save($role);
452
453
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
454
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
455
    }
456
457
    /**
458
     * Step 2: we check that nothing was saved
459
     * Expected result: no save done.
460
     *
461
     * @depends testJointureSave1
462
     */
463
    public function testJointureSave2()
464
    {
465
        $roleDao = new RoleDao($this->tdbmService);
466
        $role = $roleDao->getById(1);
467
        $this->assertCount(2, $role->getUsers());
468
    }
469
470
    /**
471
     * Step 3: we remove the role 1 from user 1 and save user 1.
472
     * Expected result: save done.
473
     *
474
     * @depends testJointureSave2
475
     */
476
    public function testJointureSave3()
477
    {
478
        $roleDao = new RoleDao($this->tdbmService);
479
        $role = $roleDao->getById(1);
480
        $userDao = new UserDao($this->tdbmService);
481
        $user = $userDao->getById(1);
482
483
        $this->assertCount(1, $user->getRoles());
484
        $user->removeRole($role);
485
        $this->assertCount(0, $user->getRoles());
486
        $userDao->save($user);
487
        $this->assertCount(0, $user->getRoles());
488
    }
489
490
    /**
491
     * Step 4: we check that save was done
492
     * Expected result: save done.
493
     *
494
     * @depends testJointureSave3
495
     */
496 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...
497
    {
498
        $roleDao = new RoleDao($this->tdbmService);
499
        $role = $roleDao->getById(1);
500
        $this->assertCount(1, $role->getUsers());
501
        $userDao = new UserDao($this->tdbmService);
502
        $user = $userDao->getById(1);
503
        $this->assertCount(0, $user->getRoles());
504
    }
505
506
    /**
507
     * Step 5: we add the role 1 from user 1 and save user 1.
508
     * Expected result: save done.
509
     *
510
     * @depends testJointureSave4
511
     */
512 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...
513
    {
514
        $roleDao = new RoleDao($this->tdbmService);
515
        $role = $roleDao->getById(1);
516
        $userDao = new UserDao($this->tdbmService);
517
        $user = $userDao->getById(1);
518
519
        $user->addRole($role);
520
        $this->assertCount(1, $user->getRoles());
521
        $userDao->save($user);
522
    }
523
524
    /**
525
     * Step 6: we check that save was done
526
     * Expected result: save done.
527
     *
528
     * @depends testJointureSave5
529
     */
530 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...
531
    {
532
        $roleDao = new RoleDao($this->tdbmService);
533
        $role = $roleDao->getById(1);
534
        $this->assertCount(2, $role->getUsers());
535
        $userDao = new UserDao($this->tdbmService);
536
        $user = $userDao->getById(1);
537
        $this->assertCount(1, $user->getRoles());
538
    }
539
540
    /**
541
     * Step 7: we add a new role to user 1 and save user 1.
542
     * Expected result: save done, including the new role.
543
     *
544
     * @depends testJointureSave6
545
     */
546
    public function testJointureSave7()
547
    {
548
        $role = new RoleBean('my new role');
549
        $userDao = new UserDao($this->tdbmService);
550
        $user = $userDao->getById(1);
551
552
        $user->addRole($role);
553
        $userDao->save($user);
554
555
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
556
    }
557
558
    /**
559
     * Step 8: we check that save was done
560
     * Expected result: save done.
561
     *
562
     * @depends testJointureSave7
563
     */
564 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...
565
    {
566
        $roleDao = new RoleDao($this->tdbmService);
567
        $userDao = new UserDao($this->tdbmService);
568
        $user = $userDao->getById(1);
569
570
        $roles = $user->getRoles();
571
        foreach ($roles as $role) {
572
            if ($role->getName() === 'my new role') {
573
                $selectedRole = $role;
574
                break;
575
            }
576
        }
577
        $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...
578
579
        $this->assertCount(2, $user->getRoles());
580
581
        // Expected: relationship removed!
582
        $roleDao->delete($selectedRole);
583
584
        $this->assertCount(1, $user->getRoles());
585
    }
586
587
    /**
588
     * Step 9: Let's test the setXXX method.
589
     *
590
     * @depends testJointureSave8
591
     */
592
    public function testJointureSave9()
593
    {
594
        $roleDao = new RoleDao($this->tdbmService);
595
        $userDao = new UserDao($this->tdbmService);
596
        $user = $userDao->getById(1);
597
598
        // At this point, user 1 is linked to role 1.
599
        // Let's bind it to role 2.
600
        $user->setRoles([$roleDao->getById(2)]);
601
        $userDao->save($user);
602
    }
603
604
    /**
605
     * Step 10: Let's check results of 9.
606
     *
607
     * @depends testJointureSave9
608
     */
609
    public function testJointureSave10()
610
    {
611
        $userDao = new UserDao($this->tdbmService);
612
        $user = $userDao->getById(1);
613
614
        $roles = $user->getRoles();
615
616
        $this->assertCount(1, $roles);
617
        $this->assertEquals(2, $roles[0]->getId());
618
    }
619
620
    /**
621
     * @depends testDaoGeneration
622
     */
623 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...
624
    {
625
        $userDao = new TestUserDao($this->tdbmService);
626
        $users = $userDao->getUsersByAlphabeticalOrder();
627
628
        $this->assertCount(6, $users);
629
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
630
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
631
632
        $users = $userDao->getUsersByCountryOrder();
633
        $this->assertCount(6, $users);
634
        $countryName1 = $users[0]->getCountry()->getLabel();
635
        for ($i = 1; $i < 6; $i++) {
636
            $countryName2 = $users[$i]->getCountry()->getLabel();
637
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
638
            $countryName1 = $countryName2;
639
        }
640
    }
641
642
    /**
643
     * @depends testDaoGeneration
644
     */
645 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...
646
    {
647
        $userDao = new TestUserDao($this->tdbmService);
648
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
649
650
        $this->assertCount(6, $users);
651
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
652
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
653
654
        $users = $userDao->getUsersFromSqlByCountryOrder();
655
        $this->assertCount(6, $users);
656
        $countryName1 = $users[0]->getCountry()->getLabel();
657
        for ($i = 1; $i < 6; $i++) {
658
            $countryName2 = $users[$i]->getCountry()->getLabel();
659
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
660
            $countryName1 = $countryName2;
661
        }
662
    }
663
664
    /**
665
     * @depends testDaoGeneration
666
     */
667
    public function testFindFromSqlOrderByOnInheritedBean()
668
    {
669
        $articleDao = new TestArticleDao($this->tdbmService);
670
        $articles = $articleDao->getArticlesByUserLogin();
671
672
        foreach ($articles as $article) {
673
            var_dump($article);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($article); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
674
        }
675
        $this->assertCount(0, $articles);
676
    }
677
678
679
    /**
680
     * @depends testDaoGeneration
681
     */
682
    public function testFindFromSqlOrderByJoinRole()
683
    {
684
        $roleDao = new TestRoleDao($this->tdbmService);
685
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
686
687
        $this->assertCount(2, $roles);
688
        $this->assertEquals('Singers', $roles[0]->getName());
689
        $this->assertEquals('Admins', $roles[1]->getName());
690
    }
691
692
    /**
693
     * @depends testDaoGeneration
694
     */
695
    public function testFindFromRawSqlOrderByUserCount()
696
    {
697
        $countryDao = new TestCountryDao($this->tdbmService);
698
        $countries = $countryDao->getCountriesByUserCount();
699
700
        $this->assertCount(4, $countries);
701
        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...
702
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
703
        }
704
    }
705
706
    /**
707
     * @depends testDaoGeneration
708
     */
709 View Code Duplication
    public function testFindFromRawSqlWithUnion()
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...
710
    {
711
        $countryDao = new TestCountryDao($this->tdbmService);
712
        $countries = $countryDao->getCountriesUsingUnion();
713
714
        $this->assertCount(2, $countries);
715
        $this->assertEquals(1, $countries[0]->getId());
716
    }
717
718
    /**
719
     * @depends testDaoGeneration
720
     */
721 View Code Duplication
    public function testFindFromRawSqlWithSimpleQuery()
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...
722
    {
723
        $countryDao = new TestCountryDao($this->tdbmService);
724
        $countries = $countryDao->getCountriesUsingSimpleQuery();
725
726
        $this->assertCount(1, $countries);
727
        $this->assertEquals(1, $countries[0]->getId());
728
    }
729
730
    /**
731
     * @depends testDaoGeneration
732
     */
733 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...
734
    {
735
        $userDao = new TestUserDao($this->tdbmService);
736
        $users = $userDao->getUsersByLoginStartingWith('bill');
737
738
        $this->assertCount(1, $users);
739
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
740
    }
741
742
    /**
743
     * @expectedException \TheCodingMachine\TDBM\TDBMException
744
     * @depends testDaoGeneration
745
     */
746
    public function testFindMode()
747
    {
748
        $userDao = new TestUserDao($this->tdbmService);
749
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
750
751
        $users[0];
752
    }
753
754
    /**
755
     * @depends testDaoGeneration
756
     */
757
    public function testFindAll()
758
    {
759
        $userDao = new TestUserDao($this->tdbmService);
760
        $users = $userDao->findAll();
761
762
        $this->assertCount(6, $users);
763
    }
764
765
    /**
766
     * @depends testDaoGeneration
767
     */
768
    public function testFindOne()
769
    {
770
        $userDao = new TestUserDao($this->tdbmService);
771
        $user = $userDao->getUserByLogin('bill.shakespeare');
772
773
        $this->assertEquals('bill.shakespeare', $user->getLogin());
774
    }
775
776
    /**
777
     * @depends testDaoGeneration
778
     */
779
    public function testJsonEncodeBean()
780
    {
781
        $userDao = new TestUserDao($this->tdbmService);
782
        $user = $userDao->getUserByLogin('bill.shakespeare');
783
784
        $jsonEncoded = json_encode($user);
785
        $userDecoded = json_decode($jsonEncoded, true);
786
787
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
788
789
        // test serialization of dates.
790
        $this->assertTrue(is_string($userDecoded['createdAt']));
791
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
792
        $this->assertNull($userDecoded['modifiedAt']);
793
794
        // testing many to 1 relationships
795
        $this->assertEquals('UK', $userDecoded['country']['label']);
796
797
        // testing many to many relationships
798
        $this->assertCount(1, $userDecoded['roles']);
799
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
800
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
801
    }
802
803
    /**
804
     * @depends testDaoGeneration
805
     */
806
    public function testNullableForeignKey()
807
    {
808
        $userDao = new TestUserDao($this->tdbmService);
809
        $user = $userDao->getUserByLogin('john.smith');
810
811
        $this->assertNull(null, $user->getManager());
812
813
        $jsonEncoded = json_encode($user);
814
        $userDecoded = json_decode($jsonEncoded, true);
815
816
        $this->assertNull(null, $userDecoded['manager']);
817
    }
818
819
    /**
820
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
821
     *
822
     * @depends testDaoGeneration
823
     */
824
    public function testSetToNullForeignKey()
825
    {
826
        $userDao = new TestUserDao($this->tdbmService);
827
        $user = $userDao->getUserByLogin('john.smith');
828
        $manager = $userDao->getUserByLogin('jean.dupont');
829
830
        $user->setManager($manager);
831
        $userDao->save($user);
832
833
        $user->setManager(null);
834
        $userDao->save($user);
835
    }
836
837
    /**
838
     * @depends testDaoGeneration
839
     * @expectedException \Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException
840
     * @expectedExceptionMessage Could not find table 'contacts'. Did you mean 'contact'?
841
     */
842
    public function testQueryOnWrongTableName()
843
    {
844
        $userDao = new TestUserDao($this->tdbmService);
845
        $users = $userDao->getUsersWrongTableName();
846
        $users->count();
847
    }
848
849
    /**
850
     * @depends testDaoGeneration
851
     */
852
    /*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...
853
    {
854
        $userDao = new TestUserDao($this->tdbmService);
855
        $users = $userDao->getUsersByManagerId(null);
856
        $this->assertCount(3, $users);
857
    }*/
858
859
    /**
860
     * @depends testDaoGeneration
861
     */
862
    public function testInnerJsonEncode()
863
    {
864
        $userDao = new TestUserDao($this->tdbmService);
865
        $user = $userDao->getUserByLogin('bill.shakespeare');
866
867
        $jsonEncoded = json_encode(['user' => $user]);
868
        $msgDecoded = json_decode($jsonEncoded, true);
869
870
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
871
    }
872
873
    /**
874
     * @depends testDaoGeneration
875
     */
876 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...
877
    {
878
        $userDao = new TestUserDao($this->tdbmService);
879
        $users = $userDao->getUsersByLoginStartingWith('bill');
880
881
        $jsonEncoded = json_encode($users);
882
        $msgDecoded = json_decode($jsonEncoded, true);
883
884
        $this->assertCount(1, $msgDecoded);
885
    }
886
887
    /**
888
     * @depends testDaoGeneration
889
     */
890 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...
891
    {
892
        $userDao = new TestUserDao($this->tdbmService);
893
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
894
895
        $jsonEncoded = json_encode($users);
896
        $msgDecoded = json_decode($jsonEncoded, true);
897
898
        $this->assertCount(1, $msgDecoded);
899
    }
900
901
    /**
902
     * @depends testDaoGeneration
903
     */
904 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...
905
    {
906
        $userDao = new TestUserDao($this->tdbmService);
907
        $users = $userDao->getUsersByLoginStartingWith('bill');
908
909
        $jsonEncoded = json_encode($users->take(0, 1));
910
        $msgDecoded = json_decode($jsonEncoded, true);
911
912
        $this->assertCount(1, $msgDecoded);
913
    }
914
915
    /**
916
     * @depends testDaoGeneration
917
     */
918 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...
919
    {
920
        $userDao = new TestUserDao($this->tdbmService);
921
        $users = $userDao->getUsersByLoginStartingWith('bill');
922
923
        $bill = $users->first();
924
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
925
    }
926
927
    /**
928
     * @depends testDaoGeneration
929
     */
930
    public function testFirstNull()
931
    {
932
        $userDao = new TestUserDao($this->tdbmService);
933
        $users = $userDao->getUsersByLoginStartingWith('mike');
934
935
        $user = $users->first();
936
        $this->assertNull($user);
937
    }
938
939
    /**
940
     * @depends testDaoGeneration
941
     */
942
    public function testCloneBeanAttachedBean()
943
    {
944
        $userDao = new TestUserDao($this->tdbmService);
945
        $user = $userDao->getUserByLogin('bill.shakespeare');
946
        $this->assertEquals(4, $user->getId());
947
        $user2 = clone $user;
948
        $this->assertNull($user2->getId());
949
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
950
        $this->assertEquals('Bill Shakespeare', $user2->getName());
951
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
952
953
        // MANY 2 MANY must be duplicated
954
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
955
956
        // Let's test saving this clone
957
        $user2->setLogin('william.shakespeare');
958
        $userDao->save($user2);
959
960
        $user3 = $userDao->getUserByLogin('william.shakespeare');
961
        $this->assertTrue($user3 === $user2);
962
        $userDao->delete($user3);
963
964
        // Finally, let's test the origin user still exists!
965
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
966
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
967
    }
968
969
    /**
970
     * @depends testDaoGeneration
971
     */
972
    public function testCloneNewBean()
973
    {
974
        $countryDao = new CountryDao($this->tdbmService);
975
        $roleDao = new RoleDao($this->tdbmService);
976
        $role = $roleDao->getById(1);
977
978
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
979
        $userBean->addRole($role);
980
981
        $user2 = clone $userBean;
982
983
        $this->assertNull($user2->getId());
984
        $this->assertEquals('john.doe', $user2->getLogin());
985
        $this->assertEquals('John Doe', $user2->getName());
986
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
987
988
        // MANY 2 MANY must be duplicated
989
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
990
    }
991
992
    /**
993
     * @depends testDaoGeneration
994
     */
995
    public function testCascadeDelete()
996
    {
997
        $userDao = new TestUserDao($this->tdbmService);
998
        $countryDao = new CountryDao($this->tdbmService);
999
1000
        $spain = new CountryBean('Spain');
1001
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1002
1003
        $countryDao->save($spain);
1004
        $userDao->save($sanchez);
1005
1006
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1007
        $this->assertTrue($sanchez === $speedy2);
1008
1009
        $exceptionTriggered = false;
1010
        try {
1011
            $countryDao->delete($spain);
1012
        } catch (ForeignKeyConstraintViolationException $e) {
1013
            $exceptionTriggered = true;
1014
        }
1015
        $this->assertTrue($exceptionTriggered);
1016
1017
        $countryDao->delete($spain, true);
1018
1019
        // Let's check that speed gonzalez was removed.
1020
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1021
        $this->assertNull($speedy3);
1022
    }
1023
1024
    /**
1025
     * @depends testDaoGeneration
1026
     */
1027
    public function testDiscardChanges()
1028
    {
1029
        $contactDao = new ContactDao($this->tdbmService);
1030
        $contactBean = $contactDao->getById(1);
1031
1032
        $oldName = $contactBean->getName();
1033
1034
        $contactBean->setName('MyNewName');
1035
1036
        $contactBean->discardChanges();
1037
1038
        $this->assertEquals($oldName, $contactBean->getName());
1039
    }
1040
1041
    /**
1042
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1043
     * @depends testDaoGeneration
1044
     */
1045
    public function testDiscardChangesOnNewBeanFails()
1046
    {
1047
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1048
        $person->discardChanges();
1049
    }
1050
1051
    /**
1052
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1053
     * @depends testDaoGeneration
1054
     */
1055
    public function testDiscardChangesOnDeletedBeanFails()
1056
    {
1057
        $userDao = new TestUserDao($this->tdbmService);
1058
        $countryDao = new CountryDao($this->tdbmService);
1059
1060
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1061
1062
        $userDao->save($sanchez);
1063
1064
        $userDao->delete($sanchez);
1065
1066
        // Cannot discard changes on a bean that is already deleted.
1067
        $sanchez->discardChanges();
1068
    }
1069
1070
    /**
1071
     * @depends testDaoGeneration
1072
     */
1073 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...
1074
    {
1075
        $userDao = new UserDao($this->tdbmService);
1076
        $user = $userDao->findOneByLogin('bill.shakespeare');
1077
1078
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1079
        $this->assertEquals('Bill Shakespeare', $user->getName());
1080
    }
1081
1082
    /**
1083
     * @depends testDaoGeneration
1084
     */
1085
    public function testFindOneByRetunsNull()
1086
    {
1087
        // Let's assert that the findOneBy... methods can return null.
1088
        $userDao = new UserDao($this->tdbmService);
1089
        $userBean = $userDao->findOneByLogin('not_exist');
1090
1091
        $this->assertNull($userBean);
1092
    }
1093
1094
    /**
1095
     * @depends testDaoGeneration
1096
     */
1097 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...
1098
    {
1099
        $countryDao = new CountryDao($this->tdbmService);
1100
        $userDao = new UserDao($this->tdbmService);
1101
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1102
1103
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1104
    }
1105
1106
    /**
1107
     * @depends testDaoGeneration
1108
     */
1109
    public function testCreationInNullableDate()
1110
    {
1111
        $roleDao = new RoleDao($this->tdbmService);
1112
1113
        $role = new RoleBean('newbee');
1114
        $roleDao->save($role);
1115
1116
        $this->assertNull($role->getCreatedAt());
1117
    }
1118
1119
    /**
1120
     * @depends testDaoGeneration
1121
     */
1122
    public function testUpdateInNullableDate()
1123
    {
1124
        $roleDao = new RoleDao($this->tdbmService);
1125
1126
        $role = new RoleBean('newbee');
1127
        $roleDao->save($role);
1128
1129
        $role->setCreatedAt(null);
1130
        $roleDao->save($role);
1131
        $this->assertNull($role->getCreatedAt());
1132
    }
1133
1134
    /**
1135
     * @depends testDaoGeneration
1136
     */
1137
    public function testFindFromSql()
1138
    {
1139
        $roleDao = new TestRoleDao($this->tdbmService);
1140
1141
        $roles = $roleDao->getRolesByRightCanSing();
1142
        $this->assertCount(2, $roles);
1143
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1144
    }
1145
1146
    /**
1147
     * @depends testDaoGeneration
1148
     */
1149
    public function testFindOneFromSql()
1150
    {
1151
        $roleDao = new TestRoleDao($this->tdbmService);
1152
1153
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1154
        $this->assertInstanceOf(RoleBean::class, $role);
1155
    }
1156
1157
    /**
1158
     * @depends testDaoGeneration
1159
     */
1160
    public function testCreateEmptyExtendedBean()
1161
    {
1162
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1163
1164
        $dogDao = new DogDao($this->tdbmService);
1165
1166
        // We are not filling no field that is part of dog table.
1167
        $dog = new DogBean('Youki');
1168
        $dog->setOrder(1);
1169
1170
        $dogDao->save($dog);
1171
    }
1172
1173
    /**
1174
     * @depends testCreateEmptyExtendedBean
1175
     */
1176
    public function testFetchEmptyExtendedBean()
1177
    {
1178
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1179
1180
        $animalDao = new AnimalDao($this->tdbmService);
1181
1182
        // We are not filling no field that is part of dog table.
1183
        $animalBean = $animalDao->getById(1);
1184
1185
        $this->assertInstanceOf(DogBean::class, $animalBean);
1186
    }
1187
1188
    /**
1189
     * @depends testDaoGeneration
1190
     */
1191
    public function testTwoBranchesHierarchy()
1192
    {
1193
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1194
1195
        $catDao = new CatDao($this->tdbmService);
1196
1197
        // We are not filling no field that is part of dog table.
1198
        $cat = new CatBean('Mew');
1199
        $cat->setOrder(2);
1200
1201
        $catDao->save($cat);
1202
    }
1203
1204
    /**
1205
     * @depends testTwoBranchesHierarchy
1206
     */
1207
    public function testFetchTwoBranchesHierarchy()
1208
    {
1209
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1210
1211
        $animalDao = new AnimalDao($this->tdbmService);
1212
1213
        $animalBean = $animalDao->getById(2);
1214
1215
        $this->assertInstanceOf(CatBean::class, $animalBean);
1216
        /* @var $animalBean CatBean */
1217
        $animalBean->setCutenessLevel(999);
1218
1219
        $animalDao->save($animalBean);
1220
    }
1221
1222
    /**
1223
     * @depends testDaoGeneration
1224
     */
1225
    public function testExceptionOnGetById()
1226
    {
1227
        $countryDao = new CountryDao($this->tdbmService);
1228
        $this->expectException(\TypeError::class);
1229
        $countryDao->getById(null);
1230
    }
1231
1232
    /**
1233
     * @depends testDaoGeneration
1234
     */
1235
    public function testDisconnectedManyToOne()
1236
    {
1237
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1238
1239
        $country = new CountryBean('Spain');
1240
1241
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1242
1243
        $this->assertCount(1, $country->getUsers());
1244
        $this->assertSame($user, $country->getUsers()[0]);
1245
    }
1246
1247
    /**
1248
     * @depends testDaoGeneration
1249
     */
1250 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...
1251
    {
1252
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1253
1254
        $userDao = new TestUserDao($this->tdbmService);
1255
        $users = $userDao->getUsersByCountryName();
1256
1257
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1258
    }
1259
1260
    /**
1261
     * @depends testDaoGeneration
1262
     */
1263
    public function testResultIteratorSort()
1264
    {
1265
        $userDao = new UserDao($this->tdbmService);
1266
        $users = $userDao->findAll()->withOrder('country.label DESC');
1267
1268
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1269
1270
        $users = $users->withOrder('country.label ASC');
1271
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1272
    }
1273
1274
    /**
1275
     * @depends testDaoGeneration
1276
     */
1277
    public function testResultIteratorWithParameters()
1278
    {
1279
        $userDao = new TestUserDao($this->tdbmService);
1280
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1281
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1282
1283
        $users = $users->withParameters(['login' => 'jean%']);
1284
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1285
    }
1286
1287
    /**
1288
     * @depends testDaoGeneration
1289
     */
1290 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...
1291
    {
1292
        $userDao = new TestUserDao($this->tdbmService);
1293
        $users = $userDao->getUsersByReversedCountryName();
1294
1295
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1296
    }
1297
1298
    /**
1299
     * @depends testDaoGeneration
1300
     */
1301
    public function testOrderByException()
1302
    {
1303
        $userDao = new TestUserDao($this->tdbmService);
1304
        $users = $userDao->getUsersByInvalidOrderBy();
1305
        $this->expectException(TDBMInvalidArgumentException::class);
1306
        $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...
1307
    }
1308
1309
    /**
1310
     * @depends testDaoGeneration
1311
     */
1312
    public function testOrderByProtectedColumn()
1313
    {
1314
        $animalDao = new AnimalDao($this->tdbmService);
1315
        $animals = $animalDao->findAll();
1316
        $animals = $animals->withOrder('`order` ASC');
1317
1318
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1319
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1320
1321
        $animals = $animals->withOrder('`order` DESC');
1322
1323
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1324
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1325
    }
1326
1327
    /**
1328
     * @depends testDaoGeneration
1329
     */
1330
    public function testGetOnAllNullableValues()
1331
    {
1332
        // Tests that a get performed on a column that has only nullable fields succeeds.
1333
        $allNullable = new AllNullableBean();
1334
        $this->assertNull($allNullable->getId());
1335
        $this->assertNull($allNullable->getLabel());
1336
        $this->assertNull($allNullable->getCountry());
1337
    }
1338
1339
    /**
1340
     * @depends testDaoGeneration
1341
     */
1342
    public function testExceptionOnMultipleInheritance()
1343
    {
1344
        $connection = self::getConnection();
1345
        self::insert($connection, 'animal', [
1346
            'id' => 99, 'name' => 'Snoofield',
1347
        ]);
1348
        self::insert($connection, 'dog', [
1349
            'id' => 99, 'race' => 'dog',
1350
        ]);
1351
        self::insert($connection, 'cat', [
1352
            'id' => 99, 'cuteness_level' => 0,
1353
        ]);
1354
1355
        $catched = false;
1356
        try {
1357
            $animalDao = new AnimalDao($this->tdbmService);
1358
            $animalDao->getById(99);
1359
        } catch (TDBMInheritanceException $e) {
1360
            $catched = true;
1361
        }
1362
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1363
1364
        self::delete($connection, 'cat', ['id' => 99]);
1365
        self::delete($connection, 'dog', ['id' => 99]);
1366
        self::delete($connection, 'animal', ['id' => 99]);
1367
    }
1368
1369
    /**
1370
     * @depends testDaoGeneration
1371
     */
1372
    public function testReferenceNotSaved()
1373
    {
1374
        $boatDao = new BoatDao($this->tdbmService);
1375
1376
        $country = new CountryBean('Atlantis');
1377
        $boat = new BoatBean($country, 'Titanic');
1378
1379
        $boatDao->save($boat);
1380
    }
1381
1382
    /**
1383
     * @depends testDaoGeneration
1384
     */
1385
    public function testReferenceDeleted()
1386
    {
1387
        $countryDao = new CountryDao($this->tdbmService);
1388
        $boatDao = new BoatDao($this->tdbmService);
1389
1390
        $country = new CountryBean('Atlantis');
1391
        $countryDao->save($country);
1392
1393
        $boat = new BoatBean($country, 'Titanic');
1394
        $countryDao->delete($country);
1395
1396
        $this->expectException(TDBMMissingReferenceException::class);
1397
        $boatDao->save($boat);
1398
    }
1399
1400
    /**
1401
     * @depends testDaoGeneration
1402
     */
1403 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...
1404
    {
1405
        $userDao = new UserDao($this->tdbmService);
1406
1407
        $country = new CountryBean('Norrisland');
1408
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1409
1410
        $user->setManager($user);
1411
1412
        $this->expectException(TDBMCyclicReferenceException::class);
1413
        $userDao->save($user);
1414
    }
1415
1416
    /**
1417
     * @depends testDaoGeneration
1418
     */
1419
    public function testCyclicReference()
1420
    {
1421
        $categoryDao = new CategoryDao($this->tdbmService);
1422
1423
        $category = new CategoryBean('Root');
1424
1425
        $category->setParent($category);
1426
1427
        $this->expectException(TDBMCyclicReferenceException::class);
1428
        $categoryDao->save($category);
1429
    }
1430
1431
    /**
1432
     * @depends testDaoGeneration
1433
     */
1434
    public function testCorrectTypeForPrimaryKeyAfterSave()
1435
    {
1436
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1437
        $this->onlyMySql();
1438
1439
        $allNullableDao = new AllNullableDao($this->tdbmService);
1440
        $allNullable = new AllNullableBean();
1441
        $allNullableDao->save($allNullable);
1442
        $id = $allNullable->getId();
1443
1444
        $this->assertTrue(is_int($id));
1445
    }
1446
1447
    /**
1448
     * @depends testDaoGeneration
1449
     */
1450
    public function testPSR2Compliance()
1451
    {
1452
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
1453
        $process->run();
1454
1455
        // executes after the command finishes
1456
        if (!$process->isSuccessful()) {
1457
            echo $process->getOutput();
1458
            $this->fail('Generated code is not PRS2 compliant');
1459
        }
1460
    }
1461
1462
    /**
1463
     * @depends testDaoGeneration
1464
     */
1465
    public function testFindOneByGeneration()
1466
    {
1467
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1468
        $parameters = $reflectionMethod->getParameters();
1469
1470
        $this->assertCount(2, $parameters);
1471
        $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...
1472
        $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...
1473
    }
1474
1475
    /**
1476
     * @depends testDaoGeneration
1477
     */
1478 View Code Duplication
    public function testUuid()
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...
1479
    {
1480
        $article = new ArticleBean('content');
1481
        $this->assertSame('content', $article->getContent());
1482
        $this->assertNotEmpty($article->getId());
1483
        $uuid = Uuid::fromString($article->getId());
1484
        $this->assertSame(1, $uuid->getVersion());
1485
    }
1486
1487
    /**
1488
     * @depends testDaoGeneration
1489
     */
1490 View Code Duplication
    public function testUuidv4()
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...
1491
    {
1492
        $article = new Article2Bean('content');
1493
        $this->assertSame('content', $article->getContent());
1494
        $this->assertNotEmpty($article->getId());
1495
        $uuid = Uuid::fromString($article->getId());
1496
        $this->assertSame(4, $uuid->getVersion());
1497
    }
1498
1499
    /**
1500
     * @depends testDaoGeneration
1501
     */
1502
    public function testTypeHintedConstructors()
1503
    {
1504
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1505
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1506
1507
        $this->assertSame('string', (string) $nameParam->getType());
1508
    }
1509
1510
    /**
1511
     * @depends testDaoGeneration
1512
     */
1513
    public function testSaveTransaction()
1514
    {
1515
        $countryDao = new CountryDao($this->tdbmService);
1516
1517
        $boatDao = new BoatDao($this->tdbmService);
1518
        $boatBean = $boatDao->getById(1);
1519
        $boatBean->setName('Bismark');
1520
1521
        $boatBean->getCountry();
1522
1523
        // Let's insert a row without telling TDBM to trigger an error!
1524
        self::insert($this->getConnection(), 'sailed_countries', [
1525
            'boat_id' => 1,
1526
            'country_id' => 2
1527
        ]);
1528
1529
        $boatBean->addCountry($countryDao->getById(2));
1530
1531
        $this->expectException(UniqueConstraintViolationException::class);
1532
1533
        $boatDao->save($boatBean);
1534
    }
1535
1536
    /**
1537
     * @depends testSaveTransaction
1538
     */
1539
    public function testSaveTransaction2()
1540
    {
1541
        $boatDao = new BoatDao($this->tdbmService);
1542
        $boatBean = $boatDao->getById(1);
1543
1544
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1545
        $this->assertNotSame('Bismark', $boatBean->getName());
1546
    }
1547
1548
    /**
1549
     * @depends testDaoGeneration
1550
     */
1551
    public function testForeignKeyPointingToNonPrimaryKey()
1552
    {
1553
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1554
        $bean = $dao->getById(1);
1555
1556
        $this->assertSame('foo', $bean->getFrom()->getTo());
1557
    }
1558
1559
    /**
1560
     * @depends testDaoGeneration
1561
     */
1562
    public function testCloningUuidBean()
1563
    {
1564
        $article = new ArticleBean('content');
1565
        $this->assertNotEmpty($article->getId());
1566
        $article2 = clone $article;
1567
        $this->assertNotEmpty($article2->getId());
1568
        $this->assertNotSame($article->getId(), $article2->getId());
1569
    }
1570
}
1571