Passed
Pull Request — master (#172)
by David
03:49
created

TDBMDaoGeneratorTest::testManyToOneEagerLoading()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 19
rs 9.8666
cc 3
nc 4
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 TheCodingMachine\TDBM\Dao\TestArticleDao;
34
use TheCodingMachine\TDBM\Dao\TestArticleSubQueryDao;
35
use TheCodingMachine\TDBM\Dao\TestCountryDao;
36
use TheCodingMachine\TDBM\Dao\TestRoleDao;
37
use TheCodingMachine\TDBM\Dao\TestUserDao;
38
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserDaoInterface;
39
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserInterface;
40
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...
41
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...
42
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...
43
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...
44
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...
45
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...
46
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...
47
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...
48
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...
49
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...
50
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...
51
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...
52
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...
53
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...
54
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...
55
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...
56
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...
57
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...
58
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...
59
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...
60
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...
61
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...
62
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...
63
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...
64
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...
65
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...
66
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...
67
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...
68
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...
69
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...
70
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...
71
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...
72
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...
73
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...
74
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...
75
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...
76
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...
77
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...
78
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...
79
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...
80
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...
81
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...
82
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...
83
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...
84
use TheCodingMachine\TDBM\Utils\PathFinder\NoPathFoundException;
85
use TheCodingMachine\TDBM\Utils\PathFinder\PathFinder;
86
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
87
use Symfony\Component\Process\Process;
88
89
class TDBMDaoGeneratorTest extends TDBMAbstractServiceTest
90
{
91
    /** @var TDBMDaoGenerator $tdbmDaoGenerator */
92
    protected $tdbmDaoGenerator;
93
94
    private $rootPath;
95
96
    protected function setUp(): void
97
    {
98
        parent::setUp();
99
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
100
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
101
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
102
        $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
103
        $this->rootPath = __DIR__ . '/../';
104
        //$this->tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
105
    }
106
107
    public function testDaoGeneration(): void
108
    {
109
        // Remove all previously generated files.
110
        $this->recursiveDelete($this->rootPath . 'src/Test/Dao/');
111
        mkdir($this->rootPath . 'src/Test/Dao/Generated', 0755, true);
112
        // Let's generate a dummy file to see it is indeed removed.
113
        $dummyFile = $this->rootPath . 'src/Test/Dao/Generated/foobar.php';
114
        touch($dummyFile);
115
        $this->assertFileExists($dummyFile);
116
117
        $this->tdbmDaoGenerator->generateAllDaosAndBeans();
118
119
        $this->assertFileNotExists($dummyFile);
120
121
        // Let's require all files to check they are valid PHP!
122
        // Test the daoFactory
123
        require_once $this->rootPath . 'src/Test/Dao/Generated/DaoFactory.php';
124
        // Test the others
125
126
        $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
127
128
        foreach ($beanDescriptors as $beanDescriptor) {
129
            $daoName = $beanDescriptor->getDaoClassName();
130
            $daoBaseName = $beanDescriptor->getBaseDaoClassName();
131
            $beanName = $beanDescriptor->getBeanClassName();
132
            $baseBeanName = $beanDescriptor->getBaseBeanClassName();
133
            require_once $this->rootPath . 'src/Test/Dao/Bean/Generated/' . $baseBeanName . '.php';
134
            require_once $this->rootPath . 'src/Test/Dao/Bean/' . $beanName . '.php';
135
            require_once $this->rootPath . 'src/Test/Dao/Generated/' . $daoBaseName . '.php';
136
            require_once $this->rootPath . 'src/Test/Dao/' . $daoName . '.php';
137
        }
138
139
        // Check that pivot tables do not generate DAOs or beans.
140
        $this->assertFalse(class_exists('TheCodingMachine\\TDBM\\Test\\Dao\\RolesRightDao'));
141
    }
142
143
    public function testGenerationException(): void
144
    {
145
        $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', self::getConnection(), $this->getNamingStrategy());
146
147
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
148
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
149
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
150
        $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
151
        $this->rootPath = __DIR__ . '/../../../../';
152
        //$tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
153
154
        $this->expectException(NoPathFoundException::class);
155
        $tdbmDaoGenerator->generateAllDaosAndBeans();
156
    }
157
158
    /**
159
     * Delete a file or recursively delete a directory.
160
     *
161
     * @param string $str Path to file or directory
162
     * @return bool
163
     */
164
    private function recursiveDelete(string $str): bool
165
    {
166
        if (is_file($str)) {
167
            return @unlink($str);
168
        } elseif (is_dir($str)) {
169
            $scan = glob(rtrim($str, '/') . '/*');
170
            foreach ($scan as $index => $path) {
171
                $this->recursiveDelete($path);
172
            }
173
174
            return @rmdir($str);
175
        }
176
        return false;
177
    }
178
179
    /**
180
     * @depends testDaoGeneration
181
     */
182
    public function testGetBeanClassName(): void
183
    {
184
        $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
185
186
        // Let's create another TDBMService to test the cache.
187
        $configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), $this->getNamingStrategy(), $this->getCache(), null, null, [$this->getDummyGeneratorListener()]);
188
        $configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 4)));
189
        $newTdbmService = new TDBMService($configuration);
190
        $this->assertEquals(UserBean::class, $newTdbmService->getBeanClassName('users'));
191
    }
192
193
    /**
194
     * @depends testDaoGeneration
195
     */
196
    public function testGeneratedGetById(): void
197
    {
198
        $contactDao = new ContactDao($this->tdbmService);
199
        $contactBean = $contactDao->getById(1);
200
        $this->assertEquals(1, $contactBean->getId());
201
        $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
202
203
        // FIXME: Question: que faire du paramètre stockage "UTC"????
204
    }
205
206
    /**
207
     * @depends testDaoGeneration
208
     */
209
    public function testGeneratedGetByIdLazyLoaded(): void
210
    {
211
        $roleDao = new RoleDao($this->tdbmService);
212
        $roleBean = $roleDao->getById(1, true);
213
        $this->assertEquals(1, $roleBean->getId());
214
        $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
215
216
        $roleBean2 = $roleDao->getById(1, true);
217
        $this->assertTrue($roleBean === $roleBean2);
218
    }
219
220
    /**
221
     * @depends testDaoGeneration
222
     */
223
    public function testDefaultValueOnNewBean(): void
224
    {
225
        $roleBean = new RoleBean('my_role');
226
        $this->assertEquals(1, $roleBean->getStatus());
227
    }
228
229
    /**
230
     * @depends testDaoGeneration
231
     */
232
    public function testForeignKeyInBean(): void
233
    {
234
        $userDao = new UserDao($this->tdbmService);
235
        $userBean = $userDao->getById(1);
236
        $country = $userBean->getCountry();
237
238
        $this->assertEquals('UK', $country->getLabel());
239
240
        $userBean2 = $userDao->getById(1);
241
        $this->assertTrue($userBean === $userBean2);
242
243
        $contactDao = new ContactDao($this->tdbmService);
244
        $contactBean = $contactDao->getById(1);
245
246
        $this->assertTrue($userBean === $contactBean);
247
    }
248
249
    /**
250
     * @depends testDaoGeneration
251
     */
252
    public function testNewBeans(): void
253
    {
254
        $countryDao = new CountryDao($this->tdbmService);
255
        $userDao = new UserDao($this->tdbmService);
256
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
257
        $userBean->setOrder(1); // Let's set a "protected keyword" column.
258
259
        $userDao->save($userBean);
260
261
        $this->assertNull($userBean->getManager());
262
    }
263
264
    /**
265
     * @depends testDaoGeneration
266
     */
267
    public function testDateTimeImmutableGetter(): void
268
    {
269
        $userDao = new UserDao($this->tdbmService);
270
        $user = $userDao->getById(1);
271
272
        $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
273
    }
274
275
    /**
276
     * @depends testDaoGeneration
277
     */
278
    public function testAssigningNewBeans(): void
279
    {
280
        $userDao = new UserDao($this->tdbmService);
281
        $countryBean = new CountryBean('Mexico');
282
        $userBean = new UserBean('Speedy Gonzalez', '[email protected]', $countryBean, 'speedy.gonzalez');
283
        $this->assertEquals($countryBean, $userBean->getCountry());
284
285
        $userDao->save($userBean);
286
    }
287
288
    /**
289
     * @depends testAssigningNewBeans
290
     */
291
    public function testUpdatingProtectedColumn(): void
292
    {
293
        $userDao = new UserDao($this->tdbmService);
294
        $userBean = $userDao->findOneByLogin('speedy.gonzalez');
295
        $userBean->setOrder(2);
296
        $userDao->save($userBean);
297
        $this->assertSame(2, $userBean->getOrder());
298
    }
299
300
    /**
301
     * @depends testDaoGeneration
302
     */
303
    public function testAssigningExistingRelationship(): void
304
    {
305
        $userDao = new UserDao($this->tdbmService);
306
        $user = $userDao->getById(1);
307
        $countryDao = new CountryDao($this->tdbmService);
308
        $country = $countryDao->getById(2);
309
310
        $user->setCountry($country);
311
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
312
    }
313
314
    /**
315
     * @depends testDaoGeneration
316
     */
317
    public function testDirectReversedRelationship(): void
