Passed
Pull Request — master (#215)
by David
03:13
created

testGeneratedColumnsAreNotPartOfTheConstructor()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 34
rs 9.6666
cc 3
nc 2
nop 0
1
<?php
2
declare(strict_types=1);
3
4
/*
5
 Copyright (C) 2006-2018 David Négrier - THE CODING MACHINE
6
7
This program is free software; you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 2 of the License, or
10
(at your option) any later version.
11
12
This program is distributed in the hope that it will be useful,
13
but WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
GNU General Public License for more details.
16
17
You should have received a copy of the GNU General Public License
18
along with this program; if not, write to the Free Software
19
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
*/
21
22
namespace TheCodingMachine\TDBM;
23
24
use Doctrine\Common\Cache\ArrayCache;
25
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
26
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
27
use Doctrine\DBAL\Platforms\MySQL57Platform;
28
use Doctrine\DBAL\Platforms\MySqlPlatform;
29
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
30
use Ramsey\Uuid\Uuid;
31
use ReflectionClass;
32
use ReflectionMethod;
33
use ReflectionNamedType;
34
use TheCodingMachine\TDBM\Dao\TestAlbumDao;
35
use TheCodingMachine\TDBM\Dao\TestArticleDao;
36
use TheCodingMachine\TDBM\Dao\TestArticleSubQueryDao;
37
use TheCodingMachine\TDBM\Dao\TestCountryDao;
38
use TheCodingMachine\TDBM\Dao\TestPersonDao;
39
use TheCodingMachine\TDBM\Dao\TestRoleDao;
40
use TheCodingMachine\TDBM\Dao\TestUserDao;
41
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserDaoInterface;
42
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserInterface;
43
use TheCodingMachine\TDBM\Test\Dao\AlbumDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\AlbumDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
44
use TheCodingMachine\TDBM\Test\Dao\AllNullableDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\AllNullableDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
45
use TheCodingMachine\TDBM\Test\Dao\AnimalDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\AnimalDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
46
use TheCodingMachine\TDBM\Test\Dao\ArtistDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\ArtistDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
47
use TheCodingMachine\TDBM\Test\Dao\BaseObjectDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\BaseObjectDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
48
use TheCodingMachine\TDBM\Test\Dao\Bean\AccountBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\AccountBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
49
use TheCodingMachine\TDBM\Test\Dao\Bean\AlbumBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\AlbumBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
50
use TheCodingMachine\TDBM\Test\Dao\Bean\AllNullableBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...ao\Bean\AllNullableBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
51
use TheCodingMachine\TDBM\Test\Dao\Bean\AnimalBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\AnimalBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
52
use TheCodingMachine\TDBM\Test\Dao\Bean\Article2Bean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\Article2Bean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
53
use TheCodingMachine\TDBM\Test\Dao\Bean\ArticleBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\ArticleBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
54
use TheCodingMachine\TDBM\Test\Dao\Bean\ArtistBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\ArtistBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
55
use TheCodingMachine\TDBM\Test\Dao\Bean\BaseObjectBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\BaseObjectBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
56
use TheCodingMachine\TDBM\Test\Dao\Bean\BoatBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\BoatBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
57
use TheCodingMachine\TDBM\Test\Dao\Bean\CatBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\CatBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
58
use TheCodingMachine\TDBM\Test\Dao\Bean\CategoryBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\CategoryBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
59
use TheCodingMachine\TDBM\Test\Dao\Bean\CountryBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\CountryBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
60
use TheCodingMachine\TDBM\Test\Dao\Bean\DogBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\DogBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
61
use TheCodingMachine\TDBM\Test\Dao\Bean\FileBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\FileBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
62
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\ArticleBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...nerated\ArticleBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
63
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\BoatBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...\Generated\BoatBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
64
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\FileBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...\Generated\FileBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
65
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\UserBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...\Generated\UserBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
66
use TheCodingMachine\TDBM\Test\Dao\Bean\InheritedObjectBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...ean\InheritedObjectBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
67
use TheCodingMachine\TDBM\Test\Dao\Bean\NodeBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\NodeBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
68
use TheCodingMachine\TDBM\Test\Dao\Bean\PersonBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\PersonBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
69
use TheCodingMachine\TDBM\Test\Dao\Bean\PlayerBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\PlayerBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
70
use TheCodingMachine\TDBM\Test\Dao\Bean\RefNoPrimKeyBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...o\Bean\RefNoPrimKeyBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
use TheCodingMachine\TDBM\Test\Dao\Bean\RoleBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\RoleBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
72
use TheCodingMachine\TDBM\Test\Dao\Bean\StateBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\StateBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
73
use TheCodingMachine\TDBM\Test\Dao\Bean\UserBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\UserBean was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
74
use TheCodingMachine\TDBM\Test\Dao\BoatDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\BoatDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
75
use TheCodingMachine\TDBM\Test\Dao\CatDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\CatDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
76
use TheCodingMachine\TDBM\Test\Dao\CategoryDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\CategoryDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
77
use TheCodingMachine\TDBM\Test\Dao\CompositeFkSourceDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...ao\CompositeFkSourceDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
78
use TheCodingMachine\TDBM\Test\Dao\ContactDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\ContactDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
79
use TheCodingMachine\TDBM\Test\Dao\CountryDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\CountryDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
80
use TheCodingMachine\TDBM\Test\Dao\DogDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\DogDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
81
use TheCodingMachine\TDBM\Test\Dao\FileDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\FileDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
82
use TheCodingMachine\TDBM\Test\Dao\Generated\UserBaseDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...o\Generated\UserBaseDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
83
use TheCodingMachine\TDBM\Test\Dao\InheritedObjectDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\InheritedObjectDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
84
use TheCodingMachine\TDBM\Test\Dao\NodeDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\NodeDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
85
use TheCodingMachine\TDBM\Test\Dao\PersonDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\PersonDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
86
use TheCodingMachine\TDBM\Test\Dao\PlayerDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\PlayerDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
87
use TheCodingMachine\TDBM\Test\Dao\RefNoPrimKeyDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\RefNoPrimKeyDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
88
use TheCodingMachine\TDBM\Test\Dao\RoleDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\RoleDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
89
use TheCodingMachine\TDBM\Test\Dao\StateDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\StateDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
90
use TheCodingMachine\TDBM\Test\Dao\UserDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\UserDao was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
91
use TheCodingMachine\TDBM\Utils\PathFinder\NoPathFoundException;
92
use TheCodingMachine\TDBM\Utils\PathFinder\PathFinder;
93
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
94
use Symfony\Component\Process\Process;
95
96
class TDBMDaoGeneratorTest extends TDBMAbstractServiceTest
97
{
98
    /** @var TDBMDaoGenerator $tdbmDaoGenerator */
99
    protected $tdbmDaoGenerator;
100
101
    private $rootPath;
102
103
    protected function setUp(): void
104
    {
105
        parent::setUp();
106
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
107
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
108
        $schemaLockFileDumper = new SchemaLockFileDumper($this->tdbmService->getConnection(), new ArrayCache(), Configuration::getDefaultLockFilePath());
109
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer, $schemaLockFileDumper);
110
        $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
111
        $this->rootPath = __DIR__ . '/../';
112
        //$this->tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
113
    }
114
115
    public function testGetSchemaCrashWithoutLock()
116
    {
117
        //let's delete the lock file
118
        $schemaFilePath = Configuration::getDefaultLockFilePath();
119
        if (file_exists($schemaFilePath)) {
120
            unlink($schemaFilePath);
121
        }
122
        //let's check we cannot call get schema without a lock file
123
        $schemaAnalyzer = new SchemaAnalyzer(self::getConnection()->getSchemaManager(), new ArrayCache(), 'prefix_');
124
        $schemaLockFileDumper = new SchemaLockFileDumper(self::getConnection(), new ArrayCache(), Configuration::getDefaultLockFilePath());
125
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer(self::getConnection(), new ArrayCache(), $schemaAnalyzer, $schemaLockFileDumper);
126
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
127
        $schema1 = $tdbmSchemaAnalyzer->getSchema(true);
0 ignored issues
show
Unused Code introduced by
The assignment to $schema1 is dead and can be removed.
Loading history...
Deprecated Code introduced by
The function TheCodingMachine\TDBM\TD...maAnalyzer::getSchema() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

127
        $schema1 = /** @scrutinizer ignore-deprecated */ $tdbmSchemaAnalyzer->getSchema(true);
Loading history...
128
    }
129
130
    public function testDaoGeneration(): void
131
    {
132
        // Remove all previously generated files.
133
        $this->recursiveDelete($this->rootPath . 'src/Test/Dao/');
134
        mkdir($this->rootPath . 'src/Test/Dao/Generated', 0755, true);
135
        // Let's generate a dummy file to see it is indeed removed.
136
        $dummyFile = $this->rootPath . 'src/Test/Dao/Generated/foobar.php';
137
        touch($dummyFile);
138
        $this->assertFileExists($dummyFile);
139
140
        //let's delete the lock file
141
        $schemaFilePath = Configuration::getDefaultLockFilePath();
142
        if (file_exists($schemaFilePath)) {
143
            unlink($schemaFilePath);
144
        }
145
146
        $this->tdbmDaoGenerator->generateAllDaosAndBeans();
147
148
        $this->assertFileNotExists($dummyFile);
149
150
        //Check that the lock file was generated
151
        $this->assertFileExists($schemaFilePath);
152
153
        // Let's require all files to check they are valid PHP!
154
        // Test the daoFactory
155
        require_once $this->rootPath . 'src/Test/Dao/Generated/DaoFactory.php';
156
        // Test the others
157
158
        $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
159
160
        foreach ($beanDescriptors as $beanDescriptor) {
161
            $daoName = $beanDescriptor->getDaoClassName();
162
            $daoBaseName = $beanDescriptor->getBaseDaoClassName();
163
            $beanName = $beanDescriptor->getBeanClassName();
164
            $baseBeanName = $beanDescriptor->getBaseBeanClassName();
165
            require_once $this->rootPath . 'src/Test/Dao/Bean/Generated/' . $baseBeanName . '.php';
166
            require_once $this->rootPath . 'src/Test/Dao/Bean/' . $beanName . '.php';
167
            require_once $this->rootPath . 'src/Test/Dao/Generated/' . $daoBaseName . '.php';
168
            require_once $this->rootPath . 'src/Test/Dao/' . $daoName . '.php';
169
        }
170
171
        // Check that pivot tables do not generate DAOs or beans.
172
        $this->assertFalse(class_exists('TheCodingMachine\\TDBM\\Test\\Dao\\RolesRightDao'));
173
    }
174
175
    public function testGenerationException(): void
176
    {
177
        $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', self::getConnection(), $this->getNamingStrategy());
178
179
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
180
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
181
        $schemaLockFileDumper = new SchemaLockFileDumper($this->tdbmService->getConnection(), new ArrayCache(), Configuration::getDefaultLockFilePath());
182
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer, $schemaLockFileDumper);
183
        $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
184
        $this->rootPath = __DIR__ . '/../../../../';
185
        //$tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
186
187
        $this->expectException(NoPathFoundException::class);
188
        $tdbmDaoGenerator->generateAllDaosAndBeans();
189
    }
