Passed
Pull Request — master (#215)
by David
03:14 queued 11s
created

TDBMDaoGeneratorTest::testGetOnAllNullableValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
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\PlayerBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\PlayerBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1637
    }
1638
1639
    /**
1640
     * @depends testDaoGeneration
1641
     */
1642
    public function testTypeHintedConstructors(): void
1643
    {
1644
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1645
        /** @var ReflectionNamedType $nameParam */
1646
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1647
1648
        $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

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

2124
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2125
    }
2126
2127
    /**
2128
     * @depends testDaoGeneration
2129
     */
2130
    public function testOptionnalParametersCanBeNullInFindOneBy()
2131
    {
2132
        $albumDao = new AlbumDao($this->tdbmService);
2133
        $artist = new ArtistBean('Marcel');
2134
2135
        $albumDao->findOneByArtistAndNode($artist, null);
2136
        $this->assertEquals(1, 1);
2137
    }
2138
2139
    /**
2140
     * @depends testDaoGeneration
2141
     */
2142
    public function testRequiredParametersCannotBeNullInFindOneBy()
2143
    {
2144
        $albumDao = new AlbumDao($this->tdbmService);
2145
        $artist = new ArtistBean('Marcel');
2146
        $account = new AccountBean('Jamie');
2147
2148
        $albumDao->findOneByArtistAndAccount($artist, $account);
2149
2150
        $this->expectException('TypeError');
2151
        $albumDao->findOneByArtistAndAccount($artist, null);
2152
    }
2153
2154
    /**
2155
     * @depends testDaoGeneration
2156
     */
2157
    public function testLazyLoad(): void
2158
    {
2159
        $roleDao = new RoleDao($this->tdbmService);
2160
        $roleBean = $roleDao->getById(1, true);
2161
2162
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2163
        $roleBean->getId();
2164
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2165
    }
2166
2167
    /**
2168
     * @depends testDaoGeneration
2169
     */
2170
    public function testOneToOneInverseRelationGetter(): void
2171
    {
2172
        $objectBaseDao = new BaseObjectDao($this->tdbmService);
2173
        $objectInheritedDao = new InheritedObjectDao($this->tdbmService);
2174
        $objectBase = new BaseObjectBean('label');
2175
        $objectBaseDao->save($objectBase);
2176
        $this->assertNull($objectBase->getInheritedObject());
2177
        $objectInherited = new InheritedObjectBean($objectBase);
2178
        $objectInheritedDao->save($objectInherited);
2179
        $this->assertSame($objectInherited, $objectBase->getInheritedObject());
2180
        $this->assertEquals(1, $objectBase->jsonSerialize()['inheritedObject']['id']);
2181
    }
2182
2183
    public function testLazyStopRecursion(): void
2184
    {
2185
        $albumDao = new AlbumDao($this->tdbmService);
2186
        $albumBean = $albumDao->getById(1);
2187
        $json = $albumBean->jsonSerialize(true);
2188
        $this->assertArrayHasKey('id', $json['artist']);
2189
        $this->assertArrayNotHasKey('name', $json['artist']);
2190
    }
2191
2192
    public function testLazyStopRecursionOnCompositeForeignKey(): void
2193
    {
2194
        $compositeFkSourceDao = new CompositeFkSourceDao($this->tdbmService);
2195
        $compositeFkSourceBean = $compositeFkSourceDao->getById(1);
2196
        $json = $compositeFkSourceBean->jsonSerialize(true);
2197
        $this->assertEquals(1, $json['compositeFkTarget']['id1']);
2198
        $this->assertEquals(1, $json['compositeFkTarget']['id2']);
2199
    }
2200
2201
    public function testMethodNameConflictsBetweenRegularAndAutoPivotProperties(): void
2202
    {
2203
        $artist = new ArtistBean('Super');
2204
        $artist->getChildren(); // regular property
2205
        $artist->getChildrenByArtistId(); // one-to-may relationship
2206
        $artist->getChildrenByArtistsRelations(); // auto-pivot relationship
2207
        $this->assertEquals(1, 1);
2208
    }
2209
2210
    /**
2211
     * @depends testDaoGeneration
2212
     */
2213
    public function testSQLCountWithArray(): void
