Test Failed
Pull Request — master (#60)
by David
02:47
created

TDBMDaoGeneratorTest::testJointureSave9()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
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 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
        $this->assertSame(6, $count);
364
    }
365
366
    /**
367
     * @depends testDaoGeneration
368
     */
369
    public function testNewBeanConstructor()
370
    {
371
        $role = new RoleBean('Newrole');
372
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
373
    }
374
375
    /**
376
     * @depends testDaoGeneration
377
     */
378
    public function testJointureAdderOnNewBean()
379
    {
380
        $countryDao = new CountryDao($this->tdbmService);
381
        $country = $countryDao->getById(1);
382
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
383
        $role = new RoleBean('Mouse');
384
        $user->addRole($role);
385
        $roles = $user->getRoles();
386
        $this->assertCount(1, $roles);
387
        $role = $roles[0];
388
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
389
        $users = $role->getUsers();
390
        $this->assertCount(1, $users);
391
        $this->assertEquals($user, $users[0]);
392
393
        $role->removeUser($user);
394
        $this->assertCount(0, $role->getUsers());
395
        $this->assertCount(0, $user->getRoles());
396
    }
397
398
    /**
399
     * @depends testDaoGeneration
400
     */
401 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...
402
    {
403
        $roleDao = new RoleDao($this->tdbmService);
404
        $userDao = new UserDao($this->tdbmService);
405
        $role = $roleDao->getById(1);
406
        $user = $userDao->getById(1);
407
408
        // We call removeUser BEFORE calling getUsers
409
        // This should work as expected.
410
        $role->removeUser($user);
411
        $users = $role->getUsers();
412
413
        $this->assertCount(1, $users);
414
    }
415
416
    /**
417
     * @depends testDaoGeneration
418
     */
419
    public function testJointureMultiAdd()
420
    {
421
        $countryDao = new CountryDao($this->tdbmService);
422
        $country = $countryDao->getById(1);
423
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
424
        $role = new RoleBean('Mouse');
425
        $user->addRole($role);
426
        $role->addUser($user);
427
        $user->addRole($role);
428
429
        $this->assertCount(1, $user->getRoles());
430
    }
431
432
    /**
433
     * Step 1: we remove the role 1 from user 1 but save role 1.
434
     * Expected result: no save done.
435
     *
436
     * @depends testDaoGeneration
437
     */
438
    public function testJointureSave1()
439
    {
440
        $roleDao = new RoleDao($this->tdbmService);
441
        $role = $roleDao->getById(1);
442
        $userDao = new UserDao($this->tdbmService);
443
        $user = $userDao->getById(1);
444
445
        $this->assertTrue($user->hasRole($role));
446
        $this->assertTrue($role->hasUser($user));
447
        $user->removeRole($role);
448
        $this->assertFalse($user->hasRole($role));
449
        $this->assertFalse($role->hasUser($user));
450
        $roleDao->save($role);
451
452
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
453
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
454
    }
455
456
    /**
457
     * Step 2: we check that nothing was saved
458
     * Expected result: no save done.
459
     *
460
     * @depends testJointureSave1
461
     */
462
    public function testJointureSave2()
463
    {
464
        $roleDao = new RoleDao($this->tdbmService);
465
        $role = $roleDao->getById(1);
466
        $this->assertCount(2, $role->getUsers());
467
    }
468
469
    /**
470
     * Step 3: we remove the role 1 from user 1 and save user 1.
471
     * Expected result: save done.
472
     *
473
     * @depends testJointureSave2
474
     */
475
    public function testJointureSave3()
476
    {
477
        $roleDao = new RoleDao($this->tdbmService);
478
        $role = $roleDao->getById(1);
479
        $userDao = new UserDao($this->tdbmService);
480
        $user = $userDao->getById(1);
481
482
        $this->assertCount(1, $user->getRoles());
483
        $user->removeRole($role);
484
        $this->assertCount(0, $user->getRoles());
485
        $userDao->save($user);
486
        $this->assertCount(0, $user->getRoles());
487
    }
488
489
    /**
490
     * Step 4: we check that save was done
491
     * Expected result: save done.
492
     *
493
     * @depends testJointureSave3
494
     */
495 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...
496
    {
497
        $roleDao = new RoleDao($this->tdbmService);
498
        $role = $roleDao->getById(1);
499
        $this->assertCount(1, $role->getUsers());
500
        $userDao = new UserDao($this->tdbmService);
501
        $user = $userDao->getById(1);
502
        $this->assertCount(0, $user->getRoles());
503
    }