190
191
    /**
192
     * Delete a file or recursively delete a directory.
193
     *
194
     * @param string $str Path to file or directory
195
     * @return bool
196
     */
197
    private function recursiveDelete(string $str): bool
198
    {
199
        if (is_file($str)) {
200
            return @unlink($str);
201
        } elseif (is_dir($str)) {
202
            $scan = glob(rtrim($str, '/') . '/*');
203
            foreach ($scan as $index => $path) {
204
                $this->recursiveDelete($path);
205
            }
206
207
            return @rmdir($str);
208
        }
209
        return false;
210
    }
211
212
    /**
213
     * @depends testDaoGeneration
214
     */
215
    public function testGetBeanClassName(): void
216
    {
217
        $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
218
219
        // Let's create another TDBMService to test the cache.
220
        $configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), $this->getNamingStrategy(), $this->getCache(), null, null, [$this->getDummyGeneratorListener()]);
221
        $configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 4)));
222
        $newTdbmService = new TDBMService($configuration);
223
        $this->assertEquals(UserBean::class, $newTdbmService->getBeanClassName('users'));
224
    }
225
226
    /**
227
     * @depends testDaoGeneration
228
     */
229
    public function testGeneratedGetById(): void
230
    {
231
        $contactDao = new ContactDao($this->tdbmService);
232
        $contactBean = $contactDao->getById(1);
233
        $this->assertEquals(1, $contactBean->getId());
234
        $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
235
236
        // FIXME: Question: que faire du paramètre stockage "UTC"????
237
    }
238
239
    /**
240
     * @depends testDaoGeneration
241
     */
242
    public function testGeneratedGetByIdLazyLoaded(): void
243
    {
244
        $roleDao = new RoleDao($this->tdbmService);
245
        $roleBean = $roleDao->getById(1, true);
246
        $this->assertEquals(1, $roleBean->getId());
247
        $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
248
249
        $roleBean2 = $roleDao->getById(1, true);
250
        $this->assertTrue($roleBean === $roleBean2);
251
    }
252
253
    /**
254
     * @depends testDaoGeneration
255
     */
256
    public function testDefaultValueOnNewBean(): void
257
    {
258
        $roleBean = new RoleBean('my_role');
259
        $this->assertEquals(1, $roleBean->getStatus());
260
    }
261
262
    /**
263
     * @depends testDaoGeneration
264
     */
265
    public function testForeignKeyInBean(): void
266
    {
267
        $userDao = new UserDao($this->tdbmService);
268
        $userBean = $userDao->getById(1);
269
        $country = $userBean->getCountry();
270
271
        $this->assertEquals('UK', $country->getLabel());
272
273
        $userBean2 = $userDao->getById(1);
274
        $this->assertTrue($userBean === $userBean2);
275
276
        $contactDao = new ContactDao($this->tdbmService);
277
        $contactBean = $contactDao->getById(1);
278
279
        $this->assertTrue($userBean === $contactBean);
280
    }
281
282
    /**
283
     * @depends testDaoGeneration
284
     */
285
    public function testNewBeans(): void
286
    {
287
        $countryDao = new CountryDao($this->tdbmService);
288
        $userDao = new UserDao($this->tdbmService);
289
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
290
        $userBean->setOrder(1); // Let's set a "protected keyword" column.
291
292
        $userDao->save($userBean);
293
294
        $this->assertNull($userBean->getManager());
295
    }
296
297
    /**
298
     * @depends testDaoGeneration
299
     */
300
    public function testDateTimeImmutableGetter(): void
301
    {
302
        $userDao = new UserDao($this->tdbmService);
303
        $user = $userDao->getById(1);
304
305
        $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
306
    }
307
308
    /**
309
     * @depends testDaoGeneration
310
     */
311
    public function testAssigningNewBeans(): void
312
    {
313
        $userDao = new UserDao($this->tdbmService);
314
        $countryBean = new CountryBean('Mexico');
315
        $userBean = new UserBean('Speedy Gonzalez', '[email protected]', $countryBean, 'speedy.gonzalez');
316
        $this->assertEquals($countryBean, $userBean->getCountry());
317
318
        $userDao->save($userBean);
319
    }
320
321
    /**
322
     * @depends testAssigningNewBeans
323
     */
324
    public function testUpdatingProtectedColumn(): void
325
    {
326
        $userDao = new UserDao($this->tdbmService);
327
        $userBean = $userDao->findOneByLogin('speedy.gonzalez');
328
        $userBean->setOrder(2);
329
        $userDao->save($userBean);
330
        $this->assertSame(2, $userBean->getOrder());
331
    }
332
333
    /**
334
     * @depends testDaoGeneration
335
     */
336
    public function testAssigningExistingRelationship(): void
337
    {
338
        $userDao = new UserDao($this->tdbmService);
339
        $user = $userDao->getById(1);
340
        $countryDao = new CountryDao($this->tdbmService);
341
        $country = $countryDao->getById(2);
342
343
        $user->setCountry($country);
344
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
345
    }
346
347
    /**
348
     * @depends testDaoGeneration
349
     */
350
    public function testDirectReversedRelationship(): void
351
    {
352
        $countryDao = new CountryDao($this->tdbmService);
353
        $country = $countryDao->getById(1);
354
        $users = $country->getUsers();
355
356
        $arr = $users->toArray();
357
358
        $this->assertCount(1, $arr);
359
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
360
        $this->assertEquals('jean.dupont', $arr[0]->getLogin());
361
362
        $newUser = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
0 ignored issues
show
Unused Code introduced by
The assignment to $newUser is dead and can be removed.
Loading history...
363
        $users = $country->getUsers();
364
365
        $arr = $users->toArray();
366
367
        $this->assertCount(2, $arr);
368
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
369
        $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
370
    }
371
372
    /**
373
     * @depends testDaoGeneration
374
     */
375
    public function testDeleteInDirectReversedRelationship(): void
376
    {
377
        $countryDao = new CountryDao($this->tdbmService);
378
        $country = $countryDao->getById(1);
379
380
        $userDao = new UserDao($this->tdbmService);
381
        $newUser = new UserBean('John Snow', '[email protected]', $country, 'john.snow');
382
        $userDao->save($newUser);
383
384
        $users = $country->getUsers();
385
386
        $arr = $users->toArray();
387
388
        $this->assertCount(2, $arr);
389
390
        $userDao->delete($arr[1]);
391
392
        $users = $country->getUsers();
393
        $arr = $users->toArray();
394
        $this->assertCount(1, $arr);
395
    }
396
397
    /**
398
     * @depends testDaoGeneration
399
     */
400
    public function testJointureGetters(): void
401
    {
402
        $roleDao = new RoleDao($this->tdbmService);
403
        $role = $roleDao->getById(1);
404
        $users = $role->getUsers();
405
406
        $this->assertCount(2, $users);
407
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
408
409
        $rights = $role->getRights();
410
411
        $this->assertCount(2, $rights);
412
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
413
    }
414
415
    /**
416
     * @depends testDaoGeneration
417
     */
418
    public function testNestedIterationOnAlterableResultIterator(): void
419
    {
420
        $countryDao = new CountryDao($this->tdbmService);
421
        $country = $countryDao->getById(2);
422
423
        $count = 0;
424
        // Let's perform 2 nested calls to check that iterators do not melt.
425
        foreach ($country->getUsers() as $user) {
426
            foreach ($country->getUsers() as $user2) {
427
                $count++;
428
            }
429
        }
430
        // There are 3 users linked to country 2.
431
        $this->assertSame(9, $count);
432
    }
433
434
    /**
435
     * @depends testDaoGeneration
436
     */
437
    public function testNewBeanConstructor(): void
438
    {
439
        $role = new RoleBean('Newrole');
440
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
441
    }
442
443
    /**
444
     * @depends testDaoGeneration
445
     */
446
    public function testJointureAdderOnNewBean(): void
447
    {
448
        $countryDao = new CountryDao($this->tdbmService);
449
        $country = $countryDao->getById(1);
450
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
451
        $role = new RoleBean('Mouse');
452
        $user->addRole($role);
453
        $roles = $user->getRoles();
454
        $this->assertCount(1, $roles);
455
        $role = $roles[0];
456
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
457
        $users = $role->getUsers();
458
        $this->assertCount(1, $users);
459
        $this->assertEquals($user, $users[0]);
460
461
        $role->removeUser($user);
462
        $this->assertCount(0, $role->getUsers());
463
        $this->assertCount(0, $user->getRoles());
464
    }
465
466
    /**
467
     * @depends testDaoGeneration
468
     */
469
    public function testJointureDeleteBeforeGetters(): void
470
    {
471
        $roleDao = new RoleDao($this->tdbmService);
472
        $userDao = new UserDao($this->tdbmService);
473
        $role = $roleDao->getById(1);
474
        $user = $userDao->getById(1);
475
476
        // We call removeUser BEFORE calling getUsers
477
        // This should work as expected.
478
        $role->removeUser($user);
479
        $users = $role->getUsers();
480
481
        $this->assertCount(1, $users);
482
    }
483
484
    /**
485
     * @depends testDaoGeneration
486
     */
487
    public function testJointureMultiAdd(): void
488
    {
489
        $countryDao = new CountryDao($this->tdbmService);
490
        $country = $countryDao->getById(1);
491
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
492
        $role = new RoleBean('Mouse');
493
        $user->addRole($role);
494
        $role->addUser($user);
495
        $user->addRole($role);
496
497
        $this->assertCount(1, $user->getRoles());
498
    }
499
500
    /**
501
     * Step 1: we remove the role 1 from user 1 but save role 1.
502
     * Expected result: no save done.
503
     *
504
     * @depends testDaoGeneration
505
     */
506
    public function testJointureSave1(): void
