Passed
Pull Request — master (#155)
by
unknown
02:35
created

TDBMDaoGeneratorTest   F

Complexity

Total Complexity 145

Size/Duplication

Total Lines 2039
Duplicated Lines 0 %

Importance

Changes 41
Bugs 1 Features 3
Metric Value
wmc 145
eloc 822
c 41
b 1
f 3
dl 0
loc 2039
rs 1.778

127 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 8 1
A testGenerationException() 0 13 1
A testFindFilters() 0 7 1
A testGetBeanClassName() 0 9 1
A testNewBeans() 0 10 1
A testJointureSave8() 0 21 3
A testFindOrderBy() 0 16 2
A testJointureSave3() 0 12 1
A testAssigningNewBeans() 0 8 1
A testJsonEncodeBean() 0 22 1
A testFindFromRawSqlWithSimpleQuery() 0 7 1
A testJointureSave6() 0 8 1
A testFindOne() 0 6 1
A testFindFromRawSqlWithUnion() 0 7 1
A testQueryOnWrongTableName() 0 7 1
A testDateTimeImmutableGetter() 0 6 1
A testDaoGeneration() 0 34 2
A testJointureSave9() 0 11 1
A testFindFromSqlOrderByOnInheritedBean() 0 9 2
A testNullableForeignKey() 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 testCursorJsonEncode() 0 9 1
A testFindAll() 0 6 1
A testJointureSave2() 0 5 1
A testJointureAdderOnNewBean() 0 18 1
A testJointureSave10() 0 9 1
A testFindFromSqlOrderBy() 0 16 2
A testArrayJsonEncode() 0 9 1
A testNewBeanConstructor() 0 4 1
A testInnerJsonEncode() 0 9 1
A testPageJsonEncode() 0 9 1
A testFindFromRawSqlWithDistinctQuery() 0 7 1
A testJointureSave4() 0 8 1
A testDefaultValueOnNewBean() 0 4 1
A testJointureSave7() 0 10 1
A testForeignKeyInBean() 0 15 1
A testFindFromSqlOrderByJoinRole() 0 8 1
A testFindFromRawSqlOrderByUserCount() 0 8 2
A testUpdatingProtectedColumn() 0 7 1
A testJointureGetters() 0 13 1
A testSetToNullForeignKey() 0 12 1
A testGeneratedGetByIdLazyLoaded() 0 9 1
A testJointureSave5() 0 10 1
A testFindMode() 0 7 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 testCanNullifyBlob() 0 8 1
A testAddInterfaceAnnotation() 0 9 2
A testFilterBag() 0 12 1
A testSaveTransaction2() 0 7 1
A testResultIteratorSort() 0 9 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 testDisconnectedManyToOne() 0 10 1
A testOrderByExternalCol() 0 8 1
A testMultiColumnsIndexBasedSearch() 0 7 1
A testCompositePrimaryKeyGetter() 0 7 1
A testExceptionOnMultipleInheritance() 0 25 2
A testRecursiveSave() 0 19 1
A testForeignKeyPointingToNonPrimaryKey() 0 13 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 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 testFirstNull() 0 7 1
A testOrderByException() 0 6 1
A testOptionnalParametersCanBeNullInFindOneBy() 0 7 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 testFirst() 0 7 1
A testJsonIgnore() 0 15 1
A testFindOneByGeneration() 0 8 1
A testBlobResourceException() 0 5 1
A testDiscardChanges() 0 12 1
A testJsonInclude() 0 10 1
A testSortOnInheritedTable() 0 12 1
A testJsonRecursive() 0 14 1
A testUuidv4() 0 7 1
A testReadAndSaveBlob() 0 9 1
A testUniqueIndexBasedSearch() 0 7 1
A testJsonFormat() 0 18 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\TestArticleDao;
34
use TheCodingMachine\TDBM\Dao\TestCountryDao;
35
use TheCodingMachine\TDBM\Dao\TestRoleDao;
36
use TheCodingMachine\TDBM\Dao\TestUserDao;
37
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserDaoInterface;
38
use TheCodingMachine\TDBM\Fixtures\Interfaces\TestUserInterface;
39
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...
40
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...
41
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...
42
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...
43
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...
44
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...
45
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...
46
use TheCodingMachine\TDBM\Test\Dao\Bean\ArrayBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\ArrayBean 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\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...
48
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...
49
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...
50
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...
51
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...
52
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...
53
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...
54
use TheCodingMachine\TDBM\Test\Dao\Bean\DateArrayBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\DateArrayBean 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\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...
56
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...
57
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...
58
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...
59
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...
60
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...
61
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...
62
use TheCodingMachine\TDBM\Test\Dao\Bean\ObjectBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\ObjectBaseBean 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\ObjectInheritedBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...ean\ObjectInheritedBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
77
use TheCodingMachine\TDBM\Test\Dao\Generated\ContactBaseDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...enerated\ContactBaseDao 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\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...
79
use TheCodingMachine\TDBM\Test\Dao\NodeDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\NodeDao was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

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

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

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

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

1710
        /** @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...
1711
        $firstLine = fgets($resource);
1712
        $this->assertSame("<?php\n", $firstLine);
1713
    }
1714
1715
    /**
1716
     * @depends testBlob
1717
     */
1718
    public function testReadBlob(): void
1719
    {
1720
        $fileDao = new FileDao($this->tdbmService);
1721
        $loadedFile = $fileDao->getById(1);
1722
1723
        $resource = $loadedFile->getFile();
1724
        $this->assertInternalType('resource', $resource);
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\Assert::assertInternalType() has been deprecated: https://github.com/sebastianbergmann/phpunit/issues/3369 ( Ignorable by Annotation )

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

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

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

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

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

2055
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
2056
    }
2057
2058
    /**
2059
     * @depends testDaoGeneration
2060
     */
2061
    public function testOptionnalParametersCanBeNullInFindOneBy()
2062
    {
2063
        $albumDao = new AlbumDao($this->tdbmService);
2064
        $artist = new ArtistBean('Marcel');
2065
2066
        $albumDao->findOneByArtistAndNode($artist, null);
2067
        $this->assertEquals(1, 1);
2068
    }
2069
2070
    /**
2071
     * @depends testDaoGeneration
2072
     */
2073
    public function testRequiredParametersCannotBeNullInFindOneBy()
2074
    {
2075
        $albumDao = new AlbumDao($this->tdbmService);
2076
        $artist = new ArtistBean('Marcel');
2077
        $account = new AccountBean('Jamie');
2078
2079
        $albumDao->findOneByArtistAndAccount($artist, $account);
2080
2081
        $this->expectException('TypeError');
2082
        $albumDao->findOneByArtistAndAccount($artist, null);
2083
    }
2084
2085
    /**
2086
     * @depends testDaoGeneration
2087
     */
2088
    public function testLazyLoad(): void
2089
    {
2090
        $roleDao = new RoleDao($this->tdbmService);
2091
        $roleBean = $roleDao->getById(1, true);
2092
2093
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2094
        $roleBean->getId();
2095
        $this->assertSame(TDBMObjectStateEnum::STATE_NOT_LOADED, $roleBean->_getDbRows()['roles']->_getStatus());
2096
    }
2097
2098
    /**
2099
     * @depends testDaoGeneration
2100
     */
2101
    public function testOneToOneInverseRelationGetter(): void
2102
    {
2103
        $objectBaseDao = new ObjectBaseDao($this->tdbmService);
2104
        $objectInheritedDao = new ObjectInheritedDao($this->tdbmService);
2105
        $objectBase = new ObjectBaseBean('label');
2106
        $objectBaseDao->save($objectBase);
2107
        $this->assertNull($objectBase->getObjectInherited());
2108
        $objectInherited = new ObjectInheritedBean($objectBase);
2109
        $objectInheritedDao->save($objectInherited);
2110
        $this->assertSame($objectInherited, $objectBase->getObjectInherited());
2111
        $this->assertEquals(1, $objectBase->jsonSerialize()['objectInherited']['id']);
2112
    }
2113
2114
    public function testLazyStopRecursion(): void
2115
    {
2116
        $albumDao = new AlbumDao($this->tdbmService);
2117
        $albumBean = $albumDao->getById(1);
2118
        $json = $albumBean->jsonSerialize(true);
2119
        $this->assertArrayHasKey('id', $json['artist']);
2120
        $this->assertArrayNotHasKey('name', $json['artist']);
2121
    }
2122
2123
    public function testLazyStopRecursionOnCompositeForeignKey(): void
2124
    {
2125
        $compositeFkSourceDao = new CompositeFkSourceDao($this->tdbmService);
2126
        $compositeFkSourceBean = $compositeFkSourceDao->getById(1);
2127
        $json = $compositeFkSourceBean->jsonSerialize(true);
2128
        $this->assertEquals(1, $json['compositeFkTarget']['id1']);
2129
        $this->assertEquals(1, $json['compositeFkTarget']['id2']);
2130
    }
2131
}
2132