504
505
    /**
506
     * Step 5: we add the role 1 from user 1 and save user 1.
507
     * Expected result: save done.
508
     *
509
     * @depends testJointureSave4
510
     */
511 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...
512
    {
513
        $roleDao = new RoleDao($this->tdbmService);
514
        $role = $roleDao->getById(1);
515
        $userDao = new UserDao($this->tdbmService);
516
        $user = $userDao->getById(1);
517
518
        $user->addRole($role);
519
        $this->assertCount(1, $user->getRoles());
520
        $userDao->save($user);
521
    }
522
523
    /**
524
     * Step 6: we check that save was done
525
     * Expected result: save done.
526
     *
527
     * @depends testJointureSave5
528
     */
529 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...
530
    {
531
        $roleDao = new RoleDao($this->tdbmService);
532
        $role = $roleDao->getById(1);
533
        $this->assertCount(2, $role->getUsers());
534
        $userDao = new UserDao($this->tdbmService);
535
        $user = $userDao->getById(1);
536
        $this->assertCount(1, $user->getRoles());
537
    }
538
539
    /**
540
     * Step 7: we add a new role to user 1 and save user 1.
541
     * Expected result: save done, including the new role.
542
     *
543
     * @depends testJointureSave6
544
     */
545
    public function testJointureSave7()
546
    {
547
        $role = new RoleBean('my new role');
548
        $userDao = new UserDao($this->tdbmService);
549
        $user = $userDao->getById(1);
550
551
        $user->addRole($role);
552
        $userDao->save($user);
553
554
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
555
    }
556
557
    /**
558
     * Step 8: we check that save was done
559
     * Expected result: save done.
560
     *
561
     * @depends testJointureSave7
562
     */
563 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...
564
    {
565
        $roleDao = new RoleDao($this->tdbmService);
566
        $userDao = new UserDao($this->tdbmService);
567
        $user = $userDao->getById(1);
568
569
        $roles = $user->getRoles();
570
        foreach ($roles as $role) {
571
            if ($role->getName() === 'my new role') {
572
                $selectedRole = $role;
573
                break;
574
            }
575
        }
576
        $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...
577
578
        $this->assertCount(2, $user->getRoles());
579
580
        // Expected: relationship removed!
581
        $roleDao->delete($selectedRole);
582
583
        $this->assertCount(1, $user->getRoles());
584
    }
585
586
    /**
587
     * Step 9: Let's test the setXXX method.
588
     *
589
     * @depends testJointureSave8
590
     */
591
    public function testJointureSave9()
592
    {
593
        $roleDao = new RoleDao($this->tdbmService);
594
        $userDao = new UserDao($this->tdbmService);
595
        $user = $userDao->getById(1);
596
597
        // At this point, user 1 is linked to role 1.
598
        // Let's bind it to role 2.
599
        $user->setRoles([$roleDao->getById(2)]);
600
        $userDao->save($user);
601
    }
602
603
    /**
604
     * Step 10: Let's check results of 9.
605
     *
606
     * @depends testJointureSave9
607
     */
608
    public function testJointureSave10()
609
    {
610
        $userDao = new UserDao($this->tdbmService);
611
        $user = $userDao->getById(1);
612
613
        $roles = $user->getRoles();
614
615
        $this->assertCount(1, $roles);
616
        $this->assertEquals(2, $roles[0]->getId());
617
    }
618
619
    /**
620
     * @depends testDaoGeneration
621
     */
622 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...
623
    {
624
        $userDao = new TestUserDao($this->tdbmService);
625
        $users = $userDao->getUsersByAlphabeticalOrder();
626
627
        $this->assertCount(6, $users);
628
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
629
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
630
631
        $users = $userDao->getUsersByCountryOrder();
632
        $this->assertCount(6, $users);
633
        $countryName1 = $users[0]->getCountry()->getLabel();
634
        for ($i = 1; $i < 6; $i++) {
635
            $countryName2 = $users[$i]->getCountry()->getLabel();
636
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
637
            $countryName1 = $countryName2;
638
        }
639
    }
640
641
    /**
642
     * @depends testDaoGeneration
643
     */
644 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...
645
    {
646
        $userDao = new TestUserDao($this->tdbmService);
647
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
648
649
        $this->assertCount(6, $users);
650
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
651
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
652
653
        $users = $userDao->getUsersFromSqlByCountryOrder();
654
        $this->assertCount(6, $users);
655
        $countryName1 = $users[0]->getCountry()->getLabel();
656
        for ($i = 1; $i < 6; $i++) {
657
            $countryName2 = $users[$i]->getCountry()->getLabel();
658
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
659
            $countryName1 = $countryName2;
660
        }
661
    }
