Test Failed
Pull Request — master (#52)
by David
03:47
created

TDBMDaoGeneratorTest::testFirstNull()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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