318
    {
319
        $countryDao = new CountryDao($this->tdbmService);
320
        $country = $countryDao->getById(1);
321
        $users = $country->getUsers();
322
323
        $arr = $users->toArray();
324
325
        $this->assertCount(1, $arr);
326
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
327
        $this->assertEquals('jean.dupont', $arr[0]->getLogin());
328
329
        $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...
330
        $users = $country->getUsers();
331
332
        $arr = $users->toArray();
333
334
        $this->assertCount(2, $arr);
335
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
336
        $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
337
    }
338
339
    /**
340
     * @depends testDaoGeneration
341
     */
342
    public function testDeleteInDirectReversedRelationship(): void
343
    {
344
        $countryDao = new CountryDao($this->tdbmService);
345
        $country = $countryDao->getById(1);
346
347
        $userDao = new UserDao($this->tdbmService);
348
        $newUser = new UserBean('John Snow', '[email protected]', $country, 'john.snow');
349
        $userDao->save($newUser);
350
351
        $users = $country->getUsers();
352
353
        $arr = $users->toArray();
354
355
        $this->assertCount(2, $arr);
356
357
        $userDao->delete($arr[1]);
358
359
        $users = $country->getUsers();
360
        $arr = $users->toArray();
361
        $this->assertCount(1, $arr);
362
    }
363
364
    /**
365
     * @depends testDaoGeneration
366
     */
367
    public function testJointureGetters(): void
368
    {
369
        $roleDao = new RoleDao($this->tdbmService);
370
        $role = $roleDao->getById(1);
371
        $users = $role->getUsers();
372
373
        $this->assertCount(2, $users);
374
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
375
376
        $rights = $role->getRights();
377
378
        $this->assertCount(2, $rights);
379
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
380
    }
381
382
    /**
383
     * @depends testDaoGeneration
384
     */
385
    public function testNestedIterationOnAlterableResultIterator(): void
386
    {
387
        $countryDao = new CountryDao($this->tdbmService);
388
        $country = $countryDao->getById(2);
389
390
        $count = 0;
391
        // Let's perform 2 nested calls to check that iterators do not melt.
392
        foreach ($country->getUsers() as $user) {
393
            foreach ($country->getUsers() as $user2) {
394
                $count++;
395
            }
396
        }
397
        // There are 3 users linked to country 2.
398
        $this->assertSame(9, $count);
399
    }
400
401
    /**
402
     * @depends testDaoGeneration
403
     */
404
    public function testNewBeanConstructor(): void
405
    {
406
        $role = new RoleBean('Newrole');
407
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
408
    }
409
410
    /**
411
     * @depends testDaoGeneration
412
     */
413
    public function testJointureAdderOnNewBean(): void
414
    {
415
        $countryDao = new CountryDao($this->tdbmService);
416
        $country = $countryDao->getById(1);
417
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
418
        $role = new RoleBean('Mouse');
419
        $user->addRole($role);
420
        $roles = $user->getRoles();
421
        $this->assertCount(1, $roles);
422
        $role = $roles[0];
423
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
424
        $users = $role->getUsers();
425
        $this->assertCount(1, $users);
426
        $this->assertEquals($user, $users[0]);
427
428
        $role->removeUser($user);
429
        $this->assertCount(0, $role->getUsers());
430
        $this->assertCount(0, $user->getRoles());
431
    }
432
433
    /**
434
     * @depends testDaoGeneration
435
     */
436
    public function testJointureDeleteBeforeGetters(): void
437
    {
438
        $roleDao = new RoleDao($this->tdbmService);
439
        $userDao = new UserDao($this->tdbmService);
440
        $role = $roleDao->getById(1);
441
        $user = $userDao->getById(1);
442
443
        // We call removeUser BEFORE calling getUsers
444
        // This should work as expected.
445
        $role->removeUser($user);
446
        $users = $role->getUsers();
447
448
        $this->assertCount(1, $users);
449
    }
450
451
    /**
452
     * @depends testDaoGeneration
453
     */
454
    public function testJointureMultiAdd(): void
455
    {
456
        $countryDao = new CountryDao($this->tdbmService);
457
        $country = $countryDao->getById(1);
458
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
459
        $role = new RoleBean('Mouse');
460
        $user->addRole($role);
461
        $role->addUser($user);
462
        $user->addRole($role);
463
464
        $this->assertCount(1, $user->getRoles());
465
    }
466
467
    /**
468
     * Step 1: we remove the role 1 from user 1 but save role 1.
469
     * Expected result: no save done.
470
     *
471
     * @depends testDaoGeneration
472
     */
473
    public function testJointureSave1(): void
474
    {
475
        $roleDao = new RoleDao($this->tdbmService);
476
        $role = $roleDao->getById(1);
477
        $userDao = new UserDao($this->tdbmService);
478
        $user = $userDao->getById(1);
479
480
        $this->assertTrue($user->hasRole($role));
481
        $this->assertTrue($role->hasUser($user));
482
        $user->removeRole($role);
483
        $this->assertFalse($user->hasRole($role));
484
        $this->assertFalse($role->hasUser($user));
485
        $roleDao->save($role);
486
487
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
488
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
489
    }
490
491
    /**
492
     * Step 2: we check that nothing was saved
493
     * Expected result: no save done.
494
     *
495
     * @depends testJointureSave1
496
     */
497
    public function testJointureSave2(): void
498
    {
499
        $roleDao = new RoleDao($this->tdbmService);
500
        $role = $roleDao->getById(1);
501
        $this->assertCount(2, $role->getUsers());
502
    }
503
504
    /**
505
     * Step 3: we remove the role 1 from user 1 and save user 1.
506
     * Expected result: save done.
507
     *
508
     * @depends testJointureSave2
509
     */
510
    public function testJointureSave3(): void
511
    {
512
        $roleDao = new RoleDao($this->tdbmService);
513
        $role = $roleDao->getById(1);
514
        $userDao = new UserDao($this->tdbmService);
515
        $user = $userDao->getById(1);
516
517
        $this->assertCount(1, $user->getRoles());
518
        $user->removeRole($role);
519
        $this->assertCount(0, $user->getRoles());
520
        $userDao->save($user);
521
        $this->assertCount(0, $user->getRoles());
522
    }
523
524
    /**
525
     * Step 4: we check that save was done
526
     * Expected result: save done.
527
     *
528
     * @depends testJointureSave3
529
     */
530
    public function testJointureSave4(): void
531
    {
532
        $roleDao = new RoleDao($this->tdbmService);
533
        $role = $roleDao->getById(1);
534
        $this->assertCount(1, $role->getUsers());
535
        $userDao = new UserDao($this->tdbmService);
536
        $user = $userDao->getById(1);
537
        $this->assertCount(0, $user->getRoles());
538
    }
539
540
    /**
541
     * Step 5: we add the role 1 from user 1 and save user 1.
542
     * Expected result: save done.
543
     *
544
     * @depends testJointureSave4
545
     */
546
    public function testJointureSave5(): void
547
    {
548
        $roleDao = new RoleDao($this->tdbmService);
549
        $role = $roleDao->getById(1);
550
        $userDao = new UserDao($this->tdbmService);
551
        $user = $userDao->getById(1);
552
553
        $user->addRole($role);
554
        $this->assertCount(1, $user->getRoles());
555
        $userDao->save($user);
556
    }
557
558
    /**
559
     * Step 6: we check that save was done
560
     * Expected result: save done.
561
     *
562
     * @depends testJointureSave5
563
     */
564
    public function testJointureSave6(): void
565
    {
566
        $roleDao = new RoleDao($this->tdbmService);
567
        $role = $roleDao->getById(1);
568
        $this->assertCount(2, $role->getUsers());
569
        $userDao = new UserDao($this->tdbmService);
570
        $user = $userDao->getById(1);
571
        $this->assertCount(1, $user->getRoles());
572
    }
573
574
    /**
575
     * Step 7: we add a new role to user 1 and save user 1.
576
     * Expected result: save done, including the new role.
577
     *
578
     * @depends testJointureSave6
579
     */
580
    public function testJointureSave7(): void
581
    {
582
        $role = new RoleBean('my new role');
583
        $userDao = new UserDao($this->tdbmService);
584
        $user = $userDao->getById(1);
585
586
        $user->addRole($role);
587
        $userDao->save($user);
588
589
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
590
    }
591
592
    /**
593
     * Step 8: we check that save was done
594
     * Expected result: save done.
595
     *
596
     * @depends testJointureSave7
597
     */
598
    public function testJointureSave8(): void
599
    {
600
        $roleDao = new RoleDao($this->tdbmService);
601
        $userDao = new UserDao($this->tdbmService);
602
        $user = $userDao->getById(1);
603
604
        $roles = $user->getRoles();
605
        foreach ($roles as $role) {
606
            if ($role->getName() === 'my new role') {
607
                $selectedRole = $role;
608
                break;
609
            }
610
        }
611
        $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...
612
613
        $this->assertCount(2, $user->getRoles());
614
615
        // Expected: relationship removed!
616
        $roleDao->delete($selectedRole);
617
618
        $this->assertCount(1, $user->getRoles());
619
    }
620
621
    /**
622
     * Step 9: Let's test the setXXX method.
623
     *
624
     * @depends testJointureSave8
625
     */
626
    public function testJointureSave9(): void
