Passed
Push — fix/findFromRaxSql-count ( 9e0437 )
by
unknown
04:06
created

TDBMDaoGeneratorTest   F

Complexity

Total Complexity 152

Size/Duplication

Total Lines 2115
Duplicated Lines 0 %

Importance

Changes 50
Bugs 3 Features 4
Metric Value
wmc 152
eloc 856
c 50
b 3
f 4
dl 0
loc 2115
rs 1.744

134 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 8 1
A testGenerationException() 0 13 1
A testGetBeanClassName() 0 9 1
A testNewBeans() 0 10 1
A testJointureSave8() 0 21 3
A testJointureSave3() 0 12 1
A testAssigningNewBeans() 0 8 1
A testJointureSave6() 0 8 1
A testDateTimeImmutableGetter() 0 6 1
A testDaoGeneration() 0 34 2
A testJointureSave9() 0 11 1
A testGeneratedGetById() 0 6 1
A testDirectReversedRelationship() 0 20 1
A testJointureSave1() 0 16 1
A testJointureMultiAdd() 0 11 1
A testJointureDeleteBeforeGetters() 0 13 1
A testDeleteInDirectReversedRelationship() 0 20 1
A recursiveDelete() 0 13 4
A testAssigningExistingRelationship() 0 9 1
A testNestedIterationOnAlterableResultIterator() 0 14 3
A testJointureSave2() 0 5 1
A testJointureAdderOnNewBean() 0 18 1
A testJointureSave10() 0 9 1
A testNewBeanConstructor() 0 4 1
A testJointureSave4() 0 8 1
A testDefaultValueOnNewBean() 0 4 1
A testJointureSave7() 0 10 1
A testForeignKeyInBean() 0 15 1
A testUpdatingProtectedColumn() 0 7 1
A testJointureGetters() 0 13 1
A testGeneratedGetByIdLazyLoaded() 0 9 1
A testJointureSave5() 0 10 1
A testFindOrderBy() 0 16 2
A testFindFromSqlOrderByOnInheritedBean() 0 9 2
A testJointureInParentTable() 0 9 1
A testFindFromSqlOrderBy() 0 16 2
A testFindFromSqlOrderByJoinRole() 0 8 1
A testDiscardChangesOnNewBeanFails() 0 5 1
A testCloningUuidBean() 0 7 1
A testTypeHintedConstructors() 0 6 1
A testRequiredParametersCannotBeNullInFindOneBy() 0 10 1
A testFindOneByRetunsNull() 0 7 1
A testInsertMultiPrimaryKeysBean() 0 11 1
A testUpdateInNullableDate() 0 10 1
A testFetchEmptyExtendedBean() 0 10 1
A testCreationInNullableDate() 0 8 1
A testFindFromRawSqlCount() 0 10 1
A testCanNullifyBlob() 0 8 1
A testAddInterfaceAnnotation() 0 9 2
A testFilterBag() 0 12 1
A testFindFilters() 0 7 1
A testResultIteratorSort() 0 9 1
A testSaveTransaction2() 0 7 1
A testDeleteMultiPrimaryKeysBean() 0 7 1
A testInnerResultIteratorCountAfterFetch() 0 6 1
A testNonInstantiableAbstractDaosAndBeans() 0 7 1
A testReadBlob() 0 15 1
A testTrait() 0 15 2
A testExceptionOnGetById() 0 5 1
A testPSR2Compliance() 0 11 2
A testFetchTwoBranchesHierarchy() 0 14 1
A testFloydHasOneChild() 0 8 1
A testJsonEncodeBean() 0 22 1
A testFindFromRawSqlWithSimpleQuery() 0 7 1
A testDisconnectedManyToOne() 0 10 1
A testFindOne() 0 6 1
A testFindFromRawSqlWithUnion() 0 7 1
A testQueryOnWrongTableName() 0 7 1
A testOrderByExternalCol() 0 8 1
A testMultiColumnsIndexBasedSearch() 0 7 1
A testCompositePrimaryKeyGetter() 0 7 1
A testExceptionOnMultipleInheritance() 0 25 2
A testFindByDateTime() 0 5 1
A testRecursiveSave() 0 19 1
A testForeignKeyPointingToNonPrimaryKey() 0 13 1
A testFindFromRawSQLOnInheritance() 0 7 1
A testLazyLoad() 0 8 1
A testFindOneFromSql() 0 6 1
A testLazyStopRecursion() 0 7 1
A testGetOnAllNullableValues() 0 7 1
A testCorrectTypeForPrimaryKeyAfterSave() 0 11 1
A testOrderByProtectedColumn() 0 13 1
A testOneToOneInverseRelationGetter() 0 11 1
A testResultIteratorWithParameters() 0 8 1
A testNullableForeignKey() 0 11 1
A testProtectedGetterSetter() 0 24 1
A testReferenceDeleted() 0 13 1
A testCascadeDelete() 0 27 2
A testOrderByExpression() 0 6 1
A testSaveTransaction() 0 21 1
A testCyclicReferenceWithInheritance() 0 11 1
A testAddInterfaceOnDaoAnnotation() 0 9 2
A testUuid() 0 7 1
A testBlob() 0 17 1
A testTwoBranchesHierarchy() 0 12 1
A testCloneBeanAttachedBean() 0 25 1
A testCyclicReference() 0 10 1
A testFindFromSql() 0 7 1
A testUniqueIndexOnForeignKeyThenScalar() 0 9 1
A testCursorJsonEncode() 0 9 1
A testFirstNull() 0 7 1
A testOrderByException() 0 6 1
A testMethodNameConflictsBetweenRegularAndAutoPivotProperties() 0 7 1
A testOptionnalParametersCanBeNullInFindOneBy() 0 7 1
A testFindAll() 0 6 1
A testCreateEmptyExtendedBean() 0 12 1
A testCloneNewBean() 0 18 1
A testPartialMultiColumnsIndexBasedSearch() 0 6 1
A testReferenceNotSaved() 0 9 1
A testJsonKey() 0 6 1
A testArrayJsonEncode() 0 9 1
A testFirst() 0 7 1
A testJsonIgnore() 0 15 1
A testFindOneByGeneration() 0 8 1
A testInnerJsonEncode() 0 9 1
A testPageJsonEncode() 0 9 1
A testFindFromRawSqlWithDistinctQuery() 0 7 1
A testBlobResourceException() 0 5 1
A testDiscardChanges() 0 12 1
A testFloydHasNoParent() 0 7 1
A testJsonInclude() 0 10 1
A testSortOnInheritedTable() 0 12 1
A testJsonRecursive() 0 14 1
A testUuidv4() 0 7 1
A testFindFromRawSqlOrderByUserCount() 0 9 2
A testSetToNullForeignKey() 0 12 1
A testReadAndSaveBlob() 0 9 1
A testUniqueIndexBasedSearch() 0 7 1
A testJsonFormat() 0 18 1
A testFindMode() 0 7 1
A testLazyStopRecursionOnCompositeForeignKey() 0 7 1
A testDiscardChangesOnDeletedBeanFails() 0 14 1
A testJsonCollection() 0 21 1
A testDecimalIsMappedToString() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like TDBMDaoGeneratorTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TDBMDaoGeneratorTest, and based on these observations, apply Extract Interface, too.

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\TestAlbumDao;
34
use TheCodingMachine\TDBM\Dao\TestArticleDao;
35
use TheCodingMachine\TDBM\Dao\TestCountryDao;
36
use TheCodingMachine\TDBM\Dao\TestPersonDao;
37
use TheCodingMachine\TDBM\Dao\TestRoleDao;
38
use TheCodingMachine\TDBM\Dao\TestUserDao;
39
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserDaoInterface;
40
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserInterface;
41
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...
42
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...
43
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...
44
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...
45
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...
46
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...
47
use TheCodingMachine\TDBM\Test\Dao\Bean\AlbumBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\AlbumBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
48
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...
49
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...
50
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...
51
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...
52
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...
53
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...
54
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...
55
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...
56
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...
57
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...
58
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...
59
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...
60
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...
61
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...
62
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...
63
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...
64
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...
65
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...
66
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...
67
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...
68
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...
69
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...
70
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...
71
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...
72
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...
73
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...
74
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...
75
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...
76
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...
77
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...
78
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...
79
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...
80
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...
81
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...
82
use TheCodingMachine\TDBM\Test\Dao\PersonDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\PersonDao was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