662
663
    /**
664
     * @depends testDaoGeneration
665
     */
666
    public function testFindFromSqlOrderByOnInheritedBean()
667
    {
668
        $articleDao = new TestArticleDao($this->tdbmService);
669
        $articles = $articleDao->getArticlesByUserLogin();
670
671
        foreach ($articles as $article) {
672
            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...
673
        }
674
        $this->assertCount(0, $articles);
675
    }
676
677
678
    /**
679
     * @depends testDaoGeneration
680
     */
681
    public function testFindFromSqlOrderByJoinRole()
682
    {
683
        $roleDao = new TestRoleDao($this->tdbmService);
684
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
685
686
        $this->assertCount(2, $roles);
687
        $this->assertEquals('Singers', $roles[0]->getName());
688
        $this->assertEquals('Admins', $roles[1]->getName());
689
    }
690
691
    /**
692
     * @depends testDaoGeneration
693
     */
694
    public function testFindFromRawSqlOrderByUserCount()
695
    {
696
        $countryDao = new TestCountryDao($this->tdbmService);
697
        $countries = $countryDao->getCountriesByUserCount();
698
699
        $this->assertCount(4, $countries);
700
        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...
701
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
702
        }
703
    }
704
705
    /**
706
     * @depends testDaoGeneration
707
     */
708 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...
709
    {
710
        $countryDao = new TestCountryDao($this->tdbmService);
711
        $countries = $countryDao->getCountriesUsingUnion();
712
713
        $this->assertCount(2, $countries);
714
        $this->assertEquals(1, $countries[0]->getId());
715
    }
716
717
    /**
718
     * @depends testDaoGeneration
719
     */
720 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...
721
    {
722
        $countryDao = new TestCountryDao($this->tdbmService);
723
        $countries = $countryDao->getCountriesUsingSimpleQuery();
724
725
        $this->assertCount(1, $countries);
726
        $this->assertEquals(1, $countries[0]->getId());
727
    }
728
729
    /**
730
     * @depends testDaoGeneration
731
     */
732 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...
733
    {
734
        $userDao = new TestUserDao($this->tdbmService);
735
        $users = $userDao->getUsersByLoginStartingWith('bill');
736
737
        $this->assertCount(1, $users);
738
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
739
    }
740
741
    /**
742
     * @expectedException \TheCodingMachine\TDBM\TDBMException
743
     * @depends testDaoGeneration
744
     */
745
    public function testFindMode()
746
    {
747
        $userDao = new TestUserDao($this->tdbmService);
748
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
749
750
        $users[0];
751
    }
752
753
    /**
754
     * @depends testDaoGeneration
755
     */
756
    public function testFindAll()
757
    {
758
        $userDao = new TestUserDao($this->tdbmService);
759
        $users = $userDao->findAll();
760
761
        $this->assertCount(6, $users);
762
    }
763
764
    /**
765
     * @depends testDaoGeneration
766
     */
767
    public function testFindOne()
768
    {
769
        $userDao = new TestUserDao($this->tdbmService);
770
        $user = $userDao->getUserByLogin('bill.shakespeare');
771
772
        $this->assertEquals('bill.shakespeare', $user->getLogin());
773
    }
774
775
    /**
776
     * @depends testDaoGeneration
777
     */
778
    public function testJsonEncodeBean()
779
    {
780
        $userDao = new TestUserDao($this->tdbmService);
781
        $user = $userDao->getUserByLogin('bill.shakespeare');
782
783
        $jsonEncoded = json_encode($user);
784
        $userDecoded = json_decode($jsonEncoded, true);
785
786
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
787
788
        // test serialization of dates.
789
        $this->assertTrue(is_string($userDecoded['createdAt']));
790
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
791
        $this->assertNull($userDecoded['modifiedAt']);
792
793
        // testing many to 1 relationships
794
        $this->assertEquals('UK', $userDecoded['country']['label']);
795
796
        // testing many to many relationships
797
        $this->assertCount(1, $userDecoded['roles']);
798
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
799
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
800
    }
801
802
    /**
803
     * @depends testDaoGeneration
804
     */
805
    public function testNullableForeignKey()