627
    {
628
        $roleDao = new RoleDao($this->tdbmService);
629
        $userDao = new UserDao($this->tdbmService);
630
        $user = $userDao->getById(1);
631
632
        // At this point, user 1 is linked to role 1.
633
        // Let's bind it to role 2.
634
        $user->setRoles([$roleDao->getById(2)]);
635
        $userDao->save($user);
636
        $this->assertTrue($user->hasRole($roleDao->getById(2)));
637
    }
638
639
    /**
640
     * Step 10: Let's check results of 9.
641
     *
642
     * @depends testJointureSave9
643
     */
644
    public function testJointureSave10(): void
645
    {
646
        $userDao = new UserDao($this->tdbmService);
647
        $user = $userDao->getById(1);
648
649
        $roles = $user->getRoles();
650
651
        $this->assertCount(1, $roles);
652
        $this->assertEquals(2, $roles[0]->getId());
653
    }
654
655
    /**
656
     * Test jointure in a parent table in an inheritance relationship
657
     *
658
     * @depends testDaoGeneration
659
     */
660
    public function testJointureInParentTable(): void
661
    {
662
        $userDao = new UserDao($this->tdbmService);
663
        $user = $userDao->getById(1);
664
665
        $boats = $user->getBoats();
666
667
        $this->assertCount(1, $boats);
668
        $this->assertEquals(1, $boats[0]->getId());
669
    }
670
671
    /**
672
     * @depends testDaoGeneration
673
     */
674
    public function testFindOrderBy(): void
675
    {
676
        $userDao = new TestUserDao($this->tdbmService);
677
        $users = $userDao->getUsersByAlphabeticalOrder();
678
679
        $this->assertCount(6, $users);
680
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
681
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
682
683
        $users = $userDao->getUsersByCountryOrder();
684
        $this->assertCount(6, $users);
685
        $countryName1 = $users[0]->getCountry()->getLabel();
686
        for ($i = 1; $i < 6; $i++) {
687
            $countryName2 = $users[$i]->getCountry()->getLabel();
688
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
689
            $countryName1 = $countryName2;
690
        }
691
    }
692
693
    /**
694
     * @depends testDaoGeneration
695
     */
696
    public function testFindFromSqlOrderBy(): void
697
    {
698
        $userDao = new TestUserDao($this->tdbmService);
699
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
700
701
        $this->assertCount(6, $users);
702
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
703
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
704
705
        $users = $userDao->getUsersFromSqlByCountryOrder();
706
        $this->assertCount(6, $users);
707
        $countryName1 = $users[0]->getCountry()->getLabel();
708
        for ($i = 1; $i < 6; $i++) {
709
            $countryName2 = $users[$i]->getCountry()->getLabel();
710
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
711
            $countryName1 = $countryName2;
712
        }
713
    }
714
715
    /**
716
     * @depends testDaoGeneration
717
     */
718
    public function testFindFromSqlOrderByOnInheritedBean(): void
719
    {
720
        $articleDao = new TestArticleDao($this->tdbmService);
721
        $articles = $articleDao->getArticlesByUserLogin();
722
723
        foreach ($articles as $article) {
724
            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...
725
        }
726
        $this->assertCount(0, $articles);
727
    }
728
729
730
    /**
731
     * @depends testDaoGeneration
732
     */
733
    public function testFindFromSqlOrderByJoinRole(): void
734
    {
735
        $roleDao = new TestRoleDao($this->tdbmService);
736
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
737
738
        $this->assertCount(2, $roles);
739
        $this->assertEquals('Singers', $roles[0]->getName());
740
        $this->assertEquals('Admins', $roles[1]->getName());
741
    }
742
743
    /**
744
     * @depends testDaoGeneration
745
     */
746
    public function testFindFromRawSqlOrderByUserCount(): void
747
    {
748
        $countryDao = new TestCountryDao($this->tdbmService);
749
        $countries = $countryDao->getCountriesByUserCount();
750
751
        $this->assertCount(4, $countries);
752
        for ($i = 1; $i < count($countries); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
753
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
754
        }
755
    }
756
757
    /**
758
     * @depends testDaoGeneration
759
     */
760
    public function testFindFromRawSqlWithUnion(): void
761
    {
762
        $countryDao = new TestCountryDao($this->tdbmService);
763
        $countries = $countryDao->getCountriesUsingUnion();
764
765
        $this->assertCount(2, $countries);
766
        $this->assertEquals(1, $countries[0]->getId());
767
    }
768
769
    /**
770
     * @depends testDaoGeneration
771
     */
772
    public function testFindFromRawSqlWithSimpleQuery(): void
773
    {
774
        $countryDao = new TestCountryDao($this->tdbmService);
775
        $countries = $countryDao->getCountriesUsingSimpleQuery();
776
777
        $this->assertCount(1, $countries);
778
        $this->assertEquals(1, $countries[0]->getId());
779
    }
780
781
    /**
782
     * @depends testDaoGeneration
783
     */
784
    public function testFindFromRawSqlWithDistinctQuery(): void
785
    {
786
        $countryDao = new TestCountryDao($this->tdbmService);
787
        $countries = $countryDao->getCountriesUsingDistinctQuery();
788
789
        $this->assertCount(1, $countries);
790
        $this->assertEquals(2, $countries[0]->getId());
791
    }
792
793
    /**
794
     * @depends testDaoGeneration
795
     */
796
    public function testFindFilters(): void
797
    {
798
        $userDao = new TestUserDao($this->tdbmService);
799
        $users = $userDao->getUsersByLoginStartingWith('bill');
800
801
        $this->assertCount(1, $users);
802
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
803
    }
804
805
    /**
806
     * @depends testDaoGeneration
807
     */
808
    public function testFindMode(): void
809
    {
810
        $userDao = new TestUserDao($this->tdbmService);
811
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
812
813
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
814
        $users[0];
815
    }
816
817
    /**
818
     * @depends testDaoGeneration
819
     */
820
    public function testFindAll(): void
821
    {
822
        $userDao = new TestUserDao($this->tdbmService);
823
        $users = $userDao->findAll();
824
825
        $this->assertCount(6, $users);
826
    }
827
828
    /**
829
     * @depends testDaoGeneration
830
     */
831
    public function testFindOne(): void
832
    {
833
        $userDao = new TestUserDao($this->tdbmService);
834
        $user = $userDao->getUserByLogin('bill.shakespeare');
835
836
        $this->assertEquals('bill.shakespeare', $user->getLogin());
837
    }
838
839
    /**
840
     * @depends testDaoGeneration
841
     */
842
    public function testJsonEncodeBean(): void
843
    {
844
        $userDao = new TestUserDao($this->tdbmService);
845
        $user = $userDao->getUserByLogin('bill.shakespeare');
846
847
        $jsonEncoded = json_encode($user);
848
        $userDecoded = json_decode($jsonEncoded, true);
849
850
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
851
852
        // test serialization of dates.
853
        $this->assertTrue(is_string($userDecoded['createdAt']));
854
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
855
        $this->assertNull($userDecoded['modifiedAt']);
856
857
        // testing many to 1 relationships
858
        $this->assertEquals('UK', $userDecoded['country']['label']);
859
860
        // testing many to many relationships
861
        $this->assertCount(1, $userDecoded['roles']);
862
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
863
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
864
    }
865
866
    /**
867
     * @depends testDaoGeneration
868
     */
869
    public function testNullableForeignKey(): void
870
    {
871
        $userDao = new TestUserDao($this->tdbmService);
872
        $user = $userDao->getUserByLogin('john.smith');
873
874
        $this->assertNull($user->getManager());
875
876
        $jsonEncoded = json_encode($user);
877
        $userDecoded = json_decode($jsonEncoded, true);
878
879
        $this->assertNull($userDecoded['manager']);
880
    }
881
882
    /**
883
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
884
     *
885
     * @depends testDaoGeneration
886
     */
887
    public function testSetToNullForeignKey(): void
888
    {
889
        $userDao = new TestUserDao($this->tdbmService);
890
        $user = $userDao->getUserByLogin('john.smith');
891
        $manager = $userDao->getUserByLogin('jean.dupont');
892
893
        $user->setManager($manager);
894
        $userDao->save($user);
895
896
        $user->setManager(null);
897
        $userDao->save($user);
898
        $this->assertNull($user->getManager());
899
    }
900
901
    /**
902
     * @depends testDaoGeneration
903
     */
904
    public function testQueryOnWrongTableName(): void
905
    {
906
        $userDao = new TestUserDao($this->tdbmService);
907
        $users = $userDao->getUsersWrongTableName();
908
        $this->expectException('Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException');
909
        $this->expectExceptionMessage('Could not find table \'contacts\'. Did you mean \'contact\'?');
910
        $users->count();
911
    }
912
913
    /**
914
     * @depends testDaoGeneration
915
     */
916
    /*public function testQueryNullForeignKey(): void
917
    {
918
        $userDao = new TestUserDao($this->tdbmService);
919
        $users = $userDao->getUsersByManagerId(null);
920
        $this->assertCount(3, $users);
921
    }*/
922
923
    /**
924
     * @depends testDaoGeneration
925
     */
926
    public function testInnerJsonEncode(): void
927
    {
928
        $userDao = new TestUserDao($this->tdbmService);
929
        $user = $userDao->getUserByLogin('bill.shakespeare');
930
931
        $jsonEncoded = json_encode(['user' => $user]);
932
        $msgDecoded = json_decode($jsonEncoded, true);
933
934
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
935
    }