507
    {
508
        $roleDao = new RoleDao($this->tdbmService);
509
        $role = $roleDao->getById(1);
510
        $userDao = new UserDao($this->tdbmService);
511
        $user = $userDao->getById(1);
512
513
        $this->assertTrue($user->hasRole($role));
514
        $this->assertTrue($role->hasUser($user));
515
        $user->removeRole($role);
516
        $this->assertFalse($user->hasRole($role));
517
        $this->assertFalse($role->hasUser($user));
518
        $roleDao->save($role);
519
520
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
521
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
522
    }
523
524
    /**
525
     * Step 2: we check that nothing was saved
526
     * Expected result: no save done.
527
     *
528
     * @depends testJointureSave1
529
     */
530
    public function testJointureSave2(): void
531
    {
532
        $roleDao = new RoleDao($this->tdbmService);
533
        $role = $roleDao->getById(1);
534
        $this->assertCount(2, $role->getUsers());
535
    }
536
537
    /**
538
     * Step 3: we remove the role 1 from user 1 and save user 1.
539
     * Expected result: save done.
540
     *
541
     * @depends testJointureSave2
542
     */
543
    public function testJointureSave3(): void
544
    {
545
        $roleDao = new RoleDao($this->tdbmService);
546
        $role = $roleDao->getById(1);
547
        $userDao = new UserDao($this->tdbmService);
548
        $user = $userDao->getById(1);
549
550
        $this->assertCount(1, $user->getRoles());
551
        $user->removeRole($role);
552
        $this->assertCount(0, $user->getRoles());
553
        $userDao->save($user);
554
        $this->assertCount(0, $user->getRoles());
555
    }
556
557
    /**
558
     * Step 4: we check that save was done
559
     * Expected result: save done.
560
     *
561
     * @depends testJointureSave3
562
     */
563
    public function testJointureSave4(): void
564
    {
565
        $roleDao = new RoleDao($this->tdbmService);
566
        $role = $roleDao->getById(1);
567
        $this->assertCount(1, $role->getUsers());
568
        $userDao = new UserDao($this->tdbmService);
569
        $user = $userDao->getById(1);
570
        $this->assertCount(0, $user->getRoles());
571
    }
572
573
    /**
574
     * Step 5: we add the role 1 from user 1 and save user 1.
575
     * Expected result: save done.
576
     *
577
     * @depends testJointureSave4
578
     */
579
    public function testJointureSave5(): void
580
    {
581
        $roleDao = new RoleDao($this->tdbmService);
582
        $role = $roleDao->getById(1);
583
        $userDao = new UserDao($this->tdbmService);
584
        $user = $userDao->getById(1);
585
586
        $user->addRole($role);
587
        $this->assertCount(1, $user->getRoles());
588
        $userDao->save($user);
589
    }
590
591
    /**
592
     * Step 6: we check that save was done
593
     * Expected result: save done.
594
     *
595
     * @depends testJointureSave5
596
     */
597
    public function testJointureSave6(): void
598
    {
599
        $roleDao = new RoleDao($this->tdbmService);
600
        $role = $roleDao->getById(1);
601
        $this->assertCount(2, $role->getUsers());
602
        $userDao = new UserDao($this->tdbmService);
603
        $user = $userDao->getById(1);
604
        $this->assertCount(1, $user->getRoles());
605
    }
606
607
    /**
608
     * Step 7: we add a new role to user 1 and save user 1.
609
     * Expected result: save done, including the new role.
610
     *
611
     * @depends testJointureSave6
612
     */
613
    public function testJointureSave7(): void
614
    {
615
        $role = new RoleBean('my new role');
616
        $userDao = new UserDao($this->tdbmService);
617
        $user = $userDao->getById(1);
618
619
        $user->addRole($role);
620
        $userDao->save($user);
621
622
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
623
    }
624
625
    /**
626
     * Step 8: we check that save was done
627
     * Expected result: save done.
628
     *
629
     * @depends testJointureSave7
630
     */
631
    public function testJointureSave8(): void
632
    {
633
        $roleDao = new RoleDao($this->tdbmService);
634
        $userDao = new UserDao($this->tdbmService);
635
        $user = $userDao->getById(1);
636
637
        $roles = $user->getRoles();
638
        foreach ($roles as $role) {
639
            if ($role->getName() === 'my new role') {
640
                $selectedRole = $role;
641
                break;
642
            }
643
        }
644
        $this->assertNotNull($selectedRole);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $selectedRole does not seem to be defined for all execution paths leading up to this point.
Loading history...
645
646
        $this->assertCount(2, $user->getRoles());
647
648
        // Expected: relationship removed!
649
        $roleDao->delete($selectedRole);
650
651
        $this->assertCount(1, $user->getRoles());
652
    }
653
654
    /**
655
     * Step 9: Let's test the setXXX method.
656
     *
657
     * @depends testJointureSave8
658
     */
659
    public function testJointureSave9(): void
660
    {
661
        $roleDao = new RoleDao($this->tdbmService);
662
        $userDao = new UserDao($this->tdbmService);
663
        $user = $userDao->getById(1);
664
665
        // At this point, user 1 is linked to role 1.
666
        // Let's bind it to role 2.
667
        $user->setRoles([$roleDao->getById(2)]);
668
        $userDao->save($user);
669
        $this->assertTrue($user->hasRole($roleDao->getById(2)));
670
    }
671
672
    /**
673
     * Step 10: Let's check results of 9.
674
     *
675
     * @depends testJointureSave9
676
     */
677
    public function testJointureSave10(): void
678
    {
679
        $userDao = new UserDao($this->tdbmService);
680
        $user = $userDao->getById(1);
681
682
        $roles = $user->getRoles();
683
684
        $this->assertCount(1, $roles);
685
        $this->assertEquals(2, $roles[0]->getId());
686
    }
687
688
    /**
689
     * Test jointure in a parent table in an inheritance relationship
690
     *
691
     * @depends testDaoGeneration
692
     */
693
    public function testJointureInParentTable(): void
694
    {
695
        $userDao = new UserDao($this->tdbmService);
696
        $user = $userDao->getById(1);
697
698
        $boats = $user->getBoats();
699
700
        $this->assertCount(1, $boats);
701
        $this->assertEquals(1, $boats[0]->getId());
702
    }
703
704
    /**
705
     * @depends testDaoGeneration
706
     */
707
    public function testFindOrderBy(): void
708
    {
709
        $userDao = new TestUserDao($this->tdbmService);
710
        $users = $userDao->getUsersByAlphabeticalOrder();
711
712
        $this->assertCount(6, $users);
713
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
714
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
715
716
        $users = $userDao->getUsersByCountryOrder();
717
        $this->assertCount(6, $users);
718
        $countryName1 = $users[0]->getCountry()->getLabel();
719
        for ($i = 1; $i < 6; $i++) {
720
            $countryName2 = $users[$i]->getCountry()->getLabel();
721
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
722
            $countryName1 = $countryName2;
723
        }
724
    }
725
726
    /**
727
     * @depends testDaoGeneration
728
     */
729
    public function testFindFromSqlOrderBy(): void
730
    {
731
        $userDao = new TestUserDao($this->tdbmService);
732
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
733
734
        $this->assertCount(6, $users);
735
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
736
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
737
738
        $users = $userDao->getUsersFromSqlByCountryOrder();
739
        $this->assertCount(6, $users);
740
        $countryName1 = $users[0]->getCountry()->getLabel();
741
        for ($i = 1; $i < 6; $i++) {
742
            $countryName2 = $users[$i]->getCountry()->getLabel();
743
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
744
            $countryName1 = $countryName2;
745
        }
746
    }
747
748
    /**
749
     * @depends testDaoGeneration
750
     */
751
    public function testFindFromSqlOrderByOnInheritedBean(): void
752
    {
753
        $articleDao = new TestArticleDao($this->tdbmService);
754
        $articles = $articleDao->getArticlesByUserLogin();
755
756
        foreach ($articles as $article) {
757
            var_dump($article);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($article) looks like debug code. Are you sure you do not want to remove it?
Loading history...
758
        }
759
        $this->assertCount(0, $articles);
760
    }
761
762
763
    /**
764
     * @depends testDaoGeneration
765
     */
766
    public function testFindFromSqlOrderByJoinRole(): void
767
    {
768
        $roleDao = new TestRoleDao($this->tdbmService);
769
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
770
771
        $this->assertCount(2, $roles);
772
        $this->assertEquals('Singers', $roles[0]->getName());
773
        $this->assertEquals('Admins', $roles[1]->getName());
774
    }
775
776
    /**
777
     * @depends testDaoGeneration
778
     */
779
    public function testFindFromRawSqlOrderByUserCount(): void
780
    {
781
        $countryDao = new TestCountryDao($this->tdbmService);
782
        $countries = $countryDao->getCountriesByUserCount();
783
784
        $nbCountries = 4;
785
        $this->assertCount($nbCountries, $countries);
786
        for ($i = 1; $i < $nbCountries; $i++) {
787
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
788
        }
789
    }
790
791
    /**
792
     * @depends testDaoGeneration
793
     */
794
    public function testFindFromRawSqlWithUnion(): void
795
    {
796
        $countryDao = new TestCountryDao($this->tdbmService);
797
        $countries = $countryDao->getCountriesUsingUnion();
798
799
        $this->assertCount(2, $countries);
800
        $this->assertEquals(1, $countries[0]->getId());
801
    }
802
803
    /**
804
     * @depends testDaoGeneration
805
     */
806
    public function testFindFromRawSqlWithSimpleQuery(): void
807
    {
808
        $countryDao = new TestCountryDao($this->tdbmService);
809
        $countries = $countryDao->getCountriesUsingSimpleQuery();
810
811
        $this->assertCount(1, $countries);
812
        $this->assertEquals(1, $countries[0]->getId());
813
    }
814
815
    /**
816
     * @depends testDaoGeneration
817
     */
818
    public function testFindFromRawSqlWithDistinctQuery(): void
819
    {
820
        $countryDao = new TestCountryDao($this->tdbmService);
821
        $countries = $countryDao->getCountriesUsingDistinctQuery();
822
823
        $this->assertCount(1, $countries);
824
        $this->assertEquals(2, $countries[0]->getId());
825
    }
826
827
    /**
828
     * @depends testDaoGeneration
829
     */
830
    public function testFindFilters(): void
831
    {
832
        $userDao = new TestUserDao($this->tdbmService);
833
        $users = $userDao->getUsersByLoginStartingWith('bill');
834
835
        $this->assertCount(1, $users);
836
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
837
    }
