Passed
Pull Request — master (#126)
by David
05:10
created

TDBMDaoGeneratorTest::testFindOneByRetunsNull()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

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

1677
        /** @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...
1678
        $firstLine = fgets($resource);
1679
        $this->assertSame("<?php\n", $firstLine);
1680
    }
1681
1682
    /**
1683
     * @depends testBlob
1684
     */
1685
    public function testReadBlob()
1686
    {
1687
        $fileDao = new FileDao($this->tdbmService);
1688
        $loadedFile = $fileDao->getById(1);
1689
1690
        $resource = $loadedFile->getFile();
1691
        $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

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