936
937
    /**
938
     * @depends testDaoGeneration
939
     */
940
    public function testArrayJsonEncode(): void
941
    {
942
        $userDao = new TestUserDao($this->tdbmService);
943
        $users = $userDao->getUsersByLoginStartingWith('bill');
944
945
        $jsonEncoded = json_encode($users);
946
        $msgDecoded = json_decode($jsonEncoded, true);
947
948
        $this->assertCount(1, $msgDecoded);
949
    }
950
951
    /**
952
     * @depends testDaoGeneration
953
     */
954
    public function testCursorJsonEncode(): void
955
    {
956
        $userDao = new TestUserDao($this->tdbmService);
957
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
958
959
        $jsonEncoded = json_encode($users);
960
        $msgDecoded = json_decode($jsonEncoded, true);
961
962
        $this->assertCount(1, $msgDecoded);
963
    }
964
965
    /**
966
     * @depends testDaoGeneration
967
     */
968
    public function testPageJsonEncode(): void
969
    {
970
        $userDao = new TestUserDao($this->tdbmService);
971
        $users = $userDao->getUsersByLoginStartingWith('bill');
972
973
        $jsonEncoded = json_encode($users->take(0, 1));
974
        $msgDecoded = json_decode($jsonEncoded, true);
975
976
        $this->assertCount(1, $msgDecoded);
977
    }
978
979
    /**
980
     * @depends testDaoGeneration
981
     */
982
    public function testInnerResultIteratorCountAfterFetch(): void
983
    {
984
        $userDao = new TestUserDao($this->tdbmService);
985
        $users = $userDao->getUsersByLoginStartingWith('j')->take(0, 4);
986
        $users->toArray(); // We force to fetch
987
        $this->assertEquals(3, $users->count());
988
    }
989
990
    /**
991
     * @depends testDaoGeneration
992
     */
993
    public function testFirst(): void
994
    {
995
        $userDao = new TestUserDao($this->tdbmService);
996
        $users = $userDao->getUsersByLoginStartingWith('bill');
997
998
        $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...
999
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
1000
    }
1001
1002
    /**
1003
     * @depends testDaoGeneration
1004
     */
1005
    public function testFirstNull(): void
1006
    {
1007
        $userDao = new TestUserDao($this->tdbmService);
1008
        $users = $userDao->getUsersByLoginStartingWith('mike');
1009
1010
        $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...
1011
        $this->assertNull($user);
1012
    }
1013
1014
    /**
1015
     * @depends testDaoGeneration
1016
     */
1017
    public function testCloneBeanAttachedBean(): void
1018
    {
1019
        $userDao = new TestUserDao($this->tdbmService);
1020
        $user = $userDao->getUserByLogin('bill.shakespeare');
1021
        $this->assertEquals(4, $user->getId());
1022
        $user2 = clone $user;
1023
        $this->assertNull($user2->getId());
1024
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
1025
        $this->assertEquals('Bill Shakespeare', $user2->getName());
1026
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1027
1028
        // MANY 2 MANY must be duplicated
1029
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
1030
1031
        // Let's test saving this clone
1032
        $user2->setLogin('william.shakespeare');
1033
        $userDao->save($user2);
1034
1035
        $user3 = $userDao->getUserByLogin('william.shakespeare');
1036
        $this->assertTrue($user3 === $user2);
1037
        $userDao->delete($user3);
1038
1039
        // Finally, let's test the origin user still exists!
1040
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
1041
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
1042
    }
1043
1044
    /**
1045
     * @depends testDaoGeneration
1046
     */
1047
    public function testCloneNewBean(): void
1048
    {
1049
        $countryDao = new CountryDao($this->tdbmService);
1050
        $roleDao = new RoleDao($this->tdbmService);
1051
        $role = $roleDao->getById(1);
1052
1053
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
1054
        $userBean->addRole($role);
1055
1056
        $user2 = clone $userBean;
1057
1058
        $this->assertNull($user2->getId());
1059
        $this->assertEquals('john.doe', $user2->getLogin());
1060
        $this->assertEquals('John Doe', $user2->getName());
1061
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1062
1063
        // MANY 2 MANY must be duplicated
1064
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
1065
    }
1066
1067
    /**
1068
     * @depends testDaoGeneration
1069
     */
1070
    public function testCascadeDelete(): void
1071
    {
1072
        $userDao = new TestUserDao($this->tdbmService);
1073
        $countryDao = new CountryDao($this->tdbmService);
1074
1075
        $spain = new CountryBean('Spain');
1076
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1077
1078
        $countryDao->save($spain);
1079
        $userDao->save($sanchez);
1080
1081
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1082
        $this->assertTrue($sanchez === $speedy2);
1083
1084
        $exceptionTriggered = false;
1085
        try {
1086
            $countryDao->delete($spain);
1087
        } catch (ForeignKeyConstraintViolationException $e) {
1088
            $exceptionTriggered = true;
1089
        }
1090
        $this->assertTrue($exceptionTriggered);
1091
1092
        $countryDao->delete($spain, true);
1093
1094
        // Let's check that speed gonzalez was removed.
1095
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1096
        $this->assertNull($speedy3);
1097
    }
1098
1099
    /**
1100
     * @depends testDaoGeneration
1101
     */
1102
    public function testDiscardChanges(): void
1103
    {
1104
        $contactDao = new ContactDao($this->tdbmService);
1105
        $contactBean = $contactDao->getById(1);
1106
1107
        $oldName = $contactBean->getName();
1108
1109
        $contactBean->setName('MyNewName');
1110
1111
        $contactBean->discardChanges();
1112
1113
        $this->assertEquals($oldName, $contactBean->getName());
1114
    }
1115
1116
    /**
1117
     * @depends testDaoGeneration
1118
     */
1119
    public function testDiscardChangesOnNewBeanFails(): void
1120
    {
1121
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1122
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
1123
        $person->discardChanges();
1124
    }
1125
1126
    /**
1127
     * @depends testDaoGeneration
1128
     */
1129
    public function testDiscardChangesOnDeletedBeanFails(): void
1130
    {
1131
        $userDao = new TestUserDao($this->tdbmService);
1132
        $countryDao = new CountryDao($this->tdbmService);
1133
1134
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1135
1136
        $userDao->save($sanchez);
1137
1138
        $userDao->delete($sanchez);
1139
1140
        $this->expectException('TheCodingMachine\TDBM\TDBMException');
1141
        // Cannot discard changes on a bean that is already deleted.
1142
        $sanchez->discardChanges();
1143
    }
1144
1145
    /**
1146
     * @depends testDaoGeneration
1147
     */
1148
    public function testUniqueIndexBasedSearch(): void
1149
    {
1150
        $userDao = new UserDao($this->tdbmService);
1151
        $user = $userDao->findOneByLogin('bill.shakespeare');
1152
1153
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1154
        $this->assertEquals('Bill Shakespeare', $user->getName());
1155
    }
1156
1157
    /**
1158
     * @depends testDaoGeneration
1159
     */
1160
    public function testFindOneByRetunsNull(): void
1161
    {
1162
        // Let's assert that the findOneBy... methods can return null.
1163
        $userDao = new UserDao($this->tdbmService);
1164
        $userBean = $userDao->findOneByLogin('not_exist');
1165
1166
        $this->assertNull($userBean);
1167
    }
1168
1169
    /**
1170
     * @depends testDaoGeneration
1171
     */
1172
    public function testMultiColumnsIndexBasedSearch(): void
1173
    {
1174
        $countryDao = new CountryDao($this->tdbmService);
1175
        $userDao = new UserDao($this->tdbmService);
1176
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1177
1178
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1179
    }
1180
1181
    /**
1182
     * @depends testDaoGeneration
1183
     */
1184
    public function testPartialMultiColumnsIndexBasedSearch(): void
1185
    {
1186
        $userDao = new UserDao($this->tdbmService);
1187
        $users = $userDao->findByStatusAndCountry('on');
1188
1189
        $this->assertCount(2, $users);
1190
    }
1191
1192
    /**
1193
     * @depends testDaoGeneration
1194
     */
1195
    public function testCreationInNullableDate(): void
1196
    {
1197
        $roleDao = new RoleDao($this->tdbmService);
1198
1199
        $role = new RoleBean('newbee');
1200
        $roleDao->save($role);
1201
1202
        $this->assertNull($role->getCreatedAt());
1203
    }
1204
1205
    /**
1206
     * @depends testDaoGeneration
1207
     */
1208
    public function testUpdateInNullableDate(): void
1209
    {
1210
        $roleDao = new RoleDao($this->tdbmService);
1211
1212
        $role = new RoleBean('newbee');
1213
        $roleDao->save($role);
1214
1215
        $role->setCreatedAt(null);
1216
        $roleDao->save($role);
1217
        $this->assertNull($role->getCreatedAt());
1218
    }
1219
1220
    /**
1221
     * @depends testDaoGeneration
1222
     */
1223
    public function testFindFromSql(): void
1224
    {
1225
        $roleDao = new TestRoleDao($this->tdbmService);
1226
1227
        $roles = $roleDao->getRolesByRightCanSing();
1228
        $this->assertCount(2, $roles);
1229
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1230
    }
1231
1232
    /**
1233
     * @depends testDaoGeneration
1234
     */
1235
    public function testFindOneFromSql(): void