806
    {
807
        $userDao = new TestUserDao($this->tdbmService);
808
        $user = $userDao->getUserByLogin('john.smith');
809
810
        $this->assertNull(null, $user->getManager());
811
812
        $jsonEncoded = json_encode($user);
813
        $userDecoded = json_decode($jsonEncoded, true);
814
815
        $this->assertNull(null, $userDecoded['manager']);
816
    }
817
818
    /**
819
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
820
     *
821
     * @depends testDaoGeneration
822
     */
823
    public function testSetToNullForeignKey()
824
    {
825
        $userDao = new TestUserDao($this->tdbmService);
826
        $user = $userDao->getUserByLogin('john.smith');
827
        $manager = $userDao->getUserByLogin('jean.dupont');
828
829
        $user->setManager($manager);
830
        $userDao->save($user);
831
832
        $user->setManager(null);
833
        $userDao->save($user);
834
    }
835
836
    /**
837
     * @depends testDaoGeneration
838
     * @expectedException \Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException
839
     * @expectedExceptionMessage Could not find table 'contacts'. Did you mean 'contact'?
840
     */
841
    public function testQueryOnWrongTableName()
842
    {
843
        $userDao = new TestUserDao($this->tdbmService);
844
        $users = $userDao->getUsersWrongTableName();
845
        $users->count();
846
    }
847
848
    /**
849
     * @depends testDaoGeneration
850
     */
851
    /*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...
852
    {
853
        $userDao = new TestUserDao($this->tdbmService);
854
        $users = $userDao->getUsersByManagerId(null);
855
        $this->assertCount(3, $users);
856
    }*/
857
858
    /**
859
     * @depends testDaoGeneration
860
     */
861
    public function testInnerJsonEncode()
862
    {
863
        $userDao = new TestUserDao($this->tdbmService);
864
        $user = $userDao->getUserByLogin('bill.shakespeare');
865
866
        $jsonEncoded = json_encode(['user' => $user]);
867
        $msgDecoded = json_decode($jsonEncoded, true);
868
869
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
870
    }
871
872
    /**
873
     * @depends testDaoGeneration
874
     */
875 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...
876
    {
877
        $userDao = new TestUserDao($this->tdbmService);
878
        $users = $userDao->getUsersByLoginStartingWith('bill');
879
880
        $jsonEncoded = json_encode($users);
881
        $msgDecoded = json_decode($jsonEncoded, true);
882
883
        $this->assertCount(1, $msgDecoded);
884
    }
885
886
    /**
887
     * @depends testDaoGeneration
888
     */
889 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...
890
    {
891
        $userDao = new TestUserDao($this->tdbmService);
892
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
893
894
        $jsonEncoded = json_encode($users);
895
        $msgDecoded = json_decode($jsonEncoded, true);
896
897
        $this->assertCount(1, $msgDecoded);
898
    }
899
900
    /**
901
     * @depends testDaoGeneration
902
     */
903 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...
904
    {
905
        $userDao = new TestUserDao($this->tdbmService);
906
        $users = $userDao->getUsersByLoginStartingWith('bill');
907
908
        $jsonEncoded = json_encode($users->take(0, 1));
909
        $msgDecoded = json_decode($jsonEncoded, true);
910
911
        $this->assertCount(1, $msgDecoded);
912
    }
913
914
    /**
915
     * @depends testDaoGeneration
916
     */
917 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...
918
    {
919
        $userDao = new TestUserDao($this->tdbmService);
920
        $users = $userDao->getUsersByLoginStartingWith('bill');
921
922
        $bill = $users->first();
923
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
924
    }
925
926
    /**
927
     * @depends testDaoGeneration
928
     */
929
    public function testFirstNull()
930
    {
931
        $userDao = new TestUserDao($this->tdbmService);
932
        $users = $userDao->getUsersByLoginStartingWith('mike');
933
934
        $user = $users->first();
935
        $this->assertNull($user);
936
    }
937
938
    /**
939
     * @depends testDaoGeneration
940
     */
941
    public function testCloneBeanAttachedBean()
942
    {
943
        $userDao = new TestUserDao($this->tdbmService);
944
        $user = $userDao->getUserByLogin('bill.shakespeare');
945
        $this->assertEquals(4, $user->getId());
946
        $user2 = clone $user;
947
        $this->assertNull($user2->getId());
948
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
949
        $this->assertEquals('Bill Shakespeare', $user2->getName());
950
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
951
952
        // MANY 2 MANY must be duplicated
953
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
954
955
        // Let's test saving this clone
956
        $user2->setLogin('william.shakespeare');
957
        $userDao->save($user2);
958
959
        $user3 = $userDao->getUserByLogin('william.shakespeare');
960
        $this->assertTrue($user3 === $user2);
961
        $userDao->delete($user3);
962
963
        // Finally, let's test the origin user still exists!
964
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
965
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
966
    }