2214
    {
2215
        $userDao = new TestUserDao($this->tdbmService);
2216
        $countryDao = new CountryDao($this->tdbmService);
2217
2218
        $country = $countryDao->getById(2);
2219
2220
        // Let's test filter bags by bean and filter bag with many values.
2221
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'John Smith'])->take(0, 1);
2222
        $this->assertEquals(1, $users->count());
2223
    }
2224
2225
    /**
2226
     * @depends testDaoGeneration
2227
     */
2228
    public function testSubQueryWithFind(): void
2229
    {
2230
        $userDao = new TestUserDao($this->tdbmService);
2231
        $articleDao = new TestArticleSubQueryDao($this->tdbmService, $userDao);
2232
2233
        $bill = $userDao->getById(4);
2234
        $article = new ArticleBean('Foo');
2235
        $article->setAuthor($bill);
2236
        $articleDao->save($article);
2237
2238
        $results = $articleDao->getArticlesByUserLoginStartingWith('bill');
2239
2240
        $this->assertCount(1, $results);
2241
        $this->assertSame('Foo', $results[0]->getContent());
2242
    }
2243
2244
    public function testSubQueryExceptionOnPrimaryKeysWithMultipleColumns(): void
2245
    {
2246
        $stateDao = new StateDao($this->tdbmService);
2247
        $states = $stateDao->findAll();
2248
        $this->expectException(TDBMException::class);
2249
        $this->expectExceptionMessage('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
2250
        $states->_getSubQuery();
2251
    }
2252
2253
    public function testFindByDateTime(): void
2254
    {
2255
        $personDao = new PersonDao($this->tdbmService);
2256
        $personDao->findByModifiedAt(new \DateTimeImmutable())->count();
2257
        $this->assertTrue(true);
2258
    }
2259
2260
    /**
2261
     * Bug: find from sql use a `COUNT(DISTINCT *)` which fails because of null values.
2262
     */
2263
    public function testFindFromRawSqlCount(): void
2264
    {
2265
        $dao = new TestAlbumDao($this->tdbmService);
2266
        $albums = $dao->findAllFromRawSql();
2267
2268
        $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...
2269
        assert($firstAlbum instanceof AlbumBean);
2270
        $this->assertNull($firstAlbum->getNode()); // This null ensure reproducibility of the bug
2271
        $expectedCount = $dao->findAllFromRawSqlWithCount()->count();
2272
        $this->assertEquals($expectedCount, $albums->count());
2273
    }
2274
2275
    public function testFindFromRawSQLOnInheritance(): void
2276
    {
2277
        $dao = new TestPersonDao($this->tdbmService);
2278
        $objects = $dao->testFindFromRawSQLOnInherited();
2279
2280
        $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...
2281
        $this->assertEquals(6, $objects->count());
2282
    }
2283
2284
    public function testGeneratedColumnsAreNotPartOfTheConstructor(): void
2285
    {
2286
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform || self::isMariaDb($this->tdbmService->getConnection())) {
2287
            $this->markTestSkipped('ReadOnly column is only tested with MySQL');
2288
        }
2289
2290
        $dao = new PlayerDao($this->tdbmService);
2291
2292
        $player = new PlayerBean([
2293
            'id' => 1,
2294
            'name' => 'Sally',
2295
            'games_played' =>
2296
                [
2297
                    'Battlefield' =>
2298
                        [
2299
                            'weapon' => 'sniper rifle',
2300
                            'rank' => 'Sergeant V',
2301
                            'level' => 20,
2302
                        ],
2303
                    'Crazy Tennis' =>
2304
                        [
2305
                            'won' => 4,
2306
                            'lost' => 1,
2307
                        ],
2308
                    'Puzzler' =>
2309
                        [
2310
                            'time' => 7,
2311
                        ],
2312
                ],
2313
        ]);
2314
2315
        $dao->save($player);
2316
2317
        $this->assertTrue(true);
2318
    }
2319
2320
    public function testCanReadVirtualColumn(): void
2321
    {
2322
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform || self::isMariaDb($this->tdbmService->getConnection())) {
2323
            $this->markTestSkipped('ReadOnly column is only tested with MySQL');
2324
        }
2325
2326
        $dao = new PlayerDao($this->tdbmService);
2327
2328
        $player = $dao->getById(1);
2329
        $this->assertSame('Sally', $player->getNamesVirtual());
2330
    }
2331
}
2332