1236
    {
1237
        $roleDao = new TestRoleDao($this->tdbmService);
1238
1239
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1240
        $this->assertInstanceOf(RoleBean::class, $role);
1241
    }
1242
1243
    /**
1244
     * @depends testDaoGeneration
1245
     */
1246
    public function testCreateEmptyExtendedBean(): void
1247
    {
1248
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1249
1250
        $dogDao = new DogDao($this->tdbmService);
1251
1252
        // We are not filling no field that is part of dog table.
1253
        $dog = new DogBean('Youki');
1254
        $dog->setOrder(1);
1255
1256
        $dogDao->save($dog);
1257
        $this->assertNull($dog->getRace());
1258
    }
1259
1260
    /**
1261
     * @depends testCreateEmptyExtendedBean
1262
     */
1263
    public function testFetchEmptyExtendedBean(): void
1264
    {
1265
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1266
1267
        $animalDao = new AnimalDao($this->tdbmService);
1268
1269
        // We are not filling no field that is part of dog table.
1270
        $animalBean = $animalDao->getById(1);
1271
1272
        $this->assertInstanceOf(DogBean::class, $animalBean);
1273
    }
1274
1275
    /**
1276
     * @depends testDaoGeneration
1277
     */
1278
    public function testTwoBranchesHierarchy(): void
1279
    {
1280
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1281
1282
        $catDao = new CatDao($this->tdbmService);
1283
1284
        // We are not filling no field that is part of dog table.
1285
        $cat = new CatBean('Mew');
1286
        $cat->setOrder(2);
1287
1288
        $catDao->save($cat);
1289
        $this->assertNotNull($cat->getId());
1290
    }
1291
1292
    /**
1293
     * @depends testTwoBranchesHierarchy
1294
     */
1295
    public function testFetchTwoBranchesHierarchy(): void
1296
    {
1297
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1298
1299
        $animalDao = new AnimalDao($this->tdbmService);
1300
1301
        $animalBean = $animalDao->getById(2);
1302
1303
        $this->assertInstanceOf(CatBean::class, $animalBean);
1304
        /* @var $animalBean CatBean */
1305
        $animalBean->setCutenessLevel(999);
1306
        $animalBean->setUppercaseColumn('foobar');
1307
1308
        $animalDao->save($animalBean);
1309
    }
1310
1311
    /**
1312
     * @depends testDaoGeneration
1313
     */
1314
    public function testExceptionOnGetById(): void
1315
    {
1316
        $countryDao = new CountryDao($this->tdbmService);
1317
        $this->expectException(\TypeError::class);
1318
        $countryDao->getById(null);
1319
    }
1320
1321
    /**
1322
     * @depends testDaoGeneration
1323
     */
1324
    public function testDisconnectedManyToOne(): void
1325
    {
1326
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1327
1328
        $country = new CountryBean('Spain');
1329
1330
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1331
1332
        $this->assertCount(1, $country->getUsers());
1333
        $this->assertSame($user, $country->getUsers()[0]);
1334
    }
1335
1336
    /**
1337
     * @depends testDaoGeneration
1338
     */
1339
    public function testOrderByExternalCol(): void
1340
    {
1341
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1342
1343
        $userDao = new TestUserDao($this->tdbmService);
1344
        $users = $userDao->getUsersByCountryName();
1345
1346
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1347
    }
1348
1349
    /**
1350
     * @depends testDaoGeneration
1351
     */
1352
    public function testResultIteratorSort(): void
1353
    {
1354
        $userDao = new UserDao($this->tdbmService);
1355
        $users = $userDao->findAll()->withOrder('country.label DESC');
1356
1357
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1358
1359
        $users = $users->withOrder('country.label ASC');
1360
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1361
    }
1362
1363
    /**
1364
     * @depends testDaoGeneration
1365
     */
1366
    public function testResultIteratorWithParameters(): void
1367
    {
1368
        $userDao = new TestUserDao($this->tdbmService);
1369
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1370
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1371
1372
        $users = $users->withParameters(['login' => 'jean%']);
1373
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1374
    }
1375
1376
    /**
1377
     * @depends testDaoGeneration
1378
     */
1379
    public function testOrderByExpression(): void
1380
    {
1381
        $userDao = new TestUserDao($this->tdbmService);
1382
        $users = $userDao->getUsersByReversedCountryName();
1383
1384
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1385
    }
1386
1387
    /**
1388
     * @depends testDaoGeneration
1389
     */
1390
    public function testOrderByException(): void