967
968
    /**
969
     * @depends testDaoGeneration
970
     */
971
    public function testCloneNewBean()
972
    {
973
        $countryDao = new CountryDao($this->tdbmService);
974
        $roleDao = new RoleDao($this->tdbmService);
975
        $role = $roleDao->getById(1);
976
977
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
978
        $userBean->addRole($role);
979
980
        $user2 = clone $userBean;
981
982
        $this->assertNull($user2->getId());
983
        $this->assertEquals('john.doe', $user2->getLogin());
984
        $this->assertEquals('John Doe', $user2->getName());
985
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
986
987
        // MANY 2 MANY must be duplicated
988
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
989
    }
990
991
    /**
992
     * @depends testDaoGeneration
993
     */
994
    public function testCascadeDelete()
995
    {
996
        $userDao = new TestUserDao($this->tdbmService);
997
        $countryDao = new CountryDao($this->tdbmService);
998
999
        $spain = new CountryBean('Spain');
1000
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1001
1002
        $countryDao->save($spain);
1003
        $userDao->save($sanchez);
1004
1005
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1006
        $this->assertTrue($sanchez === $speedy2);
1007
1008
        $exceptionTriggered = false;
1009
        try {
1010
            $countryDao->delete($spain);
1011
        } catch (ForeignKeyConstraintViolationException $e) {
1012
            $exceptionTriggered = true;
1013
        }
1014
        $this->assertTrue($exceptionTriggered);
1015
1016
        $countryDao->delete($spain, true);
1017
1018
        // Let's check that speed gonzalez was removed.
1019
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1020
        $this->assertNull($speedy3);
1021
    }
1022
1023
    /**
1024
     * @depends testDaoGeneration
1025
     */
1026
    public function testDiscardChanges()
1027
    {
1028
        $contactDao = new ContactDao($this->tdbmService);
1029
        $contactBean = $contactDao->getById(1);
1030
1031
        $oldName = $contactBean->getName();
1032
1033
        $contactBean->setName('MyNewName');
1034
1035
        $contactBean->discardChanges();
1036
1037
        $this->assertEquals($oldName, $contactBean->getName());
1038
    }
1039
1040
    /**
1041
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1042
     * @depends testDaoGeneration
1043
     */
1044
    public function testDiscardChangesOnNewBeanFails()
1045
    {
1046
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1047
        $person->discardChanges();
1048
    }
1049
1050
    /**
1051
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1052
     * @depends testDaoGeneration
1053
     */
1054
    public function testDiscardChangesOnDeletedBeanFails()
1055
    {
1056
        $userDao = new TestUserDao($this->tdbmService);
1057
        $countryDao = new CountryDao($this->tdbmService);
1058
1059
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1060
1061
        $userDao->save($sanchez);
1062
1063
        $userDao->delete($sanchez);
1064
1065
        // Cannot discard changes on a bean that is already deleted.
1066
        $sanchez->discardChanges();
1067
    }
1068
1069
    /**
1070
     * @depends testDaoGeneration
1071
     */
1072 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...
1073
    {
1074
        $userDao = new UserDao($this->tdbmService);
1075
        $user = $userDao->findOneByLogin('bill.shakespeare');
1076
1077
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1078
        $this->assertEquals('Bill Shakespeare', $user->getName());
1079
    }
1080
1081
    /**
1082
     * @depends testDaoGeneration
1083
     */
1084
    public function testFindOneByRetunsNull()
1085
    {
1086
        // Let's assert that the findOneBy... methods can return null.
1087
        $userDao = new UserDao($this->tdbmService);
1088
        $userBean = $userDao->findOneByLogin('not_exist');
1089
1090
        $this->assertNull($userBean);
1091
    }
1092
1093
    /**
1094
     * @depends testDaoGeneration
1095
     */
1096 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...
1097
    {
1098
        $countryDao = new CountryDao($this->tdbmService);
1099
        $userDao = new UserDao($this->tdbmService);
1100
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1101
1102
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1103
    }
1104
1105
    /**
1106
     * @depends testDaoGeneration
1107
     */
1108
    public function testCreationInNullableDate()