1728
        /** @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...
1729
        $firstLine = fgets($resource);
1730
        $this->assertSame("<?php\n", $firstLine);
1731
    }
1732
1733
    /**
1734
     * @depends testBlob
1735
     */
1736
    public function testReadBlob(): void
1737
    {
1738
        $fileDao = new FileDao($this->tdbmService);
1739
        $loadedFile = $fileDao->getById(1);
1740
1741
        $resource = $loadedFile->getFile();
1742
        $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

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

2092
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2093
    }
2094
2095
    /**
2096
     * @depends testDaoGeneration
2097
     */
2098
    public function testOptionnalParametersCanBeNullInFindOneBy()
2099
    {
2100
        $albumDao = new AlbumDao($this->tdbmService);
2101
        $artist = new ArtistBean('Marcel');
2102
2103
        $albumDao->findOneByArtistAndNode($artist, null);
2104
        $this->assertEquals(1, 1);
2105
    }
2106
2107
    /**
2108
     * @depends testDaoGeneration
2109
     */
2110
    public function testRequiredParametersCannotBeNullInFindOneBy()
2111
    {
2112
        $albumDao = new AlbumDao($this->tdbmService);
2113
        $artist = new ArtistBean('Marcel');
2114
        $account = new AccountBean('Jamie');
2115
2116
        $albumDao->findOneByArtistAndAccount($artist, $account);
2117
2118
        $this->expectException('TypeError');
2119
        $albumDao->findOneByArtistAndAccount($artist, null);
2120
    }