1391
    {
1392
        $userDao = new TestUserDao($this->tdbmService);
1393
        $users = $userDao->getUsersByInvalidOrderBy();
1394
        $this->expectException(TDBMInvalidArgumentException::class);
1395
        $user = $users[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
1396
    }
1397
1398
    /**
1399
     * @depends testDaoGeneration
1400
     */
1401
    public function testOrderByProtectedColumn(): void
1402
    {
1403
        $animalDao = new AnimalDao($this->tdbmService);
1404
        $animals = $animalDao->findAll();
1405
        $animals = $animals->withOrder('`order` ASC');
1406
1407
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1408
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1409
1410
        $animals = $animals->withOrder('`order` DESC');
1411
1412
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1413
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1414
    }
1415
1416
    /**
1417
     * @depends testDaoGeneration
1418
     */
1419
    public function testGetOnAllNullableValues(): void
1420
    {
1421
        // Tests that a get performed on a column that has only nullable fields succeeds.
1422
        $allNullable = new AllNullableBean();
1423
        $this->assertNull($allNullable->getId());
1424
        $this->assertNull($allNullable->getLabel());
1425
        $this->assertNull($allNullable->getCountry());
1426
    }
1427
1428
    /**
1429
     * @depends testDaoGeneration
1430
     */
1431
    public function testExceptionOnMultipleInheritance(): void
1432
    {
1433
        $connection = self::getConnection();
1434
        self::insert($connection, 'animal', [
1435
            'id' => 99, 'name' => 'Snoofield',
1436
        ]);
1437
        self::insert($connection, 'dog', [
1438
            'id' => 99, 'race' => 'dog',
1439
        ]);
1440
        self::insert($connection, 'cat', [
1441
            'id' => 99, 'cuteness_level' => 0,
1442
        ]);
1443
1444
        $catched = false;
1445
        try {
1446
            $animalDao = new AnimalDao($this->tdbmService);
1447
            $animalDao->getById(99);
1448
        } catch (TDBMInheritanceException $e) {
1449
            $catched = true;
1450
        }
1451
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1452
1453
        self::delete($connection, 'cat', ['id' => 99]);
1454
        self::delete($connection, 'dog', ['id' => 99]);
1455
        self::delete($connection, 'animal', ['id' => 99]);
1456
    }
1457
1458
    /**
1459
     * @depends testDaoGeneration
1460
     */
1461
    public function testReferenceNotSaved(): void
1462
    {
1463
        $boatDao = new BoatDao($this->tdbmService);
1464
1465
        $country = new CountryBean('Atlantis');
1466
        $boat = new BoatBean($country, 'Titanic');
1467
1468
        $boatDao->save($boat);
1469
        $this->assertNotNull($country->getId());
1470
    }
1471
1472
    /**
1473
     * @depends testReferenceNotSaved
1474
     */
1475
    public function testUniqueIndexOnForeignKeyThenScalar(): void
1476
    {
1477
        $boatDao = new BoatDao($this->tdbmService);
1478
        $countryDao = new CountryDao($this->tdbmService);
1479
1480
        $countryBean = $countryDao->findOneByLabel('Atlantis');
1481
        $boatBean = $boatDao->findOneByAnchorageCountryAndName($countryBean, 'Titanic');
1482
1483
        $this->assertNotNull($boatBean);
1484
    }
1485
1486
    /**
1487
     * @depends testDaoGeneration
1488
     */
1489
    public function testReferenceDeleted(): void
1490
    {
1491
        $countryDao = new CountryDao($this->tdbmService);
1492
        $boatDao = new BoatDao($this->tdbmService);
1493
1494
        $country = new CountryBean('Bikini Bottom');
1495
        $countryDao->save($country);
1496
1497
        $boat = new BoatBean($country, 'Squirrel boat');
1498
        $countryDao->delete($country);
1499
1500
        $this->expectException(TDBMMissingReferenceException::class);
1501
        $boatDao->save($boat);
1502
    }
1503
1504
    /**
1505
     * @depends testDaoGeneration
1506
     */
1507
    public function testCyclicReferenceWithInheritance(): void
1508
    {
1509
        $userDao = new UserDao($this->tdbmService);
1510
1511
        $country = new CountryBean('Norrisland');
1512
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1513
1514
        $user->setManager($user);
1515
1516
        $this->expectException(TDBMCyclicReferenceException::class);
1517
        $userDao->save($user);
1518
    }
1519
1520
    /**
1521
     * @depends testDaoGeneration
1522
     */
1523
    public function testCyclicReference(): void
1524
    {
1525
        $categoryDao = new CategoryDao($this->tdbmService);
1526
1527
        $category = new CategoryBean('Root');
1528
1529
        $category->setParent($category);
1530
1531
        $this->expectException(TDBMCyclicReferenceException::class);
1532
        $categoryDao->save($category);
1533
    }
1534
1535
    /**
1536
     * @depends testDaoGeneration
1537
     */
1538
    public function testCorrectTypeForPrimaryKeyAfterSave(): void
1539
    {
1540
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1541
        $this->onlyMySql();
1542
1543
        $allNullableDao = new AllNullableDao($this->tdbmService);
1544
        $allNullable = new AllNullableBean();
1545
        $allNullableDao->save($allNullable);
1546
        $id = $allNullable->getId();
1547
1548
        $this->assertTrue(is_int($id));
1549
    }
1550
1551
    /**
1552
     * @depends testDaoGeneration
1553
     */
1554
    public function testPSR2Compliance(): void
1555
    {
1556
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
0 ignored issues
show
Bug introduced by
'vendor/bin/php-cs-fixer...n --diff --rules=@PSR2' of type string is incompatible with the type array expected by parameter $command of Symfony\Component\Process\Process::__construct(). ( Ignorable by Annotation )

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

1556
        $process = new Process(/** @scrutinizer ignore-type */ 'vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
Loading history...
1557
        $process->run();
1558
1559
        // executes after the command finishes
1560
        if (!$process->isSuccessful()) {
1561
            echo $process->getOutput();
1562
            $this->fail('Generated code is not PSR-2 compliant');
1563
        }
1564
        $this->assertTrue($process->isSuccessful());
1565
    }
1566
1567
    /**
1568
     * @depends testDaoGeneration
1569
     */
1570
    public function testFindOneByGeneration(): void
1571
    {
1572
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1573
        $parameters = $reflectionMethod->getParameters();
1574
1575
        $this->assertCount(2, $parameters);
1576
        $this->assertSame('login', $parameters[0]->getName());
1577
        $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
1578
    }
1579
1580
    /**
1581
     * @depends testDaoGeneration
1582
     */
1583
    public function testUuid(): void
1584
    {
1585
        $article = new ArticleBean('content');
1586
        $this->assertSame('content', $article->getContent());
1587
        $this->assertNotEmpty($article->getId());
1588
        $uuid = Uuid::fromString($article->getId());
1589
        $this->assertSame(1, $uuid->getVersion());
1590
    }
1591
1592
    /**
1593
     * @depends testDaoGeneration
1594
     */
1595
    public function testUuidv4(): void
1596
    {
1597
        $article = new Article2Bean('content');
1598
        $this->assertSame('content', $article->getContent());
1599
        $this->assertNotEmpty($article->getId());
1600
        $uuid = Uuid::fromString($article->getId());
1601
        $this->assertSame(4, $uuid->getVersion());
1602
    }
1603
1604
    /**
1605
     * @depends testDaoGeneration
1606
     */
1607
    public function testTypeHintedConstructors(): void
1608
    {
1609
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1610
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1611
1612
        $this->assertSame('string', (string)$nameParam->getType());
1613
    }
1614
1615
    /**
1616
     * @depends testDaoGeneration
1617
     */
1618
    public function testSaveTransaction(): void
1619
    {
1620
        $countryDao = new CountryDao($this->tdbmService);
1621
1622
        $boatDao = new BoatDao($this->tdbmService);
1623
        $boatBean = $boatDao->getById(1);
1624
        $boatBean->setName('Bismark');
1625
1626
        $boatBean->getCountry();
1627
1628
        // Let's insert a row without telling TDBM to trigger an error!
1629
        self::insert($this->getConnection(), 'sailed_countries', [
1630
            'boat_id' => 1,
1631
            'country_id' => 2
1632
        ]);
1633
1634
        $boatBean->addCountry($countryDao->getById(2));
1635
1636
        $this->expectException(UniqueConstraintViolationException::class);
1637
1638
        $boatDao->save($boatBean);
1639
    }
1640
1641
    /**
1642
     * @depends testSaveTransaction
1643
     */
1644
    public function testSaveTransaction2(): void
1645
    {
1646
        $boatDao = new BoatDao($this->tdbmService);
1647
        $boatBean = $boatDao->getById(1);
1648
1649
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1650
        $this->assertNotSame('Bismark', $boatBean->getName());
1651
    }
1652
1653
    /**
1654
     * @depends testDaoGeneration
1655
     */
1656
    public function testForeignKeyPointingToNonPrimaryKey(): void
1657
    {
1658
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1659
        $bean = $dao->getById(1);
1660
1661
        $this->assertSame('foo', $bean->getFrom()->getTo());
1662
1663
        $newBean = new RefNoPrimKeyBean($bean, 'baz');
1664
        $dao->save($newBean);
1665
        $this->assertSame('foo', $newBean->getFrom()->getTo());
1666
1667
        $resultSet = $bean->getRefNoPrimKey();
1668
        $this->assertCount(2, $resultSet);
1669
    }
1670
1671
    /**
1672
     * @depends testDaoGeneration
1673
     */
1674
    public function testCloningUuidBean(): void
1675
    {
1676
        $article = new ArticleBean('content');
1677
        $this->assertNotEmpty($article->getId());
1678
        $article2 = clone $article;
1679
        $this->assertNotEmpty($article2->getId());
1680
        $this->assertNotSame($article->getId(), $article2->getId());
1681
    }
1682
1683
    /**
1684
     * @depends testDaoGeneration
1685
     */
1686
    public function testRecursiveSave(): void
1687
    {
1688
        $categoryDao = new CategoryDao($this->tdbmService);
1689
1690
        $root1 = new CategoryBean('Root1');
1691
        $categoryDao->save($root1);
1692
        // Root 2 is not saved yet.
1693
        $root2 = new CategoryBean('Root2');
1694
        $intermediate = new CategoryBean('Intermediate');
1695
        $categoryDao->save($intermediate);
1696
1697
        // Let's switch the parent to a bean in detached state.
1698
        $intermediate->setParent($root2);
1699
1700
        // Now, let's save a new category that references the leaf category.
1701
        $leaf = new CategoryBean('Leaf');
1702
        $leaf->setParent($intermediate);
1703
        $categoryDao->save($leaf);
1704
        $this->assertNull($root2->getId());
1705
    }
1706
1707
    /**
1708
     * @depends testDaoGeneration
1709
     */
1710
    public function testBlob(): void
1711
    {
1712
        $fp = fopen(__FILE__, 'r');
1713
        $file = new FileBean($fp);
1714
1715
        $fileDao = new FileDao($this->tdbmService);
1716
1717
        $fileDao->save($file);
1718
1719
        $loadedFile = $fileDao->getById($file->getId());
1720
1721
        $resource = $loadedFile->getFile();
1722
        $result = fseek($resource, 0);
1723
        $this->assertSame(0, $result);
1724
        $this->assertInternalType('resource', $resource);
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\Assert::assertInternalType() has been deprecated: https://github.com/sebastianbergmann/phpunit/issues/3369 ( Ignorable by Annotation )

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

1724
        /** @scrutinizer ignore-deprecated */ $this->assertInternalType('resource', $resource);

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...
1725
        $firstLine = fgets($resource);
1726
        $this->assertSame("<?php\n", $firstLine);
1727
    }
1728
1729
    /**
1730
     * @depends testBlob
1731
     */
1732
    public function testReadBlob(): void
1733
    {
1734
        $fileDao = new FileDao($this->tdbmService);
1735
        $loadedFile = $fileDao->getById(1);
1736
1737
        $resource = $loadedFile->getFile();
1738
        $this->assertInternalType('resource', $resource);
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\Assert::assertInternalType() has been deprecated: https://github.com/sebastianbergmann/phpunit/issues/3369 ( Ignorable by Annotation )

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

1738
        /** @scrutinizer ignore-deprecated */ $this->assertInternalType('resource', $resource);

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...
1739
        $firstLine = fgets($resource);
1740
        $this->assertSame("<?php\n", $firstLine);
1741
1742
        stream_get_contents($resource);
1743
1744
        $loadedFile->setId($loadedFile->getId());
1745
1746
        $fileDao->save($loadedFile);
1747
    }
1748
1749
    /**
1750
     * @depends testReadBlob
1751
     */
1752
    public function testReadAndSaveBlob(): void
1753
    {
1754
        $fileDao = new FileDao($this->tdbmService);
1755
        $loadedFile = $fileDao->getById(1);
1756
1757
        $resource = $loadedFile->getFile();
1758
1759
        $firstLine = fgets($resource);
1760
        $this->assertSame("<?php\n", $firstLine);
1761
    }
1762
1763
    /**
1764
     * @depends testReadBlob
1765
     */
1766
    public function testProtectedGetterSetter(): void
1767
    {
1768
        $md5Getter = new ReflectionMethod(FileBaseBean::class, 'getMd5');
1769
        $md5Setter = new ReflectionMethod(FileBaseBean::class, 'setMd5');
1770
1771
        $this->assertTrue($md5Getter->isProtected());
1772
        $this->assertTrue($md5Setter->isProtected());
1773
1774
        $md5Getter2 = new ReflectionMethod(FileBaseBean::class, 'getArticle');
1775
        $md5Setter2 = new ReflectionMethod(FileBaseBean::class, 'setArticle');
1776
1777
        $this->assertTrue($md5Getter2->isProtected());
1778
        $this->assertTrue($md5Setter2->isProtected());
1779
1780
        $oneToManyGetter = new ReflectionMethod(ArticleBaseBean::class, 'getFiles');
1781
        $this->assertTrue($oneToManyGetter->isProtected());
1782
1783
        $fileDao = new FileDao($this->tdbmService);
1784
        $loadedFile = $fileDao->getById(1);
1785
1786
        // The md5 and article columns are not JSON serialized
1787
        $this->assertSame([
1788
            'id' => 1,
1789
        ], $loadedFile->jsonSerialize());
1790
    }
1791
1792
    /**
1793
     * @depends testDaoGeneration
1794
     */
1795
    public function testBlobResourceException(): void
1796
    {
1797
        $this->expectException(TDBMInvalidArgumentException::class);
1798
        $this->expectExceptionMessage('Invalid argument passed to \'TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\Generated\\FileBaseBean::setFile\'. Expecting a resource. Got a string.');
1799
        new FileBean('foobar');
1800
    }
1801
1802
    /**
1803
     * @depends testDaoGeneration
1804
     */
1805
    public function testFilterBag(): void
1806
    {
1807
        $userDao = new TestUserDao($this->tdbmService);
1808
        $countryDao = new CountryDao($this->tdbmService);
1809
1810
        $country = $countryDao->getById(2);
1811
1812
        // Let's test filter bags by bean and filter bag with many values.
1813
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'Jane Doe']);
1814
1815
        $this->assertCount(1, $users);
1816
        $this->assertSame('John Doe', $users[0]->getName());
1817
    }