838
839
    /**
840
     * @depends testDaoGeneration
841
     */
842
    public function testFindMode(): void
843
    {
844
        $userDao = new TestUserDao($this->tdbmService);
845
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
846
847
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
848
        $users[0];
849
    }
850
851
    /**
852
     * @depends testDaoGeneration
853
     */
854
    public function testFindAll(): void
855
    {
856
        $userDao = new TestUserDao($this->tdbmService);
857
        $users = $userDao->findAll();
858
859
        $this->assertCount(6, $users);
860
    }
861
862
    /**
863
     * @depends testDaoGeneration
864
     */
865
    public function testFindOne(): void
866
    {
867
        $userDao = new TestUserDao($this->tdbmService);
868
        $user = $userDao->getUserByLogin('bill.shakespeare');
869
870
        $this->assertEquals('bill.shakespeare', $user->getLogin());
871
    }
872
873
    /**
874
     * @depends testDaoGeneration
875
     */
876
    public function testJsonEncodeBean(): void
877
    {
878
        $userDao = new TestUserDao($this->tdbmService);
879
        $user = $userDao->getUserByLogin('bill.shakespeare');
880
881
        $jsonEncoded = json_encode($user);
882
        $userDecoded = json_decode($jsonEncoded, true);
883
884
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
885
886
        // test serialization of dates.
887
        $this->assertTrue(is_string($userDecoded['createdAt']));
888
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
889
        $this->assertNull($userDecoded['modifiedAt']);
890
891
        // testing many to 1 relationships
892
        $this->assertEquals('UK', $userDecoded['country']['label']);
893
894
        // testing many to many relationships
895
        $this->assertCount(1, $userDecoded['roles']);
896
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
897
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
898
    }
899
900
    /**
901
     * @depends testDaoGeneration
902
     */
903
    public function testNullableForeignKey(): void
904
    {
905
        $userDao = new TestUserDao($this->tdbmService);
906
        $user = $userDao->getUserByLogin('john.smith');
907
908
        $this->assertNull($user->getManager());
909
910
        $jsonEncoded = json_encode($user);
911
        $userDecoded = json_decode($jsonEncoded, true);
912
913
        $this->assertNull($userDecoded['manager']);
914
    }
915
916
    /**
917
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
918
     *
919
     * @depends testDaoGeneration
920
     */
921
    public function testSetToNullForeignKey(): void
922
    {
923
        $userDao = new TestUserDao($this->tdbmService);
924
        $user = $userDao->getUserByLogin('john.smith');
925
        $manager = $userDao->getUserByLogin('jean.dupont');
926
927
        $user->setManager($manager);
928
        $userDao->save($user);
929
930
        $user->setManager(null);
931
        $userDao->save($user);
932
        $this->assertNull($user->getManager());
933
    }
934
935
    /**
936
     * @depends testDaoGeneration
937
     */
938
    public function testQueryOnWrongTableName(): void
939
    {
940
        $userDao = new TestUserDao($this->tdbmService);
941
        $users = $userDao->getUsersWrongTableName();
942
        $this->expectException('Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException');
943
        $this->expectExceptionMessage('Could not find table \'contacts\'. Did you mean \'contact\'?');
944
        $users->count();
945
    }
946
947
    /**
948
     * @depends testDaoGeneration
949
     */
950
    /*public function testQueryNullForeignKey(): void
951
    {
952
        $userDao = new TestUserDao($this->tdbmService);
953
        $users = $userDao->getUsersByManagerId(null);
954
        $this->assertCount(3, $users);
955
    }*/
956
957
    /**
958
     * @depends testDaoGeneration
959
     */
960
    public function testInnerJsonEncode(): void
961
    {
962
        $userDao = new TestUserDao($this->tdbmService);
963
        $user = $userDao->getUserByLogin('bill.shakespeare');
964
965
        $jsonEncoded = json_encode(['user' => $user]);
966
        $msgDecoded = json_decode($jsonEncoded, true);
967
968
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
969
    }
970
971
    /**
972
     * @depends testDaoGeneration
973
     */
974
    public function testArrayJsonEncode(): void
975
    {
976
        $userDao = new TestUserDao($this->tdbmService);
977
        $users = $userDao->getUsersByLoginStartingWith('bill');
978
979
        $jsonEncoded = json_encode($users);
980
        $msgDecoded = json_decode($jsonEncoded, true);
981
982
        $this->assertCount(1, $msgDecoded);
983
    }
984
985
    /**
986
     * @depends testDaoGeneration
987
     */
988
    public function testCursorJsonEncode(): void
989
    {
990
        $userDao = new TestUserDao($this->tdbmService);
991
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
992
993
        $jsonEncoded = json_encode($users);
994
        $msgDecoded = json_decode($jsonEncoded, true);
995
996
        $this->assertCount(1, $msgDecoded);
997
    }
998
999
    /**
1000
     * @depends testDaoGeneration
1001
     */
1002
    public function testPageJsonEncode(): void
1003
    {
1004
        $userDao = new TestUserDao($this->tdbmService);
1005
        $users = $userDao->getUsersByLoginStartingWith('bill');
1006
1007
        $jsonEncoded = json_encode($users->take(0, 1));
1008
        $msgDecoded = json_decode($jsonEncoded, true);
1009
1010
        $this->assertCount(1, $msgDecoded);
1011
    }
1012
1013
    /**
1014
     * @depends testDaoGeneration
1015
     */
1016
    public function testInnerResultIteratorCountAfterFetch(): void
1017
    {
1018
        $userDao = new TestUserDao($this->tdbmService);
1019
        $users = $userDao->getUsersByLoginStartingWith('j')->take(0, 4);
1020
        $users->toArray(); // We force to fetch
1021
        $this->assertEquals(3, $users->count());
1022
    }
1023
1024
    /**
1025
     * @depends testDaoGeneration
1026
     */
1027
    public function testFirst(): void
1028
    {
1029
        $userDao = new TestUserDao($this->tdbmService);
1030
        $users = $userDao->getUsersByLoginStartingWith('bill');
1031
1032
        $bill = $users->first();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $bill is correct as $users->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1033
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
1034
    }
1035
1036
    /**
1037
     * @depends testDaoGeneration
1038
     */
1039
    public function testFirstNull(): void
1040
    {
1041
        $userDao = new TestUserDao($this->tdbmService);
1042
        $users = $userDao->getUsersByLoginStartingWith('mike');
1043
1044
        $user = $users->first();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $user is correct as $users->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1045
        $this->assertNull($user);
1046
    }
1047
1048
    /**
1049
     * @depends testDaoGeneration
1050
     */
1051
    public function testCloneBeanAttachedBean(): void
1052
    {
1053
        $userDao = new TestUserDao($this->tdbmService);
1054
        $user = $userDao->getUserByLogin('bill.shakespeare');
1055
        $this->assertEquals(4, $user->getId());
1056
        $user2 = clone $user;
1057
        $this->assertNull($user2->getId());
1058
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
1059
        $this->assertEquals('Bill Shakespeare', $user2->getName());
1060
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1061
1062
        // MANY 2 MANY must be duplicated
1063
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
1064
1065
        // Let's test saving this clone
1066
        $user2->setLogin('william.shakespeare');
1067
        $userDao->save($user2);
1068
1069
        $user3 = $userDao->getUserByLogin('william.shakespeare');
1070
        $this->assertTrue($user3 === $user2);
1071
        $userDao->delete($user3);
1072
1073
        // Finally, let's test the origin user still exists!
1074
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
1075
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
1076
    }
1077
1078
    /**
1079
     * @depends testDaoGeneration
1080
     */
1081
    public function testCloneNewBean(): void
1082
    {
1083
        $countryDao = new CountryDao($this->tdbmService);
1084
        $roleDao = new RoleDao($this->tdbmService);
1085
        $role = $roleDao->getById(1);
1086
1087
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
1088
        $userBean->addRole($role);
1089
1090
        $user2 = clone $userBean;
1091
1092
        $this->assertNull($user2->getId());
1093
        $this->assertEquals('john.doe', $user2->getLogin());
1094
        $this->assertEquals('John Doe', $user2->getName());
1095
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1096
1097
        // MANY 2 MANY must be duplicated
1098
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
1099
    }
1100
1101
    /**
1102
     * @depends testDaoGeneration
1103
     */
1104
    public function testCascadeDelete(): void
1105
    {
1106
        $userDao = new TestUserDao($this->tdbmService);
1107
        $countryDao = new CountryDao($this->tdbmService);
1108
1109
        $spain = new CountryBean('Spain');
1110
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1111
1112
        $countryDao->save($spain);
1113
        $userDao->save($sanchez);
1114
1115
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1116
        $this->assertTrue($sanchez === $speedy2);
1117
1118
        $exceptionTriggered = false;
1119
        try {
1120
            $countryDao->delete($spain);
1121
        } catch (ForeignKeyConstraintViolationException $e) {
1122
            $exceptionTriggered = true;
1123
        }
1124
        $this->assertTrue($exceptionTriggered);
1125
1126
        $countryDao->delete($spain, true);
1127
1128
        // Let's check that speed gonzalez was removed.
1129
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1130
        $this->assertNull($speedy3);
1131
    }
1132
1133
    /**
1134
     * @depends testDaoGeneration
1135
     */
1136
    public function testDiscardChanges(): void
1137
    {
1138
        $contactDao = new ContactDao($this->tdbmService);
1139
        $contactBean = $contactDao->getById(1);
1140
1141
        $oldName = $contactBean->getName();
1142
1143
        $contactBean->setName('MyNewName');
1144
1145
        $contactBean->discardChanges();
1146
1147
        $this->assertEquals($oldName, $contactBean->getName());
1148
    }
1149
1150
    /**
1151
     * @depends testDaoGeneration
1152
     */
1153
    public function testDiscardChangesOnNewBeanFails(): void
1154
    {
1155
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1156
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
1157
        $person->discardChanges();
1158
    }
1159
1160
    /**
1161
     * @depends testDaoGeneration
1162
     */
1163
    public function testDiscardChangesOnDeletedBeanFails(): void
1164
    {
1165
        $userDao = new TestUserDao($this->tdbmService);
1166
        $countryDao = new CountryDao($this->tdbmService);
1167
1168
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1169
1170
        $userDao->save($sanchez);
1171
1172
        $userDao->delete($sanchez);
1173
1174
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
1175
        // Cannot discard changes on a bean that is already deleted.
1176
        $sanchez->discardChanges();
1177
    }