2121
2122
    /**
2123
     * @depends testDaoGeneration
2124
     */
2125
    public function testLazyLoad(): void
2126
    {
2127
        $roleDao = new RoleDao($this->tdbmService);
2128
        $roleBean = $roleDao->getById(1, true);
2129
2130
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2131
        $roleBean->getId();
2132
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2133
    }
2134
2135
    /**
2136
     * @depends testDaoGeneration
2137
     */
2138
    public function testOneToOneInverseRelationGetter(): void
2139
    {
2140
        $objectBaseDao = new BaseObjectDao($this->tdbmService);
2141
        $objectInheritedDao = new InheritedObjectDao($this->tdbmService);
2142
        $objectBase = new BaseObjectBean('label');
2143
        $objectBaseDao->save($objectBase);
2144
        $this->assertNull($objectBase->getInheritedObject());
2145
        $objectInherited = new InheritedObjectBean($objectBase);
2146
        $objectInheritedDao->save($objectInherited);
2147
        $this->assertSame($objectInherited, $objectBase->getInheritedObject());
2148
        $this->assertEquals(1, $objectBase->jsonSerialize()['inheritedObject']['id']);
2149
    }
2150
2151
    public function testLazyStopRecursion(): void
2152
    {
2153
        $albumDao = new AlbumDao($this->tdbmService);
2154
        $albumBean = $albumDao->getById(1);
2155
        $json = $albumBean->jsonSerialize(true);
2156
        $this->assertArrayHasKey('id', $json['artist']);
2157
        $this->assertArrayNotHasKey('name', $json['artist']);
2158
    }
2159
2160
    public function testLazyStopRecursionOnCompositeForeignKey(): void
2161
    {
2162
        $compositeFkSourceDao = new CompositeFkSourceDao($this->tdbmService);
2163
        $compositeFkSourceBean = $compositeFkSourceDao->getById(1);
2164
        $json = $compositeFkSourceBean->jsonSerialize(true);
2165
        $this->assertEquals(1, $json['compositeFkTarget']['id1']);
2166
        $this->assertEquals(1, $json['compositeFkTarget']['id2']);
2167
    }
2168
2169
    public function testMethodNameConflictsBetweenRegularAndAutoPivotProperties(): void
2170
    {
2171
        $artist = new ArtistBean('Super');
2172
        $artist->getChildren(); // regular property
2173
        $artist->getChildrenByArtistId(); // one-to-may relationship
2174
        $artist->getChildrenByArtistsRelations(); // auto-pivot relationship
2175
        $this->assertEquals(1, 1);
2176
    }
2177
2178
    public function testFindByDateTime(): void
2179
    {
2180
        $personDao = new PersonDao($this->tdbmService);
2181
        $personDao->findByModifiedAt(new \DateTimeImmutable())->count();
2182
        $this->assertTrue(true);
2183
    }
2184
2185
    /**
2186
     * Bug: find from sql use a `COUNT(DISTINCT *)` which fails because of null values.
2187
     */
2188
    public function testFindFromRawSqlCount(): void
2189
    {
2190
        $dao = new TestAlbumDao($this->tdbmService);
2191
        $albums = $dao->findAllFromRawSql();
2192
2193
        $firstAlbum = $albums->first();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $firstAlbum is correct as $albums->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

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

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

}

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

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

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

Loading history...
2194
        assert($firstAlbum instanceof AlbumBean);
2195
        $this->assertNull($firstAlbum->getNode()); // This null ensure reproducibility of the bug
2196
        $expectedCount = $dao->findAllFromRawSqlWithCount()->count();
2197
        $this->assertEquals($expectedCount, $albums->count());
2198
    }
2199
2200
    public function testFindFromRawSQLOnInheritance(): void
2201
    {
2202
        $dao = new TestPersonDao($this->tdbmService);
2203
        $objects = $dao->testFindFromRawSQLOnInherited();
2204
2205
        $this->assertNotNull($objects->first());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $objects->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

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

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

}

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

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

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

Loading history...
2206
        $this->assertEquals(6, $objects->count());
2207
    }
2208
}
2209