1818
1819
    /**
1820
     * @depends testDaoGeneration
1821
     */
1822
    public function testDecimalIsMappedToString(): void
1823
    {
1824
        $reflectionClass = new \ReflectionClass(BoatBaseBean::class);
1825
        $this->assertSame('string', (string) $reflectionClass->getMethod('getLength')->getReturnType());
1826
    }
1827
1828
    /**
1829
     * @depends testDaoGeneration
1830
     */
1831
    public function testInsertMultiPrimaryKeysBean(): void
1832
    {
1833
        $countryDao = new CountryDao($this->tdbmService);
1834
1835
        $country = $countryDao->getById(1);
1836
1837
        $stateDao = new StateDao($this->tdbmService);
1838
        $state = new StateBean($country, 'IDF', 'Ile de France');
1839
        $stateDao->save($state);
1840
1841
        $this->assertSame($state, $stateDao->findAll()[0]);
1842
    }
1843
1844
    /**
1845
     * @depends testInsertMultiPrimaryKeysBean
1846
     */
1847
    public function testDeleteMultiPrimaryKeysBean(): void
1848
    {
1849
        $stateDao = new StateDao($this->tdbmService);
1850
1851
        $state = $stateDao->findAll()[0];
1852
        $stateDao->delete($state);
1853
        $this->assertCount(0, $stateDao->findAll());
1854
    }
1855
1856
    /**
1857
     * @depends testDaoGeneration
1858
     */
1859
    public function testCompositePrimaryKeyGetter(): void
1860
    {
1861
        $stateDao = new StateDao($this->tdbmService);
1862
        $country = new CountryBean('USA');
1863
        $stateBean = new StateBean($country, 'CA', 'California');
1864
        $stateDao->save($stateBean);
1865
        $this->assertSame($stateBean, $stateDao->getById($country->getId(), 'CA'));
1866
    }
1867
1868
    /**
1869
     * @depends testDaoGeneration
1870
     */
1871
    public function testSortOnInheritedTable(): void
1872
    {
1873
        $animalDao = new AnimalDao($this->tdbmService);
1874
1875
        // Let's insert an animal that is nothing.
1876
        $animal = new AnimalBean('Mickey');
1877
        $animalDao->save($animal);
1878
1879
        $animals = $animalDao->findAll()->withOrder('dog.race ASC');
1880
1881
        $animalsArr = $animals->toArray();
1882
        $this->assertCount(3, $animalsArr);
1883
    }
1884
1885
    /**
1886
     * @depends testDaoGeneration
1887
     */
1888
    public function testJsonKey(): void
1889
    {
1890
        $node = new NodeBean('foo.html');
1891
        $json = $node->jsonSerialize();
1892
        self::assertTrue(isset($json['basename']));
1893
        self::assertEquals('foo.html', $json['basename']);
1894
    }
1895
1896
    /**
1897
     * @depends testDaoGeneration
1898
     */
1899
    public function testJsonIgnore(): void
1900
    {
1901
        $nodeDao = new NodeDao($this->tdbmService);
1902
        $index = $nodeDao->getById(6);
1903
        $json = $index->jsonSerialize();
1904
        // Ignored scalar 'id'
1905
        self::assertTrue(!isset($json['id']));
1906
        // Ignored object 'root'
1907
        self::assertTrue(!isset($json['root']));
1908
        self::assertTrue(isset($json['guests']));
1909
        self::assertTrue(!empty($json['guests']));
1910
        $account = $index->getAccounts()[0];
1911
        $json = $account->jsonSerialize();
1912
        // Ignored array 'nodes' (from nodes_users table)
1913
        self::assertTrue(!isset($json['nodes']));
1914
    }
1915
1916
    /**
1917
     * @depends testDaoGeneration
1918
     */
1919
    public function testJsonInclude(): void
1920
    {
1921
        $nodeDao = new NodeDao($this->tdbmService);
1922
        $index = $nodeDao->getById(6);
1923
        $json = $index->jsonSerialize();
1924
        // Whole chain of parents should be serialized
1925
        self::assertTrue(isset($json['parent']));
1926
        self::assertTrue(isset($json['parent']['parent']));
1927
        self::assertTrue(isset($json['parent']['parent']['parent']));
1928
        self::assertEquals('/', $json['parent']['parent']['parent']['basename']);
1929
    }
1930
1931
    /**
1932
     * @depends testDaoGeneration
1933
     */
1934
    public function testJsonRecursive(): void
1935
    {
1936
        $nodeDao = new NodeDao($this->tdbmService);
1937
        $index = $nodeDao->getById(8);
1938
        $json = $index->jsonSerialize();
1939
        // Original chain of aliases is recursively serialized, ...
1940
        self::assertTrue(isset($json['alias']));
1941
        self::assertTrue(isset($json['alias']['alias']));
1942
        self::assertEquals('index.html', $json['alias']['alias']['basename']);
1943
        // ... each alias even serializes its parents, ...
1944
        self::assertTrue(isset($json['alias']['alias']['parent']['parent']));
1945
        // ... however, parents aliases chains have just their foreign key (id), as parents are serialized with $stopRecursion=true
1946
        self::assertEquals(3, $json['alias']['alias']['parent']['parent']['alias']['id']);
1947
        self::assertCount(1, $json['alias']['alias']['parent']['parent']['alias']);
1948
    }
1949
1950
    /**
1951
     * @depends testDaoGeneration
1952
     */
1953
    public function testJsonFormat(): void
1954
    {
1955
        $nodeDao = new NodeDao($this->tdbmService);
1956
        $index = $nodeDao->getById(6);
1957
        $json = $index->jsonSerialize();
1958
        self::assertTrue(isset($json['size']));
1959
        self::assertEquals('512 o', $json['size']);
1960
        self::assertEquals('42.50g', $json['weight']);
1961
        self::assertEquals($index->getCreatedAt()->format('Y-m-d'), $json['createdAt']);
1962
        self::assertEquals($index->getOwner()->getName(), $json['owner']);
1963
        self::assertEquals($index->getAccounts()[1]->getName(), $json['guests'][1]);
1964
        self::assertTrue(isset($json['entries']));
1965
        self::assertEquals('Hello, World', $json['entries'][1]);
1966
        $www = $index->getParent();
1967
        $json = $www->jsonSerialize();
1968
        self::assertEquals('0 o', $json['size']);
1969
        self::assertNull($json['weight']);
1970
        self::assertNull($json['owner']);
1971
    }
1972
1973
    /**
1974
     * @depends testDaoGeneration
1975
     */
1976
    public function testJsonCollection(): void
1977
    {
1978
        $artists = new ArtistDao($this->tdbmService);
1979
        $pinkFloyd = $artists->getById(1);
1980
        $animals =  $pinkFloyd->getAlbums()[0];
1981
        $json = $pinkFloyd->jsonSerialize();
1982
        // Collection name properly handled ('discography' instead of default 'albums')
1983
        self::assertTrue(isset($json['discography']));
1984
        self::assertEquals($animals->getTitle(), $json['discography'][0]['title']);
1985
        // Make sure top object have just its primary key
1986
        self::assertEquals(1, $json['discography'][0]['artist']['id']);
1987
        self::assertCount(1, $json['discography'][0]['artist']);
1988
        $json = $animals->jsonSerialize();
1989
        // Nevertheless, artist should be serialized in album as top object...
1990
        self::assertTrue(isset($json['artist']));
1991
        // ... as should be tracks...
1992
        self::assertTrue(isset($json['tracks'][0]));
1993
        self::assertEquals('Pigs on the Wing 1', $json['tracks'][0]['title']);
1994
        // ... and, ultimately, list of featuring artists, since feat is included
1995
        self::assertTrue(isset($json['tracks'][0]['feat'][0]));
1996
        self::assertEquals('Roger Waters', $json['tracks'][0]['feat'][0]['name']);
1997
    }
1998
1999
    public function testFloydHasNoParent(): void
2000
    {
2001
        $artists = new ArtistDao($this->tdbmService);
2002
        $pinkFloyd = $artists->getById(1);
2003
        $parents = $pinkFloyd->getParents();
2004
2005
        $this->assertEquals([], $parents);
2006
    }