1178
1179
    /**
1180
     * @depends testDaoGeneration
1181
     */
1182
    public function testUniqueIndexBasedSearch(): void
1183
    {
1184
        $userDao = new UserDao($this->tdbmService);
1185
        $user = $userDao->findOneByLogin('bill.shakespeare');
1186
1187
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1188
        $this->assertEquals('Bill Shakespeare', $user->getName());
1189
    }
1190
1191
    /**
1192
     * @depends testDaoGeneration
1193
     */
1194
    public function testFindOneByRetunsNull(): void
1195
    {
1196
        // Let's assert that the findOneBy... methods can return null.
1197
        $userDao = new UserDao($this->tdbmService);
1198
        $userBean = $userDao->findOneByLogin('not_exist');
1199
1200
        $this->assertNull($userBean);
1201
    }
1202
1203
    /**
1204
     * @depends testDaoGeneration
1205
     */
1206
    public function testMultiColumnsIndexBasedSearch(): void
1207
    {
1208
        $countryDao = new CountryDao($this->tdbmService);
1209
        $userDao = new UserDao($this->tdbmService);
1210
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1211
1212
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1213
    }
1214
1215
    /**
1216
     * @depends testDaoGeneration
1217
     */
1218
    public function testPartialMultiColumnsIndexBasedSearch(): void
1219
    {
1220
        $userDao = new UserDao($this->tdbmService);
1221
        $users = $userDao->findByStatusAndCountry('on');
1222
1223
        $this->assertCount(2, $users);
1224
    }
1225
1226
    /**
1227
     * @depends testDaoGeneration
1228
     */
1229
    public function testCreationInNullableDate(): void
1230
    {
1231
        $roleDao = new RoleDao($this->tdbmService);
1232
1233
        $role = new RoleBean('newbee');
1234
        $roleDao->save($role);
1235
1236
        $this->assertNull($role->getCreatedAt());
1237
    }
1238
1239
    /**
1240
     * @depends testDaoGeneration
1241
     */
1242
    public function testUpdateInNullableDate(): void
1243
    {
1244
        $roleDao = new RoleDao($this->tdbmService);
1245
1246
        $role = new RoleBean('newbee');
1247
        $roleDao->save($role);
1248
1249
        $role->setCreatedAt(null);
1250
        $roleDao->save($role);
1251
        $this->assertNull($role->getCreatedAt());
1252
    }
1253
1254
    /**
1255
     * @depends testDaoGeneration
1256
     */
1257
    public function testFindFromSql(): void
1258
    {
1259
        $roleDao = new TestRoleDao($this->tdbmService);
1260
1261
        $roles = $roleDao->getRolesByRightCanSing();
1262
        $this->assertCount(2, $roles);
1263
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1264
    }
1265
1266
    /**
1267
     * @depends testDaoGeneration
1268
     */
1269
    public function testFindOneFromSql(): void
1270
    {
1271
        $roleDao = new TestRoleDao($this->tdbmService);
1272
1273
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1274
        $this->assertInstanceOf(RoleBean::class, $role);
1275
    }
1276
1277
    /**
1278
     * @depends testDaoGeneration
1279
     */
1280
    public function testCreateEmptyExtendedBean(): void
1281
    {
1282
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1283
1284
        $dogDao = new DogDao($this->tdbmService);
1285
1286
        // We are not filling no field that is part of dog table.
1287
        $dog = new DogBean('Youki');
1288
        $dog->setOrder(1);
1289
1290
        $dogDao->save($dog);
1291
        $this->assertNull($dog->getRace());
1292
    }
1293
1294
    /**
1295
     * @depends testCreateEmptyExtendedBean
1296
     */
1297
    public function testFetchEmptyExtendedBean(): void
1298
    {
1299
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1300
1301
        $animalDao = new AnimalDao($this->tdbmService);
1302
1303
        // We are not filling no field that is part of dog table.
1304
        $animalBean = $animalDao->getById(1);
1305
1306
        $this->assertInstanceOf(DogBean::class, $animalBean);
1307
    }
1308
1309
    /**
1310
     * @depends testDaoGeneration
1311
     */
1312
    public function testTwoBranchesHierarchy(): void
1313
    {
1314
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1315
1316
        $catDao = new CatDao($this->tdbmService);
1317
1318
        // We are not filling no field that is part of dog table.
1319
        $cat = new CatBean('Mew');
1320
        $cat->setOrder(2);
1321
1322
        $catDao->save($cat);
1323
        $this->assertNotNull($cat->getId());
1324
    }
1325
1326
    /**
1327
     * @depends testTwoBranchesHierarchy
1328
     */
1329
    public function testFetchTwoBranchesHierarchy(): void
1330
    {
1331
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1332
1333
        $animalDao = new AnimalDao($this->tdbmService);
1334
1335
        $animalBean = $animalDao->getById(2);
1336
1337
        $this->assertInstanceOf(CatBean::class, $animalBean);
1338
        /* @var $animalBean CatBean */
1339
        $animalBean->setCutenessLevel(999);
1340
        $animalBean->setUppercaseColumn('foobar');
1341
1342
        $animalDao->save($animalBean);
1343
    }
1344
1345
    /**
1346
     * @depends testDaoGeneration
1347
     */
1348
    public function testExceptionOnGetById(): void
1349
    {
1350
        $countryDao = new CountryDao($this->tdbmService);
1351
        $this->expectException(\TypeError::class);
1352
        $countryDao->getById(null);
1353
    }
1354
1355
    /**
1356
     * @depends testDaoGeneration
1357
     */
1358
    public function testDisconnectedManyToOne(): void
1359
    {
1360
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1361
1362
        $country = new CountryBean('Spain');
1363
1364
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1365
1366
        $this->assertCount(1, $country->getUsers());
1367
        $this->assertSame($user, $country->getUsers()[0]);
1368
    }
1369
1370
    /**
1371
     * @depends testDaoGeneration
1372
     */
1373
    public function testOrderByExternalCol(): void
1374
    {
1375
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1376
1377
        $userDao = new TestUserDao($this->tdbmService);
1378
        $users = $userDao->getUsersByCountryName();
1379
1380
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1381
    }
1382
1383
    /**
1384
     * @depends testDaoGeneration
1385
     */
1386
    public function testResultIteratorSort(): void
1387
    {
1388
        $userDao = new UserDao($this->tdbmService);
1389
        $users = $userDao->findAll()->withOrder('country.label DESC');
1390
1391
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1392
1393
        $users = $users->withOrder('country.label ASC');
1394
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1395
    }
1396
1397
    /**
1398
     * @depends testDaoGeneration
1399
     */
1400
    public function testResultIteratorWithParameters(): void
1401
    {
1402
        $userDao = new TestUserDao($this->tdbmService);
1403
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1404
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1405
1406
        $users = $users->withParameters(['login' => 'jean%']);
1407
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1408
    }
1409
1410
    /**
1411
     * @depends testDaoGeneration
1412
     */
1413
    public function testOrderByExpression(): void
1414
    {
1415
        $userDao = new TestUserDao($this->tdbmService);
1416
        $users = $userDao->getUsersByReversedCountryName();
1417
1418
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1419
    }
1420
1421
    /**
1422
     * @depends testDaoGeneration
1423
     */
1424
    public function testOrderByException(): void