1109
    {
1110
        $roleDao = new RoleDao($this->tdbmService);
1111
1112
        $role = new RoleBean('newbee');
1113
        $roleDao->save($role);
1114
1115
        $this->assertNull($role->getCreatedAt());
1116
    }
1117
1118
    /**
1119
     * @depends testDaoGeneration
1120
     */
1121
    public function testUpdateInNullableDate()
1122
    {
1123
        $roleDao = new RoleDao($this->tdbmService);
1124
1125
        $role = new RoleBean('newbee');
1126
        $roleDao->save($role);
1127
1128
        $role->setCreatedAt(null);
1129
        $roleDao->save($role);
1130
        $this->assertNull($role->getCreatedAt());
1131
    }
1132
1133
    /**
1134
     * @depends testDaoGeneration
1135
     */
1136
    public function testFindFromSql()
1137
    {
1138
        $roleDao = new TestRoleDao($this->tdbmService);
1139
1140
        $roles = $roleDao->getRolesByRightCanSing();
1141
        $this->assertCount(2, $roles);
1142
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1143
    }
1144
1145
    /**
1146
     * @depends testDaoGeneration
1147
     */
1148
    public function testFindOneFromSql()
1149
    {
1150
        $roleDao = new TestRoleDao($this->tdbmService);
1151
1152
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1153
        $this->assertInstanceOf(RoleBean::class, $role);
1154
    }
1155
1156
    /**
1157
     * @depends testDaoGeneration
1158
     */
1159
    public function testCreateEmptyExtendedBean()
1160
    {
1161
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1162
1163
        $dogDao = new DogDao($this->tdbmService);
1164
1165
        // We are not filling no field that is part of dog table.
1166
        $dog = new DogBean('Youki');
1167
        $dog->setOrder(1);
1168
1169
        $dogDao->save($dog);
1170
    }
1171
1172
    /**
1173
     * @depends testCreateEmptyExtendedBean
1174
     */
1175
    public function testFetchEmptyExtendedBean()
1176
    {
1177
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1178
1179
        $animalDao = new AnimalDao($this->tdbmService);
1180
1181
        // We are not filling no field that is part of dog table.
1182
        $animalBean = $animalDao->getById(1);
1183
1184
        $this->assertInstanceOf(DogBean::class, $animalBean);
1185
    }
1186
1187
    /**
1188
     * @depends testDaoGeneration
1189
     */
1190
    public function testTwoBranchesHierarchy()
1191
    {
1192
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1193
1194
        $catDao = new CatDao($this->tdbmService);
1195
1196
        // We are not filling no field that is part of dog table.
1197
        $cat = new CatBean('Mew');
1198
        $cat->setOrder(2);
1199
1200
        $catDao->save($cat);
1201
    }
1202
1203
    /**
1204
     * @depends testTwoBranchesHierarchy
1205
     */
1206
    public function testFetchTwoBranchesHierarchy()
1207
    {
1208
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1209
1210
        $animalDao = new AnimalDao($this->tdbmService);
1211
1212
        $animalBean = $animalDao->getById(2);
1213
1214
        $this->assertInstanceOf(CatBean::class, $animalBean);
1215
        /* @var $animalBean CatBean */
1216
        $animalBean->setCutenessLevel(999);
1217
1218
        $animalDao->save($animalBean);
1219
    }
1220
1221
    /**
1222
     * @depends testDaoGeneration
1223
     */
1224
    public function testExceptionOnGetById()
1225
    {
1226
        $countryDao = new CountryDao($this->tdbmService);
1227
        $this->expectException(\TypeError::class);
1228
        $countryDao->getById(null);
1229
    }
1230
1231
    /**
1232
     * @depends testDaoGeneration
1233
     */
1234
    public function testDisconnectedManyToOne()
1235
    {
1236
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1237
1238
        $country = new CountryBean('Spain');
1239
1240
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1241
1242
        $this->assertCount(1, $country->getUsers());
1243
        $this->assertSame($user, $country->getUsers()[0]);
1244
    }
1245
1246
    /**
1247
     * @depends testDaoGeneration
1248
     */
1249 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...
1250
    {
1251
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1252
1253
        $userDao = new TestUserDao($this->tdbmService);
1254
        $users = $userDao->getUsersByCountryName();
1255
1256
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1257
    }
1258
1259
    /**
1260
     * @depends testDaoGeneration
1261
     */
1262
    public function testResultIteratorSort()
