Passed
Pull Request — master (#132)
by Dorian
04:52
created

TDBMDaoGeneratorTest   F

Complexity

Total Complexity 127

Size/Duplication

Total Lines 1797
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 127
eloc 709
dl 0
loc 1797
rs 1.891
c 0
b 0
f 0

112 Methods

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

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

1684
        /** @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...
1685
        $firstLine = fgets($resource);
1686
        $this->assertSame("<?php\n", $firstLine);
1687
    }
1688
1689
    /**
1690
     * @depends testBlob
1691
     */
1692
    public function testReadBlob()
1693
    {
1694
        $fileDao = new FileDao($this->tdbmService);
1695
        $loadedFile = $fileDao->getById(1);
1696
1697
        $resource = $loadedFile->getFile();
1698
        $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

1698
        /** @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...
1699
        $firstLine = fgets($resource);
1700
        $this->assertSame("<?php\n", $firstLine);
1701
1702
        stream_get_contents($resource);
1703
1704
        $loadedFile->setId($loadedFile->getId());
1705
1706
        $fileDao->save($loadedFile);
1707
    }
1708
1709
    /**
1710
     * @depends testReadBlob
1711
     */
1712
    public function testReadAndSaveBlob()
1713
    {
1714
        $fileDao = new FileDao($this->tdbmService);
1715
        $loadedFile = $fileDao->getById(1);
1716
1717
        $resource = $loadedFile->getFile();
1718
1719
        $firstLine = fgets($resource);
1720
        $this->assertSame("<?php\n", $firstLine);
1721
    }
1722
1723
    /**
1724
     * @depends testReadBlob
1725
     */
1726
    public function testProtectedGetterSetter()
1727
    {
1728
        $md5Getter = new ReflectionMethod(FileBaseBean::class, 'getMd5');
1729
        $md5Setter = new ReflectionMethod(FileBaseBean::class, 'setMd5');
1730
1731
        $this->assertTrue($md5Getter->isProtected());
1732
        $this->assertTrue($md5Setter->isProtected());
1733
1734
        $md5Getter2 = new ReflectionMethod(FileBaseBean::class, 'getArticle');
1735
        $md5Setter2 = new ReflectionMethod(FileBaseBean::class, 'setArticle');
1736
1737
        $this->assertTrue($md5Getter2->isProtected());
1738
        $this->assertTrue($md5Setter2->isProtected());
1739
1740
        $oneToManyGetter = new ReflectionMethod(ArticleBaseBean::class, 'getFiles');
1741
        $this->assertTrue($oneToManyGetter->isProtected());
1742
1743
        $fileDao = new FileDao($this->tdbmService);
1744
        $loadedFile = $fileDao->getById(1);
1745
1746
        // The md5 and article columns are not JSON serialized
1747
        $this->assertSame([
1748
            'id' => 1,
1749
        ], $loadedFile->jsonSerialize());
1750
    }
1751
1752
    /**
1753
     * @depends testDaoGeneration
1754
     */
1755
    public function testBlobResourceException()
1756
    {
1757
        $this->expectException(TDBMInvalidArgumentException::class);
1758
        $this->expectExceptionMessage('Invalid argument passed to \'TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\Generated\\FileBaseBean::setFile\'. Expecting a resource. Got a string.');
1759
        new FileBean('foobar');
1760
    }
1761
1762
    /**
1763
     * @depends testDaoGeneration
1764
     */
1765
    public function testFilterBag()
1766
    {
1767
        $userDao = new TestUserDao($this->tdbmService);
1768
        $countryDao = new CountryDao($this->tdbmService);
1769
1770
        $country = $countryDao->getById(2);
1771
1772
        // Let's test filter bags by bean and filter bag with many values.
1773
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'Jane Doe']);
1774
1775
        $this->assertCount(1, $users);
1776
        $this->assertSame('John Doe', $users[0]->getName());
1777
    }
1778
1779
    /**
1780
     * @depends testDaoGeneration
1781
     */
1782
    public function testDecimalIsMappedToString()
1783
    {
1784
        $reflectionClass = new \ReflectionClass(BoatBaseBean::class);
1785
        $this->assertSame('string', (string) $reflectionClass->getMethod('getLength')->getReturnType());
1786
    }
1787
1788
    /**
1789
     * @depends testDaoGeneration
1790
     */
1791
    public function testNoGetByIdOnMultiPrimaryKeys()
1792
    {
1793
        $reflectionClass = new \ReflectionClass(StateDao::class);
1794
        $this->assertFalse($reflectionClass->hasMethod('getById'));
1795
    }
1796
1797
    /**
1798
     * @depends testDaoGeneration
1799
     */
1800
    public function testInsertMultiPrimaryKeysBean()
1801
    {
1802
        $countryDao = new CountryDao($this->tdbmService);
1803
1804
        $country = $countryDao->getById(1);
1805
1806
        $stateDao = new StateDao($this->tdbmService);
1807
        $state = new StateBean($country, 'IDF', 'Ile de France');
1808
        $stateDao->save($state);
1809
1810
        $this->assertSame($state, $stateDao->findAll()[0]);
1811
    }
1812
1813
    /**
1814
     * @depends testInsertMultiPrimaryKeysBean
1815
     */
1816
    public function testDeleteMultiPrimaryKeysBean()
1817
    {
1818
        $stateDao = new StateDao($this->tdbmService);
1819
1820
        $state = $stateDao->findAll()[0];
1821
        $stateDao->delete($state);
1822
        $this->assertCount(0, $stateDao->findAll());
1823
1824
    }
1825
1826
    /**
1827
     * @depends testDaoGeneration
1828
     */
1829
    public function testSortOnInheritedTable()
1830
    {
1831
        $animalDao = new AnimalDao($this->tdbmService);
1832
1833
        // Let's insert an animal that is nothing.
1834
        $animal = new AnimalBean('Mickey');
1835
        $animalDao->save($animal);
1836
1837
        $animals = $animalDao->findAll()->withOrder('dog.race ASC');
1838
1839
        $animalsArr = $animals->toArray();
1840
        $this->assertCount(3, $animalsArr);
1841
    }
1842
1843
    public function testJsonAnnotations()
1844
    {
1845
        $nodeDao = new NodeDao($this->tdbmService);
1846
        $index = $nodeDao->getById(4);
1847
        $json = $index->jsonSerialize();
1848
1849
        self::assertArrayNotHasKey('id', $json);
1850
        self::assertArrayNotHasKey('alias', $json);
1851
        self::assertArrayHasKey('parent', $json);
1852
        self::assertArrayHasKey('parent', $json['parent']);
1853
        self::assertEquals($index->getCreatedAt()->format('Y-m-d'), $json['createdAt']);
1854
    }
1855
1856
    public function testJsonObjectNamedArray()
1857
    {
1858
        $parent = new ArrayBean('foo', 'bar');
1859
        $child = new ArrayBean('baz', 'qux');
1860
        $child->setArray($parent);
1861
        $json = $child->jsonSerialize();
1862
        self::assertIsArray($json);
1863
        self::assertArrayHasKey('array', $json);
1864
    }
1865
1866
    public function testJsonDateNamedArray()
1867
    {
1868
        $dateArray = new DateArrayBean();
1869
        $dateArray->setArray(new \DateTimeImmutable('now'));
1870
        $json = $dateArray->jsonSerialize();
1871
        self::assertIsArray($json);
1872
        self::assertArrayHasKey('array', $json);
1873
    }
1874
}
1875