1425
    {
1426
        $userDao = new TestUserDao($this->tdbmService);
1427
        $users = $userDao->getUsersByInvalidOrderBy();
1428
        $this->expectException(TDBMInvalidArgumentException::class);
1429
        $user = $users[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
1430
    }
1431
1432
    /**
1433
     * @depends testDaoGeneration
1434
     */
1435
    public function testOrderByProtectedColumn(): void
1436
    {
1437
        $animalDao = new AnimalDao($this->tdbmService);
1438
        $animals = $animalDao->findAll();
1439
        $animals = $animals->withOrder('`order` ASC');
1440
1441
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1442
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1443
1444
        $animals = $animals->withOrder('`order` DESC');
1445
1446
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1447
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1448
    }
1449
1450
    /**
1451
     * @depends testDaoGeneration
1452
     */
1453
    public function testGetOnAllNullableValues(): void
1454
    {
1455
        // Tests that a get performed on a column that has only nullable fields succeeds.
1456
        $allNullable = new AllNullableBean();
1457
        $this->assertNull($allNullable->getId());
1458
        $this->assertNull($allNullable->getLabel());
1459
        $this->assertNull($allNullable->getCountry());
1460
    }
1461
1462
    /**
1463
     * @depends testDaoGeneration
1464
     */
1465
    public function testExceptionOnMultipleInheritance(): void
1466
    {
1467
        $connection = self::getConnection();
1468
        self::insert($connection, 'animal', [
1469
            'id' => 99, 'name' => 'Snoofield',
1470
        ]);
1471
        self::insert($connection, 'dog', [
1472
            'id' => 99, 'race' => 'dog',
1473
        ]);
1474
        self::insert($connection, 'cat', [
1475
            'id' => 99, 'cuteness_level' => 0,
1476
        ]);
1477
1478
        $catched = false;
1479
        try {
1480
            $animalDao = new AnimalDao($this->tdbmService);
1481
            $animalDao->getById(99);
1482
        } catch (TDBMInheritanceException $e) {
1483
            $catched = true;
1484
        }
1485
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1486
1487
        self::delete($connection, 'cat', ['id' => 99]);
1488
        self::delete($connection, 'dog', ['id' => 99]);
1489
        self::delete($connection, 'animal', ['id' => 99]);
1490
    }
1491
1492
    /**
1493
     * @depends testDaoGeneration
1494
     */
1495
    public function testReferenceNotSaved(): void
1496
    {
1497
        $boatDao = new BoatDao($this->tdbmService);
1498
1499
        $country = new CountryBean('Atlantis');
1500
        $boat = new BoatBean($country, 'Titanic');
1501
1502
        $boatDao->save($boat);
1503
        $this->assertNotNull($country->getId());
1504
    }
1505
1506
    /**
1507
     * @depends testReferenceNotSaved
1508
     */
1509
    public function testUniqueIndexOnForeignKeyThenScalar(): void
1510
    {
1511
        $boatDao = new BoatDao($this->tdbmService);
1512
        $countryDao = new CountryDao($this->tdbmService);
1513
1514
        $countryBean = $countryDao->findOneByLabel('Atlantis');
1515
        $boatBean = $boatDao->findOneByAnchorageCountryAndName($countryBean, 'Titanic');
1516
1517
        $this->assertNotNull($boatBean);
1518
    }
1519
1520
    /**
1521
     * @depends testDaoGeneration
1522
     */
1523
    public function testReferenceDeleted(): void
1524
    {
1525
        $countryDao = new CountryDao($this->tdbmService);
1526
        $boatDao = new BoatDao($this->tdbmService);
1527
1528
        $country = new CountryBean('Bikini Bottom');
1529
        $countryDao->save($country);
1530
1531
        $boat = new BoatBean($country, 'Squirrel boat');
1532
        $countryDao->delete($country);
1533
1534
        $this->expectException(TDBMMissingReferenceException::class);
1535
        $boatDao->save($boat);
1536
    }
1537
1538
    /**
1539
     * @depends testDaoGeneration
1540
     */
1541
    public function testCyclicReferenceWithInheritance(): void
1542
    {
1543
        $userDao = new UserDao($this->tdbmService);
1544
1545
        $country = new CountryBean('Norrisland');
1546
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1547
1548
        $user->setManager($user);
1549
1550
        $this->expectException(TDBMCyclicReferenceException::class);
1551
        $userDao->save($user);
1552
    }
1553
1554
    /**
1555
     * @depends testDaoGeneration
1556
     */
1557
    public function testCyclicReference(): void
1558
    {
1559
        $categoryDao = new CategoryDao($this->tdbmService);
1560
1561
        $category = new CategoryBean('Root');
1562
1563
        $category->setParent($category);
1564
1565
        $this->expectException(TDBMCyclicReferenceException::class);
1566
        $categoryDao->save($category);
1567
    }
1568
1569
    /**
1570
     * @depends testDaoGeneration
1571
     */
1572
    public function testCorrectTypeForPrimaryKeyAfterSave(): void
1573
    {
1574
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1575
        $this->onlyMySql();
1576
1577
        $allNullableDao = new AllNullableDao($this->tdbmService);
1578
        $allNullable = new AllNullableBean();
1579
        $allNullableDao->save($allNullable);
1580
        $id = $allNullable->getId();
1581
1582
        $this->assertTrue(is_int($id));
1583
    }
1584
1585
    /**
1586
     * @depends testDaoGeneration
1587
     */
1588
    public function testPSR2Compliance(): void
1589
    {
1590
        $process = new Process(['vendor/bin/php-cs-fixer', 'fix', 'src/Test/', '--dry-run', '--diff', '--rules=@PSR2']);
1591
        $process->run();
1592
1593
        // executes after the command finishes
1594
        if (!$process->isSuccessful()) {
1595
            echo $process->getOutput();
1596
            $this->fail('Generated code is not PSR-2 compliant');
1597
        }
1598
        $this->assertTrue($process->isSuccessful());
1599
    }
1600
1601
    /**
1602
     * @depends testDaoGeneration
1603
     */
1604
    public function testFindOneByGeneration(): void
1605
    {
1606
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1607
        $parameters = $reflectionMethod->getParameters();
1608
1609
        $this->assertCount(2, $parameters);
1610
        $this->assertSame('login', $parameters[0]->getName());
1611
        $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
1612
    }
1613
1614
    /**
1615
     * @depends testDaoGeneration
1616
     */
1617
    public function testUuid(): void
1618
    {
1619
        $article = new ArticleBean('content');
1620
        $this->assertSame('content', $article->getContent());
1621
        $this->assertNotEmpty($article->getId());
1622
        $uuid = Uuid::fromString($article->getId());
1623
        $this->assertSame(1, $uuid->getVersion());
0 ignored issues
show
Deprecated Code introduced by
The function Ramsey\Uuid\DeprecatedUuidInterface::getVersion() has been deprecated: Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1623
        $this->assertSame(1, /** @scrutinizer ignore-deprecated */ $uuid->getVersion());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
1624
    }
1625
1626
    /**
1627
     * @depends testDaoGeneration
1628
     */
1629
    public function testUuidv4(): void
1630
    {
1631
        $article = new Article2Bean('content');
1632
        $this->assertSame('content', $article->getContent());
1633
        $this->assertNotEmpty($article->getId());
1634
        $uuid = Uuid::fromString($article->getId());
1635
        $this->assertSame(4, $uuid->getVersion());
0 ignored issues
show
Deprecated Code introduced by
The function Ramsey\Uuid\DeprecatedUuidInterface::getVersion() has been deprecated: Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1635
        $this->assertSame(4, /** @scrutinizer ignore-deprecated */ $uuid->getVersion());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
1636
    }
1637
1638
    /**
1639
     * @depends testDaoGeneration
1640
     */
1641
    public function testTypeHintedConstructors(): void
1642
    {
1643
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1644
        /** @var ReflectionNamedType $nameParam */
1645
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1646
1647
        $this->assertSame('string', $nameParam->getType()->getName());
0 ignored issues
show
Bug introduced by
The method getType() does not exist on ReflectionNamedType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1647
        $this->assertSame('string', $nameParam->/** @scrutinizer ignore-call */ getType()->getName());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1648
    }
1649
1650
    /**
1651
     * @depends testDaoGeneration
1652
     */
1653
    public function testSaveTransaction(): void
1654
    {
1655
        $countryDao = new CountryDao($this->tdbmService);
1656
1657
        $boatDao = new BoatDao($this->tdbmService);
1658
        $boatBean = $boatDao->getById(1);
1659
        $boatBean->setName('Bismark');
1660
1661
        $boatBean->getCountry();
1662
1663
        // Let's insert a row without telling TDBM to trigger an error!
1664
        self::insert($this->getConnection(), 'sailed_countries', [
1665
            'boat_id' => 1,
1666
            'country_id' => 2
1667
        ]);
1668
1669
        $boatBean->addCountry($countryDao->getById(2));
1670
1671
        $this->expectException(UniqueConstraintViolationException::class);
1672
1673
        $boatDao->save($boatBean);
1674
    }
1675
1676
    /**
1677
     * @depends testSaveTransaction
1678
     */
1679
    public function testSaveTransaction2(): void
1680
    {
1681
        $boatDao = new BoatDao($this->tdbmService);
1682
        $boatBean = $boatDao->getById(1);
1683
1684
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1685
        $this->assertNotSame('Bismark', $boatBean->getName());
1686
    }
1687
1688
    /**
1689
     * @depends testDaoGeneration
1690
     */
1691
    public function testForeignKeyPointingToNonPrimaryKey(): void
1692
    {
1693
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1694
        $bean = $dao->getById(1);
1695
1696
        $this->assertSame('foo', $bean->getFrom()->getTo());
1697
1698
        $newBean = new RefNoPrimKeyBean($bean, 'baz');
1699
        $dao->save($newBean);
1700
        $this->assertSame('foo', $newBean->getFrom()->getTo());
1701
1702
        $resultSet = $bean->getRefNoPrimKey();
1703
        $this->assertCount(2, $resultSet);
1704
    }
1705
1706
    /**
1707
     * @depends testDaoGeneration
1708
     */
1709
    public function testCloningUuidBean(): void
1710
    {
1711
        $article = new ArticleBean('content');
1712
        $this->assertNotEmpty($article->getId());
1713
        $article2 = clone $article;
1714
        $this->assertNotEmpty($article2->getId());
1715
        $this->assertNotSame($article->getId(), $article2->getId());
1716
    }
1717
1718
    /**
1719
     * @depends testDaoGeneration
1720
     */
1721
    public function testRecursiveSave(): void
1722
    {
1723
        $categoryDao = new CategoryDao($this->tdbmService);
1724
1725
        $root1 = new CategoryBean('Root1');
1726
        $categoryDao->save($root1);
1727
        // Root 2 is not saved yet.
1728
        $root2 = new CategoryBean('Root2');
1729
        $intermediate = new CategoryBean('Intermediate');
1730
        $categoryDao->save($intermediate);
1731
1732
        // Let's switch the parent to a bean in detached state.
1733
        $intermediate->setParent($root2);
1734
1735
        // Now, let's save a new category that references the leaf category.
1736
        $leaf = new CategoryBean('Leaf');
1737
        $leaf->setParent($intermediate);
1738
        $categoryDao->save($leaf);
1739
        $this->assertNull($root2->getId());
1740
    }
1741
1742
    /**
1743
     * @depends testDaoGeneration
1744
     */
1745
    public function testBlob(): void
1746
    {
1747
        $fp = fopen(__FILE__, 'r');
1748
        $file = new FileBean($fp);
1749
1750
        $fileDao = new FileDao($this->tdbmService);
1751
1752
        $fileDao->save($file);
1753
1754
        $loadedFile = $fileDao->getById($file->getId());
1755
1756
        $resource = $loadedFile->getFile();
1757
        $result = fseek($resource, 0);
1758
        $this->assertSame(0, $result);
1759
        $this->assertIsResource($resource);
1760
        $firstLine = fgets($resource);
1761
        $this->assertSame("<?php\n", $firstLine);
1762
    }
1763
1764
    /**
1765
     * @depends testBlob
1766
     */
1767
    public function testReadBlob(): void
1768
    {
1769
        $fileDao = new FileDao($this->tdbmService);
1770
        $loadedFile = $fileDao->getById(1);
1771
1772
        $resource = $loadedFile->getFile();
1773
        $this->assertIsResource($resource);
1774
        $firstLine = fgets($resource);
1775
        $this->assertSame("<?php\n", $firstLine);
1776
1777
        stream_get_contents($resource);
1778
1779
        $loadedFile->setId($loadedFile->getId());
1780
1781
        $fileDao->save($loadedFile);
1782
    }
1783
1784
    /**
1785
     * @depends testReadBlob
1786
     */
1787
    public function testReadAndSaveBlob(): void
1788
    {
1789
        $fileDao = new FileDao($this->tdbmService);
1790
        $loadedFile = $fileDao->getById(1);
1791
1792
        $resource = $loadedFile->getFile();
1793
1794
        $firstLine = fgets($resource);
1795
        $this->assertSame("<?php\n", $firstLine);
1796
    }
1797
1798
    /**
1799
     * @depends testReadBlob
1800
     */
1801
    public function testProtectedGetterSetter(): void
1802
    {
1803
        $md5Getter = new ReflectionMethod(FileBaseBean::class, 'getMd5');
1804
        $md5Setter = new ReflectionMethod(FileBaseBean::class, 'setMd5');
1805
1806
        $this->assertTrue($md5Getter->isProtected());
1807
        $this->assertTrue($md5Setter->isProtected());
1808
1809
        $md5Getter2 = new ReflectionMethod(FileBaseBean::class, 'getArticle');
1810
        $md5Setter2 = new ReflectionMethod(FileBaseBean::class, 'setArticle');
1811
1812
        $this->assertTrue($md5Getter2->isProtected());
1813
        $this->assertTrue($md5Setter2->isProtected());
1814
1815
        $oneToManyGetter = new ReflectionMethod(ArticleBaseBean::class, 'getFiles');
1816
        $this->assertTrue($oneToManyGetter->isProtected());
1817
1818
        $fileDao = new FileDao($this->tdbmService);
1819
        $loadedFile = $fileDao->getById(1);
1820
1821
        // The md5 and article columns are not JSON serialized
1822
        $this->assertSame([
1823
            'id' => 1,
1824
        ], $loadedFile->jsonSerialize());
1825
    }
1826
1827
    /**
1828
     * @depends testDaoGeneration
1829
     */
1830
    public function testBlobResourceException(): void
1831
    {
1832
        $this->expectException(TDBMInvalidArgumentException::class);
1833
        $this->expectExceptionMessage('Invalid argument passed to \'TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\Generated\\FileBaseBean::setFile\'. Expecting a resource. Got a string.');
1834
        new FileBean('foobar');
1835
    }
1836
1837
    /**
1838
     * @depends testDaoGeneration
1839
     */
1840
    public function testFilterBag(): void
1841
    {
1842
        $userDao = new TestUserDao($this->tdbmService);
1843
        $countryDao = new CountryDao($this->tdbmService);
1844
1845
        $country = $countryDao->getById(2);
1846
1847
        // Let's test filter bags by bean and filter bag with many values.
1848
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'Jane Doe']);
1849
1850
        $this->assertCount(1, $users);
