Passed
Pull Request — master (#12)
by Dorian
04:12
created

TDBMDaoGeneratorTest::testOrderByExpression()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %

Importance

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