Passed
Pull Request — master (#208)
by David
08:37
created

TDBMDaoGeneratorTest::testSetToNullForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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