1263
    {
1264
        $userDao = new UserDao($this->tdbmService);
1265
        $users = $userDao->findAll()->withOrder('country.label DESC');
1266
1267
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1268
1269
        $users = $users->withOrder('country.label ASC');
1270
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1271
    }
1272
1273
    /**
1274
     * @depends testDaoGeneration
1275
     */
1276
    public function testResultIteratorWithParameters()
1277
    {
1278
        $userDao = new TestUserDao($this->tdbmService);
1279
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1280
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1281
1282
        $users = $users->withParameters(['login' => 'jean%']);
1283
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1284
    }
1285
1286
    /**
1287
     * @depends testDaoGeneration
1288
     */
1289 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...
1290
    {
1291
        $userDao = new TestUserDao($this->tdbmService);
1292
        $users = $userDao->getUsersByReversedCountryName();
1293
1294
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1295
    }
1296
1297
    /**
1298
     * @depends testDaoGeneration
1299
     */
1300
    public function testOrderByException()
1301
    {
1302
        $userDao = new TestUserDao($this->tdbmService);
1303
        $users = $userDao->getUsersByInvalidOrderBy();
1304
        $this->expectException(TDBMInvalidArgumentException::class);
1305
        $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...
1306
    }
1307
1308
    /**
1309
     * @depends testDaoGeneration
1310
     */
1311
    public function testOrderByProtectedColumn()
1312
    {
1313
        $animalDao = new AnimalDao($this->tdbmService);
1314
        $animals = $animalDao->findAll();
1315
        $animals = $animals->withOrder('`order` ASC');
1316
1317
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1318
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1319
1320
        $animals = $animals->withOrder('`order` DESC');
1321
1322
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1323
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1324
    }
1325
1326
    /**
1327
     * @depends testDaoGeneration
1328
     */
1329
    public function testGetOnAllNullableValues()
1330
    {
1331
        // Tests that a get performed on a column that has only nullable fields succeeds.
1332
        $allNullable = new AllNullableBean();
1333
        $this->assertNull($allNullable->getId());
1334
        $this->assertNull($allNullable->getLabel());
1335
        $this->assertNull($allNullable->getCountry());
1336
    }
1337
1338
    /**
1339
     * @depends testDaoGeneration
1340
     */
1341
    public function testExceptionOnMultipleInheritance()
1342
    {
1343
        $connection = self::getConnection();
1344
        self::insert($connection, 'animal', [
1345
            'id' => 99, 'name' => 'Snoofield',
1346
        ]);
1347
        self::insert($connection, 'dog', [
1348
            'id' => 99, 'race' => 'dog',
1349
        ]);
1350
        self::insert($connection, 'cat', [
1351
            'id' => 99, 'cuteness_level' => 0,
1352
        ]);
1353
1354
        $catched = false;
1355
        try {
1356
            $animalDao = new AnimalDao($this->tdbmService);
1357
            $animalDao->getById(99);
1358
        } catch (TDBMInheritanceException $e) {
1359
            $catched = true;
1360
        }
1361
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1362
1363
        self::delete($connection, 'cat', ['id' => 99]);
1364
        self::delete($connection, 'dog', ['id' => 99]);
1365
        self::delete($connection, 'animal', ['id' => 99]);
1366
    }
1367
1368
    /**
1369
     * @depends testDaoGeneration
1370
     */
1371
    public function testReferenceNotSaved()
1372
    {
1373
        $boatDao = new BoatDao($this->tdbmService);
1374
1375
        $country = new CountryBean('Atlantis');
1376
        $boat = new BoatBean($country, 'Titanic');
1377
1378
        $boatDao->save($boat);
1379
    }
1380
1381
    /**
1382
     * @depends testDaoGeneration
1383
     */
1384
    public function testReferenceDeleted()
1385
    {
1386
        $countryDao = new CountryDao($this->tdbmService);
1387
        $boatDao = new BoatDao($this->tdbmService);
1388
1389
        $country = new CountryBean('Atlantis');
1390
        $countryDao->save($country);
1391
1392
        $boat = new BoatBean($country, 'Titanic');
1393
        $countryDao->delete($country);
1394
1395
        $this->expectException(TDBMMissingReferenceException::class);
1396
        $boatDao->save($boat);
1397
    }
1398
1399
    /**
1400
     * @depends testDaoGeneration
1401
     */
1402 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...
1403
    {
1404
        $userDao = new UserDao($this->tdbmService);
1405
1406
        $country = new CountryBean('Norrisland');
1407
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1408
1409
        $user->setManager($user);
1410
1411
        $this->expectException(TDBMCyclicReferenceException::class);
1412
        $userDao->save($user);
1413
    }
