Completed
Push — uuid_annotation ( ce334a )
by David
02:50
created

TDBMDaoGeneratorTest::testUuidv4()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 8
Ratio 100 %

Importance

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