1851
        $this->assertSame('John Doe', $users[0]->getName());
1852
    }
1853
1854
    /**
1855
     * @depends testDaoGeneration
1856
     */
1857
    public function testDecimalIsMappedToString(): void
1858
    {
1859
        $reflectionClass = new \ReflectionClass(BoatBaseBean::class);
1860
        $this->assertSame('string', $reflectionClass->getMethod('getLength')->getReturnType()->getName());
1861
    }
1862
1863
    /**
1864
     * @depends testDaoGeneration
1865
     */
1866
    public function testInsertMultiPrimaryKeysBean(): void
1867
    {
1868
        $countryDao = new CountryDao($this->tdbmService);
1869
1870
        $country = $countryDao->getById(1);
1871
1872
        $stateDao = new StateDao($this->tdbmService);
1873
        $state = new StateBean($country, 'IDF', 'Ile de France');
1874
        $stateDao->save($state);
1875
1876
        $this->assertSame($state, $stateDao->findAll()[0]);
1877
    }
1878
1879
    /**
1880
     * @depends testInsertMultiPrimaryKeysBean
1881
     */
1882
    public function testDeleteMultiPrimaryKeysBean(): void
1883
    {
1884
        $stateDao = new StateDao($this->tdbmService);
1885
1886
        $state = $stateDao->findAll()[0];
1887
        $stateDao->delete($state);
1888
        $this->assertCount(0, $stateDao->findAll());
1889
    }
1890
1891
    /**
1892
     * @depends testDaoGeneration
1893
     */
1894
    public function testCompositePrimaryKeyGetter(): void
1895
    {
1896
        $stateDao = new StateDao($this->tdbmService);
1897
        $country = new CountryBean('USA');
1898
        $stateBean = new StateBean($country, 'CA', 'California');
1899
        $stateDao->save($stateBean);
1900
        $this->assertSame($stateBean, $stateDao->getById($country->getId(), 'CA'));
1901
    }
1902
1903
    /**
1904
     * @depends testDaoGeneration
1905
     */
1906
    public function testSortOnInheritedTable(): void
1907
    {
1908
        $animalDao = new AnimalDao($this->tdbmService);
1909
1910
        // Let's insert an animal that is nothing.
1911
        $animal = new AnimalBean('Mickey');
1912
        $animalDao->save($animal);
1913
1914
        $animals = $animalDao->findAll()->withOrder('dog.race ASC');
1915
1916
        $animalsArr = $animals->toArray();
1917
        $this->assertCount(3, $animalsArr);
1918
    }
1919
1920
    /**
1921
     * @depends testDaoGeneration
1922
     */
1923
    public function testJsonKey(): void
1924
    {
1925
        $node = new NodeBean('foo.html');
1926
        $json = $node->jsonSerialize();
1927
        self::assertTrue(isset($json['basename']));
1928
        self::assertEquals('foo.html', $json['basename']);
1929
    }
1930
1931
    /**
1932
     * @depends testDaoGeneration
1933
     */
1934
    public function testJsonIgnore(): void
1935
    {
1936
        $nodeDao = new NodeDao($this->tdbmService);
1937
        $index = $nodeDao->getById(6);
1938
        $json = $index->jsonSerialize();
1939
        // Ignored scalar 'id'
1940
        self::assertTrue(!isset($json['id']));
1941
        // Ignored object 'root'
1942
        self::assertTrue(!isset($json['root']));
1943
        self::assertTrue(isset($json['guests']));
1944
        self::assertTrue(!empty($json['guests']));
1945
        $account = $index->getAccounts()[0];
1946
        $json = $account->jsonSerialize();
1947
        // Ignored array 'nodes' (from nodes_users table)
1948
        self::assertTrue(!isset($json['nodes']));
1949
    }
1950
1951
    /**
1952
     * @depends testDaoGeneration
1953
     */
1954
    public function testJsonInclude(): void
1955
    {
1956
        $nodeDao = new NodeDao($this->tdbmService);
1957
        $index = $nodeDao->getById(6);
1958
        $json = $index->jsonSerialize();
1959
        // Whole chain of parents should be serialized
1960
        self::assertTrue(isset($json['parent']));
1961
        self::assertTrue(isset($json['parent']['parent']));
1962
        self::assertTrue(isset($json['parent']['parent']['parent']));
1963
        self::assertEquals('/', $json['parent']['parent']['parent']['basename']);
1964
    }
1965
1966
    /**
1967
     * @depends testDaoGeneration
1968
     */
1969
    public function testJsonRecursive(): void
1970
    {
1971
        $nodeDao = new NodeDao($this->tdbmService);
1972
        $index = $nodeDao->getById(8);
1973
        $json = $index->jsonSerialize();
1974
        // Original chain of aliases is recursively serialized, ...
1975
        self::assertTrue(isset($json['alias']));
1976
        self::assertTrue(isset($json['alias']['alias']));
1977
        self::assertEquals('index.html', $json['alias']['alias']['basename']);
1978
        // ... each alias even serializes its parents, ...
1979
        self::assertTrue(isset($json['alias']['alias']['parent']['parent']));
1980
        // ... however, parents aliases chains have just their foreign key (id), as parents are serialized with $stopRecursion=true
1981
        self::assertEquals(3, $json['alias']['alias']['parent']['parent']['alias']['id']);
1982
        self::assertCount(1, $json['alias']['alias']['parent']['parent']['alias']);
1983
    }
1984
1985
    /**
1986
     * @depends testDaoGeneration
1987
     */
1988
    public function testJsonFormat(): void
1989
    {
1990
        $nodeDao = new NodeDao($this->tdbmService);
1991
        $index = $nodeDao->getById(6);
1992
        $json = $index->jsonSerialize();
1993
        self::assertTrue(isset($json['size']));
1994
        self::assertEquals('512 o', $json['size']);
1995
        self::assertEquals('42.50g', $json['weight']);
1996
        self::assertEquals($index->getCreatedAt()->format('Y-m-d'), $json['createdAt']);
1997
        self::assertEquals($index->getOwner()->getName(), $json['owner']);
1998
        self::assertEquals($index->getAccounts()[1]->getName(), $json['guests'][1]);
1999
        self::assertTrue(isset($json['entries']));
2000
        self::assertEquals('Hello, World', $json['entries'][1]);
2001
        $www = $index->getParent();
2002
        $json = $www->jsonSerialize();
2003
        self::assertEquals('0 o', $json['size']);
2004
        self::assertNull($json['weight']);
2005
        self::assertNull($json['owner']);
2006
    }
2007
2008
    /**
2009
     * @depends testDaoGeneration
2010
     */
2011
    public function testJsonCollection(): void
2012
    {
2013
        $artists = new ArtistDao($this->tdbmService);
2014
        $pinkFloyd = $artists->getById(1);
2015
        $animals =  $pinkFloyd->getAlbums()[0];
2016
        $json = $pinkFloyd->jsonSerialize();
2017
        // Collection name properly handled ('discography' instead of default 'albums')
2018
        self::assertTrue(isset($json['discography']));
2019
        self::assertEquals($animals->getTitle(), $json['discography'][0]['title']);
2020
        // Make sure top object have just its primary key
2021
        self::assertEquals(1, $json['discography'][0]['artist']['id']);
2022
        self::assertCount(1, $json['discography'][0]['artist']);
2023
        $json = $animals->jsonSerialize();
2024
        // Nevertheless, artist should be serialized in album as top object...
2025
        self::assertTrue(isset($json['artist']));
2026
        // ... as should be tracks...
2027
        self::assertTrue(isset($json['tracks'][0]));
2028
        self::assertEquals('Pigs on the Wing 1', $json['tracks'][0]['title']);
2029
        // ... and, ultimately, list of featuring artists, since feat is included
2030
        self::assertTrue(isset($json['tracks'][0]['feat'][0]));
2031
        self::assertEquals('Roger Waters', $json['tracks'][0]['feat'][0]['name']);
2032
    }
2033
2034
    public function testFloydHasNoParent(): void
2035
    {
2036
        $artists = new ArtistDao($this->tdbmService);
2037
        $pinkFloyd = $artists->getById(1);
2038
        $parents = $pinkFloyd->getParents();
2039
2040
        $this->assertEquals([], $parents);
2041
    }
2042
2043
    public function testFloydHasOneChild(): void
2044
    {
2045
        $artists = new ArtistDao($this->tdbmService);
2046
        $pinkFloyd = $artists->getById(1);
2047
        $children = $pinkFloyd->getChildrenByArtistsRelations();
2048
2049
        $this->assertEquals(1, count($children));
2050
        $this->assertEquals(2, $children[0]->getId());
2051
    }
2052
2053
    /**
2054
     * @depends testDaoGeneration
2055
     */
2056
    public function testAddInterfaceAnnotation(): void
2057
    {
2058
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2059
            // See https://github.com/doctrine/dbal/pull/3512
2060
            $this->markTestSkipped('Only MySQL supports table level comments');
2061
        }