1414
1415
    /**
1416
     * @depends testDaoGeneration
1417
     */
1418
    public function testCyclicReference()
1419
    {
1420
        $categoryDao = new CategoryDao($this->tdbmService);
1421
1422
        $category = new CategoryBean('Root');
1423
1424
        $category->setParent($category);
1425
1426
        $this->expectException(TDBMCyclicReferenceException::class);
1427
        $categoryDao->save($category);
1428
    }
1429
1430
    /**
1431
     * @depends testDaoGeneration
1432
     */
1433
    public function testCorrectTypeForPrimaryKeyAfterSave()
1434
    {
1435
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1436
        $this->onlyMySql();
1437
1438
        $allNullableDao = new AllNullableDao($this->tdbmService);
1439
        $allNullable = new AllNullableBean();
1440
        $allNullableDao->save($allNullable);
1441
        $id = $allNullable->getId();
1442
1443
        $this->assertTrue(is_int($id));
1444
    }
1445
1446
    /**
1447
     * @depends testDaoGeneration
1448
     */
1449
    public function testPSR2Compliance()
1450
    {
1451
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
1452
        $process->run();
1453
1454
        // executes after the command finishes
1455
        if (!$process->isSuccessful()) {
1456
            echo $process->getOutput();
1457
            $this->fail('Generated code is not PRS2 compliant');
1458
        }
1459
    }
1460
1461
    /**
1462
     * @depends testDaoGeneration
1463
     */
1464
    public function testFindOneByGeneration()
1465
    {
1466
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1467
        $parameters = $reflectionMethod->getParameters();
1468
1469
        $this->assertCount(2, $parameters);
1470
        $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...
1471
        $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...
1472
    }
1473
1474
    /**
1475
     * @depends testDaoGeneration
1476
     */
1477 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...
1478
    {
1479
        $article = new ArticleBean('content');
1480
        $this->assertSame('content', $article->getContent());
1481
        $this->assertNotEmpty($article->getId());
1482
        $uuid = Uuid::fromString($article->getId());
1483
        $this->assertSame(1, $uuid->getVersion());
1484
    }
1485
1486
    /**
1487
     * @depends testDaoGeneration
1488
     */
1489 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...
1490
    {
1491
        $article = new Article2Bean('content');
1492
        $this->assertSame('content', $article->getContent());
1493
        $this->assertNotEmpty($article->getId());
1494
        $uuid = Uuid::fromString($article->getId());
1495
        $this->assertSame(4, $uuid->getVersion());
1496
    }
1497
1498
    /**
1499
     * @depends testDaoGeneration
1500
     */
1501
    public function testTypeHintedConstructors()
1502
    {
1503
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1504
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1505
1506
        $this->assertSame('string', (string) $nameParam->getType());
1507
    }
1508
1509
    /**
1510
     * @depends testDaoGeneration
1511
     */
1512
    public function testSaveTransaction()
1513
    {
1514
        $countryDao = new CountryDao($this->tdbmService);
1515
1516
        $boatDao = new BoatDao($this->tdbmService);
1517
        $boatBean = $boatDao->getById(1);
1518
        $boatBean->setName('Bismark');
1519
1520
        $boatBean->getCountry();
1521
1522
        // Let's insert a row without telling TDBM to trigger an error!
1523
        self::insert($this->getConnection(), 'sailed_countries', [
1524
            'boat_id' => 1,
1525
            'country_id' => 2
1526
        ]);
1527
1528
        $boatBean->addCountry($countryDao->getById(2));
1529
1530
        $this->expectException(UniqueConstraintViolationException::class);
1531
1532
        $boatDao->save($boatBean);
1533
    }
1534
1535
    /**
1536
     * @depends testSaveTransaction
1537
     */
1538
    public function testSaveTransaction2()
1539
    {
1540
        $boatDao = new BoatDao($this->tdbmService);
1541
        $boatBean = $boatDao->getById(1);
1542
1543
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1544
        $this->assertNotSame('Bismark', $boatBean->getName());
1545
    }
1546
1547
    /**
1548
     * @depends testDaoGeneration
1549
     */
1550
    public function testForeignKeyPointingToNonPrimaryKey()
1551
    {
1552
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1553
        $bean = $dao->getById(1);
1554
1555
        $this->assertSame('foo', $bean->getFrom()->getTo());
1556
    }
1557
}
1558