2007
2008
    public function testFloydHasOneChild(): void
2009
    {
2010
        $artists = new ArtistDao($this->tdbmService);
2011
        $pinkFloyd = $artists->getById(1);
2012
        $children = $pinkFloyd->getChildrenByArtistsRelations();
2013
2014
        $this->assertEquals(1, count($children));
2015
        $this->assertEquals(2, $children[0]->getId());
2016
    }
2017
2018
    /**
2019
     * @depends testDaoGeneration
2020
     */
2021
    public function testAddInterfaceAnnotation(): void
2022
    {
2023
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2024
            // See https://github.com/doctrine/dbal/pull/3512
2025
            $this->markTestSkipped('Only MySQL supports table level comments');
2026
        }
2027
2028
        $refClass = new ReflectionClass(UserBaseBean::class);
2029
        $this->assertTrue($refClass->implementsInterface(TestUserInterface::class));
2030
    }
2031
2032
    /**
2033
     * @depends testDaoGeneration
2034
     */
2035
    public function testAddInterfaceOnDaoAnnotation(): void
2036
    {
2037
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2038
            // See https://github.com/doctrine/dbal/pull/3512
2039
            $this->markTestSkipped('Only MySQL supports table level comments');
2040
        }
2041
2042
        $refClass = new ReflectionClass(UserBaseDao::class);
2043
        $this->assertTrue($refClass->implementsInterface(TestUserDaoInterface::class));
2044
    }
2045
2046
    /**
2047
     * @depends testDaoGeneration
2048
     */
2049
    public function testTrait(): void
2050
    {
2051
        if (!$this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
2052
            // See https://github.com/doctrine/dbal/pull/3512
2053
            $this->markTestSkipped('Only MySQL supports table level comments');
2054
        }
2055
2056
        $userDao = new UserDao($this->tdbmService);
2057
        $userBean = $userDao->getById(1);
2058
2059
        $this->assertSame('TestOtherUserTrait', $userBean->method1());
2060
        $this->assertSame('TestUserTrait', $userBean->method1renamed());
2061
2062
        $refClass = new ReflectionClass(UserBaseDao::class);
2063
        $this->assertTrue($refClass->hasMethod('findNothing'));
2064
    }
2065
2066
    /**
2067
     * @depends testDaoGeneration
2068
     */
2069
    public function testNonInstantiableAbstractDaosAndBeans(): void
2070
    {
2071
        $refClass = new ReflectionClass(UserBaseDao::class);
2072
        $this->assertFalse($refClass->isInstantiable());
2073
2074
        $refClass = new ReflectionClass(UserBaseBean::class);
2075
        $this->assertFalse($refClass->isInstantiable());
2076
    }
2077
2078
    /**
2079
     * @depends testDaoGeneration
2080
     */
2081
    public function testCanNullifyBlob(): void
2082
    {
2083
        $article = new ArticleBean('content');
2084
        $fp = fopen(__FILE__, 'r');
2085
        $article->setAttachment($fp);
2086
        $article->setAttachment(null);
2087
        $this->assertNull($article->getAttachment(null));
2088
        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

2088
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2089
    }
2090
2091
    /**
2092
     * @depends testDaoGeneration
2093
     */
2094
    public function testOptionnalParametersCanBeNullInFindOneBy()
2095
    {
2096
        $albumDao = new AlbumDao($this->tdbmService);
2097
        $artist = new ArtistBean('Marcel');
2098
2099
        $albumDao->findOneByArtistAndNode($artist, null);
2100
        $this->assertEquals(1, 1);
2101
    }
2102
2103
    /**
2104
     * @depends testDaoGeneration
2105
     */
2106
    public function testRequiredParametersCannotBeNullInFindOneBy()
2107
    {
2108
        $albumDao = new AlbumDao($this->tdbmService);
2109
        $artist = new ArtistBean('Marcel');
2110
        $account = new AccountBean('Jamie');
2111
2112
        $albumDao->findOneByArtistAndAccount($artist, $account);
2113
2114
        $this->expectException('TypeError');
2115
        $albumDao->findOneByArtistAndAccount($artist, null);
2116
    }
2117
2118
    /**
2119
     * @depends testDaoGeneration
2120
     */
2121
    public function testLazyLoad(): void
2122
    {
2123
        $roleDao = new RoleDao($this->tdbmService);
2124
        $roleBean = $roleDao->getById(1, true);
2125
2126
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2127
        $roleBean->getId();
2128
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2129
    }
2130
2131
    /**
2132
     * @depends testDaoGeneration
2133
     */
2134
    public function testOneToOneInverseRelationGetter(): void
2135
    {
2136
        $objectBaseDao = new BaseObjectDao($this->tdbmService);
2137
        $objectInheritedDao = new InheritedObjectDao($this->tdbmService);
2138
        $objectBase = new BaseObjectBean('label');
2139
        $objectBaseDao->save($objectBase);
2140
        $this->assertNull($objectBase->getInheritedObject());
2141
        $objectInherited = new InheritedObjectBean($objectBase);
2142
        $objectInheritedDao->save($objectInherited);
2143
        $this->assertSame($objectInherited, $objectBase->getInheritedObject());
2144
        $this->assertEquals(1, $objectBase->jsonSerialize()['inheritedObject']['id']);
2145
    }
2146
2147
    public function testLazyStopRecursion(): void
2148
    {
2149
        $albumDao = new AlbumDao($this->tdbmService);
2150
        $albumBean = $albumDao->getById(1);
2151
        $json = $albumBean->jsonSerialize(true);
2152
        $this->assertArrayHasKey('id', $json['artist']);
2153
        $this->assertArrayNotHasKey('name', $json['artist']);
2154
    }
2155
2156
    public function testLazyStopRecursionOnCompositeForeignKey(): void
2157
    {
2158
        $compositeFkSourceDao = new CompositeFkSourceDao($this->tdbmService);
2159
        $compositeFkSourceBean = $compositeFkSourceDao->getById(1);
2160
        $json = $compositeFkSourceBean->jsonSerialize(true);
2161
        $this->assertEquals(1, $json['compositeFkTarget']['id1']);
2162
        $this->assertEquals(1, $json['compositeFkTarget']['id2']);
2163
    }
2164
2165
    public function testMethodNameConflictsBetweenRegularAndAutoPivotProperties()
2166
    {
2167
        $artist = new ArtistBean('Super');
2168
        $artist->getChildren(); // regular property
2169
        $artist->getChildrenByArtistId(); // one-to-may relationship
2170
        $artist->getChildrenByArtistsRelations(); // auto-pivot relationship
2171
        $this->assertEquals(1, 1);
2172
    }
2173
2174
    /**
2175
     * @depends testDaoGeneration
2176
     */
2177
    public function testSQLCountWithArray(): void
2178
    {
2179
        $userDao = new TestUserDao($this->tdbmService);
2180
        $countryDao = new CountryDao($this->tdbmService);
2181
2182
        $country = $countryDao->getById(2);
2183
2184
        // Let's test filter bags by bean and filter bag with many values.
2185
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'John Smith'])->take(0, 1);
2186
        $this->assertEquals(1, $users->count());
2187
    }
2188
2189
    /**
2190
     * @depends testDaoGeneration
2191
     */
2192
    public function testSubQueryWithFind(): void
2193
    {
2194
        $userDao = new TestUserDao($this->tdbmService);
2195
        $articleDao = new TestArticleSubQueryDao($this->tdbmService, $userDao);
2196
2197
        $bill = $userDao->getById(4);
2198
        $article = new ArticleBean('Foo');
2199
        $article->setAuthor($bill);
2200
        $articleDao->save($article);
2201
2202
        $results = $articleDao->getArticlesByUserLoginStartingWith('bill');
2203
2204
        $this->assertCount(1, $results);
2205
        $this->assertSame('Foo', $results[0]->getContent());
2206
    }
2207
2208
    /**
2209
     * @depends testDaoGeneration
2210
     */
2211
    public function testSubQueryExceptionOnPrimaryKeysWithMultipleColumns(): void
2212
    {
2213
        $stateDao = new StateDao($this->tdbmService);
2214
        $states = $stateDao->findAll();
2215
        $this->expectException(TDBMException::class);
2216
        $this->expectExceptionMessage('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
2217
        $states->_getSubQuery();
2218
    }
2219
2220
    public function testManyToOneEagerLoading(): void
2221
    {
2222
        $userDao = new UserDao($this->tdbmService);
2223
        $users = $userDao->findAll()->withOrder('id asc');
2224
        $countryIds = [];
2225
        foreach ($users as $user) {
2226
            $countryIds[] = $user->getCountry()->getId();
2227
        }
2228
2229
        $this->assertFalse($users->getIterator()->hasManyToOneDataLoader('__country_id'));
2230
        $this->assertSame([2, 1, 3, 2, 2, 4], $countryIds);
2231
2232
        $countryNames = [];
2233
        foreach ($users as $user) {
2234
            $countryNames[] = $user->getCountry()->getLabel();
2235
        }
2236
2237
        $this->assertTrue($users->getIterator()->hasManyToOneDataLoader('__country_id'));
2238
        $this->assertSame(['UK', 'France', 'Jamaica', 'UK', 'UK', 'Mexico'], $countryNames);
2239
    }
2240
}
2241