2062
2063
        $refClass = new ReflectionClass(UserBaseBean::class);
2064
        $this->assertTrue($refClass->implementsInterface(TestUserInterface::class));
2065
    }
2066
2067
    /**
2068
     * @depends testDaoGeneration
2069
     */
2070
    public function testAddInterfaceOnDaoAnnotation(): void
2071
    {
2072
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2073
            // See https://github.com/doctrine/dbal/pull/3512
2074
            $this->markTestSkipped('Only MySQL supports table level comments');
2075
        }
2076
2077
        $refClass = new ReflectionClass(UserBaseDao::class);
2078
        $this->assertTrue($refClass->implementsInterface(TestUserDaoInterface::class));
2079
    }
2080
2081
    /**
2082
     * @depends testDaoGeneration
2083
     */
2084
    public function testTrait(): void
2085
    {
2086
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2087
            // See https://github.com/doctrine/dbal/pull/3512
2088
            $this->markTestSkipped('Only MySQL supports table level comments');
2089
        }
2090
2091
        $userDao = new UserDao($this->tdbmService);
2092
        $userBean = $userDao->getById(1);
2093
2094
        $this->assertSame('TestOtherUserTrait', $userBean->method1());
2095
        $this->assertSame('TestUserTrait', $userBean->method1renamed());
2096
2097
        $refClass = new ReflectionClass(UserBaseDao::class);
2098
        $this->assertTrue($refClass->hasMethod('findNothing'));
2099
    }
2100
2101
    /**
2102
     * @depends testDaoGeneration
2103
     */
2104
    public function testNonInstantiableAbstractDaosAndBeans(): void
2105
    {
2106
        $refClass = new ReflectionClass(UserBaseDao::class);
2107
        $this->assertFalse($refClass->isInstantiable());
2108
2109
        $refClass = new ReflectionClass(UserBaseBean::class);
2110
        $this->assertFalse($refClass->isInstantiable());
2111
    }
2112
2113
    /**
2114
     * @depends testDaoGeneration
2115
     */
2116
    public function testCanNullifyBlob(): void
2117
    {
2118
        $article = new ArticleBean('content');
2119
        $fp = fopen(__FILE__, 'r');
2120
        $article->setAttachment($fp);
2121
        $article->setAttachment(null);
2122
        $this->assertNull($article->getAttachment(null));
2123
        fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2123
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2124
    }
2125
2126
    /**
2127
     * @depends testDaoGeneration
2128
     */
2129
    public function testOptionnalParametersCanBeNullInFindOneBy()
2130
    {
2131
        $albumDao = new AlbumDao($this->tdbmService);
2132
        $artist = new ArtistBean('Marcel');
2133
2134
        $albumDao->findOneByArtistAndNode($artist, null);
2135
        $this->assertEquals(1, 1);
2136
    }
2137
2138
    /**
2139
     * @depends testDaoGeneration
2140
     */
2141
    public function testRequiredParametersCannotBeNullInFindOneBy()
2142
    {
2143
        $albumDao = new AlbumDao($this->tdbmService);
2144
        $artist = new ArtistBean('Marcel');
2145
        $account = new AccountBean('Jamie');
2146
2147
        $albumDao->findOneByArtistAndAccount($artist, $account);
2148
2149
        $this->expectException('TypeError');
2150
        $albumDao->findOneByArtistAndAccount($artist, null);
2151
    }
2152
2153
    /**
2154
     * @depends testDaoGeneration
2155
     */
2156
    public function testLazyLoad(): void
2157
    {
2158
        $roleDao = new RoleDao($this->tdbmService);
2159
        $roleBean = $roleDao->getById(1, true);
2160
2161
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2162
        $roleBean->getId();
2163
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2164
    }
2165
2166
    /**
2167
     * @depends testDaoGeneration
2168
     */
2169
    public function testOneToOneInverseRelationGetter(): void
2170
    {
2171
        $objectBaseDao = new BaseObjectDao($this->tdbmService);
2172
        $objectInheritedDao = new InheritedObjectDao($this->tdbmService);
2173
        $objectBase = new BaseObjectBean('label');
2174
        $objectBaseDao->save($objectBase);
2175
        $this->assertNull($objectBase->getInheritedObject());
2176
        $objectInherited = new InheritedObjectBean($objectBase);
2177
        $objectInheritedDao->save($objectInherited);
2178
        $this->assertSame($objectInherited, $objectBase->getInheritedObject());
2179
        $this->assertEquals(1, $objectBase->jsonSerialize()['inheritedObject']['id']);
2180
    }
2181
2182
    public function testLazyStopRecursion(): void
2183
    {
2184
        $albumDao = new AlbumDao($this->tdbmService);
2185
        $albumBean = $albumDao->getById(1);
2186
        $json = $albumBean->jsonSerialize(true);
2187
        $this->assertArrayHasKey('id', $json['artist']);
2188
        $this->assertArrayNotHasKey('name', $json['artist']);
2189
    }
2190
2191
    public function testLazyStopRecursionOnCompositeForeignKey(): void
2192
    {
2193
        $compositeFkSourceDao = new CompositeFkSourceDao($this->tdbmService);
2194
        $compositeFkSourceBean = $compositeFkSourceDao->getById(1);
2195
        $json = $compositeFkSourceBean->jsonSerialize(true);
2196
        $this->assertEquals(1, $json['compositeFkTarget']['id1']);
2197
        $this->assertEquals(1, $json['compositeFkTarget']['id2']);
2198
    }
2199
2200
    public function testMethodNameConflictsBetweenRegularAndAutoPivotProperties(): void
2201
    {
2202
        $artist = new ArtistBean('Super');
2203
        $artist->getChildren(); // regular property
2204
        $artist->getChildrenByArtistId(); // one-to-may relationship
2205
        $artist->getChildrenByArtistsRelations(); // auto-pivot relationship
2206
        $this->assertEquals(1, 1);
2207
    }
2208
2209
    /**
2210
     * @depends testDaoGeneration
2211
     */
2212
    public function testSQLCountWithArray(): void
2213
    {
2214
        $userDao = new TestUserDao($this->tdbmService);
2215
        $countryDao = new CountryDao($this->tdbmService);
2216
2217
        $country = $countryDao->getById(2);
2218
2219
        // Let's test filter bags by bean and filter bag with many values.
2220
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'John Smith'])->take(0, 1);
2221
        $this->assertEquals(1, $users->count());
2222
    }
2223
2224
    /**
2225
     * @depends testDaoGeneration
2226
     */
2227
    public function testSubQueryWithFind(): void
2228
    {
2229
        $userDao = new TestUserDao($this->tdbmService);
2230
        $articleDao = new TestArticleSubQueryDao($this->tdbmService, $userDao);
2231
2232
        $bill = $userDao->getById(4);
2233
        $article = new ArticleBean('Foo');
2234
        $article->setAuthor($bill);
2235
        $articleDao->save($article);
2236
2237
        $results = $articleDao->getArticlesByUserLoginStartingWith('bill');
2238
2239
        $this->assertCount(1, $results);
2240
        $this->assertSame('Foo', $results[0]->getContent());
2241
    }
2242
2243
    public function testSubQueryExceptionOnPrimaryKeysWithMultipleColumns(): void
2244
    {
2245
        $stateDao = new StateDao($this->tdbmService);
2246
        $states = $stateDao->findAll();
2247
        $this->expectException(TDBMException::class);
2248
        $this->expectExceptionMessage('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
2249
        $states->_getSubQuery();
2250
    }
2251
2252
    public function testFindByDateTime(): void
2253
    {
2254
        $personDao = new PersonDao($this->tdbmService);
2255
        $personDao->findByModifiedAt(new \DateTimeImmutable())->count();
2256
        $this->assertTrue(true);
2257
    }
2258
2259
    /**
2260
     * Bug: find from sql use a `COUNT(DISTINCT *)` which fails because of null values.
2261
     */
2262
    public function testFindFromRawSqlCount(): void
2263
    {
2264
        $dao = new TestAlbumDao($this->tdbmService);
2265
        $albums = $dao->findAllFromRawSql();
2266
2267
        $firstAlbum = $albums->first();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $firstAlbum is correct as $albums->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2268
        assert($firstAlbum instanceof AlbumBean);
2269
        $this->assertNull($firstAlbum->getNode()); // This null ensure reproducibility of the bug
2270
        $expectedCount = $dao->findAllFromRawSqlWithCount()->count();
2271
        $this->assertEquals($expectedCount, $albums->count());
2272
    }
2273
2274
    public function testFindFromRawSQLOnInheritance(): void
2275
    {
2276
        $dao = new TestPersonDao($this->tdbmService);
2277
        $objects = $dao->testFindFromRawSQLOnInherited();
2278
2279
        $this->assertNotNull($objects->first());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $objects->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2280
        $this->assertEquals(6, $objects->count());
2281
    }
2282
2283
    public function testGeneratedColumnsAreNotPartOfTheConstructor(): void
2284
    {
2285
        if ($this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform && !self::isMariaDb($this->tdbmService->getConnection())) {
2286
            $this->markTestSkipped('ReadOnly column is only tested with MySQL');
2287
        }
2288
2289
        $dao = new PlayerDao($this->tdbmService);
2290
2291
        $player = new PlayerBean([
2292
            'id' => 1,
2293
            'name' => 'Sally',
2294
            'games_played' =>
2295
                [
2296
                    'Battlefield' =>
2297
                        [
2298
                            'weapon' => 'sniper rifle',
2299
                            'rank' => 'Sergeant V',
2300
                            'level' => 20,
2301
                        ],
2302
                    'Crazy Tennis' =>
2303
                        [
2304
                            'won' => 4,
2305
                            'lost' => 1,
2306
                        ],
2307
                    'Puzzler' =>
2308
                        [
2309
                            'time' => 7,
2310
                        ],
2311
                ],
2312
        ]);
2313
2314
        $dao->save($player);
2315
2316
        $this->assertTrue(true);
2317
    }
2318
2319
    public function testCanReadVirtualColumn(): void
2320
    {
2321
        if ($this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform && !self::isMariaDb($this->tdbmService->getConnection())) {
2322
            $this->markTestSkipped('ReadOnly column is only tested with MySQL');
2323
        }
2324
2325
        $dao = new PlayerDao($this->tdbmService);
2326
2327
        $player = $dao->getById(1);
2328
        $this->assertSame('Sally', $player->getNamesVirtual());
2329
    }
2330
}
2331