Passed
Push — phpstan ( abd307...309e5a )
by David
03:19
created

testPartialMultiColumnsIndexBasedSearch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
/*
4
 Copyright (C) 2006-2014 David Négrier - THE CODING MACHINE
5
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
10
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
GNU General Public License for more details.
15
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
*/
20
21
namespace TheCodingMachine\TDBM;
22
23
use Doctrine\Common\Cache\ArrayCache;
24
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
25
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
26
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
27
use Ramsey\Uuid\Uuid;
28
use TheCodingMachine\TDBM\Dao\TestArticleDao;
29
use TheCodingMachine\TDBM\Dao\TestCountryDao;
30
use TheCodingMachine\TDBM\Dao\TestRoleDao;
31
use TheCodingMachine\TDBM\Dao\TestUserDao;
32
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...
33
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...
34
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...
35
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...
36
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...
37
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...
38
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...
39
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...
40
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...
41
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...
42
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...
43
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...
44
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...
45
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...
46
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...
47
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...
48
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...
49
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...
50
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...
51
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...
52
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...
53
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...
54
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...
55
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...
56
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...
57
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...
58
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...
59
use TheCodingMachine\TDBM\Utils\PathFinder\NoPathFoundException;
60
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
61
use Symfony\Component\Process\Process;
62
63
class TDBMDaoGeneratorTest extends TDBMAbstractServiceTest
64
{
65
    /** @var TDBMDaoGenerator $tdbmDaoGenerator */
66
    protected $tdbmDaoGenerator;
67
68
    private $rootPath;
69
70
    protected function setUp()
71
    {
72
        parent::setUp();
73
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
74
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
75
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
76
        $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
77
        $this->rootPath = __DIR__ . '/../';
78
        //$this->tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
79
    }
80
81
    public function testDaoGeneration()
82
    {
83
        // Remove all previously generated files.
84
        $this->recursiveDelete($this->rootPath . 'src/Test/Dao/');
85
86
        $this->tdbmDaoGenerator->generateAllDaosAndBeans();
87
88
        // Let's require all files to check they are valid PHP!
89
        // Test the daoFactory
90
        require_once $this->rootPath . 'src/Test/Dao/Generated/DaoFactory.php';
91
        // Test the others
92
93
        $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
94
95
        foreach ($beanDescriptors as $beanDescriptor) {
96
            $daoName = $beanDescriptor->getDaoClassName();
97
            $daoBaseName = $beanDescriptor->getBaseDaoClassName();
98
            $beanName = $beanDescriptor->getBeanClassName();
99
            $baseBeanName = $beanDescriptor->getBaseBeanClassName();
100
            require_once $this->rootPath . 'src/Test/Dao/Bean/Generated/' . $baseBeanName . '.php';
101
            require_once $this->rootPath . 'src/Test/Dao/Bean/' . $beanName . '.php';
102
            require_once $this->rootPath . 'src/Test/Dao/Generated/' . $daoBaseName . '.php';
103
            require_once $this->rootPath . 'src/Test/Dao/' . $daoName . '.php';
104
        }
105
106
        // Check that pivot tables do not generate DAOs or beans.
107
        $this->assertFalse(class_exists('TheCodingMachine\\TDBM\\Test\\Dao\\RolesRightDao'));
108
    }
109
110
    public function testGenerationException()
111
    {
112
        $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', self::getConnection(), $this->getNamingStrategy());
113
114
        $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
115
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
116
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
117
        $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
118
        $this->rootPath = __DIR__ . '/../../../../';
119
        //$tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
120
121
        $this->expectException(NoPathFoundException::class);
122
        $tdbmDaoGenerator->generateAllDaosAndBeans();
123
    }
124
125
    /**
126
     * Delete a file or recursively delete a directory.
127
     *
128
     * @param string $str Path to file or directory
129
     * @return bool
130
     */
131
    private function recursiveDelete(string $str): bool
132
    {
133
        if (is_file($str)) {
134
            return @unlink($str);
135
        } elseif (is_dir($str)) {
136
            $scan = glob(rtrim($str, '/') . '/*');
137
            foreach ($scan as $index => $path) {
138
                $this->recursiveDelete($path);
139
            }
140
141
            return @rmdir($str);
142
        }
143
        return false;
144
    }
145
146
    /**
147
     * @depends testDaoGeneration
148
     */
149
    public function testGetBeanClassName()
150
    {
151
        $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
152
    }
153
154
    /**
155
     * @depends testDaoGeneration
156
     */
157
    public function testGetBeanClassNameException()
158
    {
159
        $this->expectException(TDBMInvalidArgumentException::class);
160
        $this->tdbmService->getBeanClassName('not_exists');
161
    }
162
163
    /**
164
     * @depends testDaoGeneration
165
     */
166
    public function testGeneratedGetById()
167
    {
168
        $contactDao = new ContactDao($this->tdbmService);
169
        $contactBean = $contactDao->getById(1);
170
        $this->assertEquals(1, $contactBean->getId());
171
        $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
172
173
        // FIXME: Question: que faire du paramètre stockage "UTC"????
174
    }
175
176
    /**
177
     * @depends testDaoGeneration
178
     */
179
    public function testGeneratedGetByIdLazyLoaded()
180
    {
181
        $roleDao = new RoleDao($this->tdbmService);
182
        $roleBean = $roleDao->getById(1, true);
183
        $this->assertEquals(1, $roleBean->getId());
184
        $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
185
186
        $roleBean2 = $roleDao->getById(1, true);
187
        $this->assertTrue($roleBean === $roleBean2);
188
    }
189
190
    /**
191
     * @depends testDaoGeneration
192
     */
193
    public function testDefaultValueOnNewBean()
194
    {
195
        $roleBean = new RoleBean('my_role');
196
        $this->assertEquals(1, $roleBean->getStatus());
197
    }
198
199
    /**
200
     * @depends testDaoGeneration
201
     */
202
    public function testForeignKeyInBean()
203
    {
204
        $userDao = new UserDao($this->tdbmService);
205
        $userBean = $userDao->getById(1);
206
        $country = $userBean->getCountry();
207
208
        $this->assertEquals('UK', $country->getLabel());
209
210
        $userBean2 = $userDao->getById(1);
211
        $this->assertTrue($userBean === $userBean2);
212
213
        $contactDao = new ContactDao($this->tdbmService);
214
        $contactBean = $contactDao->getById(1);
215
216
        $this->assertTrue($userBean === $contactBean);
217
    }
218
219
    /**
220
     * @depends testDaoGeneration
221
     */
222
    public function testNewBeans()
223
    {
224
        $countryDao = new CountryDao($this->tdbmService);
225
        $userDao = new UserDao($this->tdbmService);
226
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
227
        $userBean->setOrder(1); // Let's set a "protected keyword" column.
228
229
        $userDao->save($userBean);
230
231
        $this->assertNull($userBean->getManager());
232
    }
233
234
    /**
235
     * @depends testDaoGeneration
236
     */
237
    public function testDateTimeImmutableGetter()
238
    {
239
        $userDao = new UserDao($this->tdbmService);
240
        $user = $userDao->getById(1);
241
242
        $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
243
    }
244
245
    /**
246
     * @depends testDaoGeneration
247
     */
248
    public function testAssigningNewBeans()
249
    {
250
        $userDao = new UserDao($this->tdbmService);
251
        $countryBean = new CountryBean('Mexico');
252
        $userBean = new UserBean('Speedy Gonzalez', '[email protected]', $countryBean, 'speedy.gonzalez');
253
        $this->assertEquals($countryBean, $userBean->getCountry());
254
255
        $userDao->save($userBean);
256
    }
257
258
    /**
259
     * @depends testAssigningNewBeans
260
     */
261
    public function testUpdatingProtectedColumn()
262
    {
263
        $userDao = new UserDao($this->tdbmService);
264
        $userBean = $userDao->findOneByLogin('speedy.gonzalez');
265
        $userBean->setOrder(2);
266
        $userDao->save($userBean);
267
    }
268
269
    /**
270
     * @depends testDaoGeneration
271
     */
272
    public function testAssigningExistingRelationship()
273
    {
274
        $userDao = new UserDao($this->tdbmService);
275
        $user = $userDao->getById(1);
276
        $countryDao = new CountryDao($this->tdbmService);
277
        $country = $countryDao->getById(2);
278
279
        $user->setCountry($country);
280
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
281
    }
282
283
    /**
284
     * @depends testDaoGeneration
285
     */
286
    public function testDirectReversedRelationship()
287
    {
288
        $countryDao = new CountryDao($this->tdbmService);
289
        $country = $countryDao->getById(1);
290
        $users = $country->getUsers();
291
292
        $arr = $users->toArray();
293
294
        $this->assertCount(1, $arr);
295
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
296
        $this->assertEquals('jean.dupont', $arr[0]->getLogin());
297
298
        $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...
299
        $users = $country->getUsers();
300
301
        $arr = $users->toArray();
302
303
        $this->assertCount(2, $arr);
304
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
305
        $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
306
    }
307
308
    /**
309
     * @depends testDaoGeneration
310
     */
311
    public function testDeleteInDirectReversedRelationship()
312
    {
313
        $countryDao = new CountryDao($this->tdbmService);
314
        $country = $countryDao->getById(1);
315
316
        $userDao = new UserDao($this->tdbmService);
317
        $newUser = new UserBean('John Snow', '[email protected]', $country, 'john.snow');
318
        $userDao->save($newUser);
319
320
        $users = $country->getUsers();
321
322
        $arr = $users->toArray();
323
324
        $this->assertCount(2, $arr);
325
326
        $userDao->delete($arr[1]);
327
328
        $users = $country->getUsers();
329
        $arr = $users->toArray();
330
        $this->assertCount(1, $arr);
331
    }
332
333
    /**
334
     * @depends testDaoGeneration
335
     */
336
    public function testJointureGetters()
337
    {
338
        $roleDao = new RoleDao($this->tdbmService);
339
        $role = $roleDao->getById(1);
340
        $users = $role->getUsers();
341
342
        $this->assertCount(2, $users);
343
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
344
345
        $rights = $role->getRights();
346
347
        $this->assertCount(2, $rights);
348
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
349
    }
350
351
    /**
352
     * @depends testDaoGeneration
353
     */
354
    public function testNestedIterationOnAlterableResultIterator()
355
    {
356
        $countryDao = new CountryDao($this->tdbmService);
357
        $country = $countryDao->getById(2);
358
359
        $count = 0;
360
        // Let's perform 2 nested calls to check that iterators do not melt.
361
        foreach ($country->getUsers() as $user) {
362
            foreach ($country->getUsers() as $user2) {
363
                $count++;
364
            }
365
        }
366
        // There are 3 users linked to country 2.
367
        $this->assertSame(9, $count);
368
    }
369
370
    /**
371
     * @depends testDaoGeneration
372
     */
373
    public function testNewBeanConstructor()
374
    {
375
        $role = new RoleBean('Newrole');
376
        $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
377
    }
378
379
    /**
380
     * @depends testDaoGeneration
381
     */
382
    public function testJointureAdderOnNewBean()
383
    {
384
        $countryDao = new CountryDao($this->tdbmService);
385
        $country = $countryDao->getById(1);
386
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
387
        $role = new RoleBean('Mouse');
388
        $user->addRole($role);
389
        $roles = $user->getRoles();
390
        $this->assertCount(1, $roles);
391
        $role = $roles[0];
392
        $this->assertInstanceOf('TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
393
        $users = $role->getUsers();
394
        $this->assertCount(1, $users);
395
        $this->assertEquals($user, $users[0]);
396
397
        $role->removeUser($user);
398
        $this->assertCount(0, $role->getUsers());
399
        $this->assertCount(0, $user->getRoles());
400
    }
401
402
    /**
403
     * @depends testDaoGeneration
404
     */
405
    public function testJointureDeleteBeforeGetters()
406
    {
407
        $roleDao = new RoleDao($this->tdbmService);
408
        $userDao = new UserDao($this->tdbmService);
409
        $role = $roleDao->getById(1);
410
        $user = $userDao->getById(1);
411
412
        // We call removeUser BEFORE calling getUsers
413
        // This should work as expected.
414
        $role->removeUser($user);
415
        $users = $role->getUsers();
416
417
        $this->assertCount(1, $users);
418
    }
419
420
    /**
421
     * @depends testDaoGeneration
422
     */
423
    public function testJointureMultiAdd()
424
    {
425
        $countryDao = new CountryDao($this->tdbmService);
426
        $country = $countryDao->getById(1);
427
        $user = new UserBean('Speedy Gonzalez', '[email protected]', $country, 'speedy.gonzalez');
428
        $role = new RoleBean('Mouse');
429
        $user->addRole($role);
430
        $role->addUser($user);
431
        $user->addRole($role);
432
433
        $this->assertCount(1, $user->getRoles());
434
    }
435
436
    /**
437
     * Step 1: we remove the role 1 from user 1 but save role 1.
438
     * Expected result: no save done.
439
     *
440
     * @depends testDaoGeneration
441
     */
442
    public function testJointureSave1()
443
    {
444
        $roleDao = new RoleDao($this->tdbmService);
445
        $role = $roleDao->getById(1);
446
        $userDao = new UserDao($this->tdbmService);
447
        $user = $userDao->getById(1);
448
449
        $this->assertTrue($user->hasRole($role));
450
        $this->assertTrue($role->hasUser($user));
451
        $user->removeRole($role);
452
        $this->assertFalse($user->hasRole($role));
453
        $this->assertFalse($role->hasUser($user));
454
        $roleDao->save($role);
455
456
        $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
457
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
458
    }
459
460
    /**
461
     * Step 2: we check that nothing was saved
462
     * Expected result: no save done.
463
     *
464
     * @depends testJointureSave1
465
     */
466
    public function testJointureSave2()
467
    {
468
        $roleDao = new RoleDao($this->tdbmService);
469
        $role = $roleDao->getById(1);
470
        $this->assertCount(2, $role->getUsers());
471
    }
472
473
    /**
474
     * Step 3: we remove the role 1 from user 1 and save user 1.
475
     * Expected result: save done.
476
     *
477
     * @depends testJointureSave2
478
     */
479
    public function testJointureSave3()
480
    {
481
        $roleDao = new RoleDao($this->tdbmService);
482
        $role = $roleDao->getById(1);
483
        $userDao = new UserDao($this->tdbmService);
484
        $user = $userDao->getById(1);
485
486
        $this->assertCount(1, $user->getRoles());
487
        $user->removeRole($role);
488
        $this->assertCount(0, $user->getRoles());
489
        $userDao->save($user);
490
        $this->assertCount(0, $user->getRoles());
491
    }
492
493
    /**
494
     * Step 4: we check that save was done
495
     * Expected result: save done.
496
     *
497
     * @depends testJointureSave3
498
     */
499
    public function testJointureSave4()
500
    {
501
        $roleDao = new RoleDao($this->tdbmService);
502
        $role = $roleDao->getById(1);
503
        $this->assertCount(1, $role->getUsers());
504
        $userDao = new UserDao($this->tdbmService);
505
        $user = $userDao->getById(1);
506
        $this->assertCount(0, $user->getRoles());
507
    }
508
509
    /**
510
     * Step 5: we add the role 1 from user 1 and save user 1.
511
     * Expected result: save done.
512
     *
513
     * @depends testJointureSave4
514
     */
515
    public function testJointureSave5()
516
    {
517
        $roleDao = new RoleDao($this->tdbmService);
518
        $role = $roleDao->getById(1);
519
        $userDao = new UserDao($this->tdbmService);
520
        $user = $userDao->getById(1);
521
522
        $user->addRole($role);
523
        $this->assertCount(1, $user->getRoles());
524
        $userDao->save($user);
525
    }
526
527
    /**
528
     * Step 6: we check that save was done
529
     * Expected result: save done.
530
     *
531
     * @depends testJointureSave5
532
     */
533
    public function testJointureSave6()
534
    {
535
        $roleDao = new RoleDao($this->tdbmService);
536
        $role = $roleDao->getById(1);
537
        $this->assertCount(2, $role->getUsers());
538
        $userDao = new UserDao($this->tdbmService);
539
        $user = $userDao->getById(1);
540
        $this->assertCount(1, $user->getRoles());
541
    }
542
543
    /**
544
     * Step 7: we add a new role to user 1 and save user 1.
545
     * Expected result: save done, including the new role.
546
     *
547
     * @depends testJointureSave6
548
     */
549
    public function testJointureSave7()
550
    {
551
        $role = new RoleBean('my new role');
552
        $userDao = new UserDao($this->tdbmService);
553
        $user = $userDao->getById(1);
554
555
        $user->addRole($role);
556
        $userDao->save($user);
557
558
        $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
559
    }
560
561
    /**
562
     * Step 8: we check that save was done
563
     * Expected result: save done.
564
     *
565
     * @depends testJointureSave7
566
     */
567
    public function testJointureSave8()
568
    {
569
        $roleDao = new RoleDao($this->tdbmService);
570
        $userDao = new UserDao($this->tdbmService);
571
        $user = $userDao->getById(1);
572
573
        $roles = $user->getRoles();
574
        foreach ($roles as $role) {
575
            if ($role->getName() === 'my new role') {
576
                $selectedRole = $role;
577
                break;
578
            }
579
        }
580
        $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...
581
582
        $this->assertCount(2, $user->getRoles());
583
584
        // Expected: relationship removed!
585
        $roleDao->delete($selectedRole);
586
587
        $this->assertCount(1, $user->getRoles());
588
    }
589
590
    /**
591
     * Step 9: Let's test the setXXX method.
592
     *
593
     * @depends testJointureSave8
594
     */
595
    public function testJointureSave9()
596
    {
597
        $roleDao = new RoleDao($this->tdbmService);
598
        $userDao = new UserDao($this->tdbmService);
599
        $user = $userDao->getById(1);
600
601
        // At this point, user 1 is linked to role 1.
602
        // Let's bind it to role 2.
603
        $user->setRoles([$roleDao->getById(2)]);
604
        $userDao->save($user);
605
    }
606
607
    /**
608
     * Step 10: Let's check results of 9.
609
     *
610
     * @depends testJointureSave9
611
     */
612
    public function testJointureSave10()
613
    {
614
        $userDao = new UserDao($this->tdbmService);
615
        $user = $userDao->getById(1);
616
617
        $roles = $user->getRoles();
618
619
        $this->assertCount(1, $roles);
620
        $this->assertEquals(2, $roles[0]->getId());
621
    }
622
623
    /**
624
     * @depends testDaoGeneration
625
     */
626
    public function testFindOrderBy()
627
    {
628
        $userDao = new TestUserDao($this->tdbmService);
629
        $users = $userDao->getUsersByAlphabeticalOrder();
630
631
        $this->assertCount(6, $users);
632
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
633
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
634
635
        $users = $userDao->getUsersByCountryOrder();
636
        $this->assertCount(6, $users);
637
        $countryName1 = $users[0]->getCountry()->getLabel();
638
        for ($i = 1; $i < 6; $i++) {
639
            $countryName2 = $users[$i]->getCountry()->getLabel();
640
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
641
            $countryName1 = $countryName2;
642
        }
643
    }
644
645
    /**
646
     * @depends testDaoGeneration
647
     */
648
    public function testFindFromSqlOrderBy()
649
    {
650
        $userDao = new TestUserDao($this->tdbmService);
651
        $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
652
653
        $this->assertCount(6, $users);
654
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
655
        $this->assertEquals('jean.dupont', $users[1]->getLogin());
656
657
        $users = $userDao->getUsersFromSqlByCountryOrder();
658
        $this->assertCount(6, $users);
659
        $countryName1 = $users[0]->getCountry()->getLabel();
660
        for ($i = 1; $i < 6; $i++) {
661
            $countryName2 = $users[$i]->getCountry()->getLabel();
662
            $this->assertLessThanOrEqual(0, strcmp($countryName1, $countryName2));
663
            $countryName1 = $countryName2;
664
        }
665
    }
666
667
    /**
668
     * @depends testDaoGeneration
669
     */
670
    public function testFindFromSqlOrderByOnInheritedBean()
671
    {
672
        $articleDao = new TestArticleDao($this->tdbmService);
673
        $articles = $articleDao->getArticlesByUserLogin();
674
675
        foreach ($articles as $article) {
676
            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...
677
        }
678
        $this->assertCount(0, $articles);
679
    }
680
681
682
    /**
683
     * @depends testDaoGeneration
684
     */
685
    public function testFindFromSqlOrderByJoinRole()
686
    {
687
        $roleDao = new TestRoleDao($this->tdbmService);
688
        $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
689
690
        $this->assertCount(2, $roles);
691
        $this->assertEquals('Singers', $roles[0]->getName());
692
        $this->assertEquals('Admins', $roles[1]->getName());
693
    }
694
695
    /**
696
     * @depends testDaoGeneration
697
     */
698
    public function testFindFromRawSqlOrderByUserCount()
699
    {
700
        $countryDao = new TestCountryDao($this->tdbmService);
701
        $countries = $countryDao->getCountriesByUserCount();
702
703
        $this->assertCount(4, $countries);
704
        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...
705
            $this->assertLessThanOrEqual($countries[$i - 1]->getUsers()->count(), $countries[$i]->getUsers()->count());
706
        }
707
    }
708
709
    /**
710
     * @depends testDaoGeneration
711
     */
712
    public function testFindFromRawSqlWithUnion()
713
    {
714
        $countryDao = new TestCountryDao($this->tdbmService);
715
        $countries = $countryDao->getCountriesUsingUnion();
716
717
        $this->assertCount(2, $countries);
718
        $this->assertEquals(1, $countries[0]->getId());
719
    }
720
721
    /**
722
     * @depends testDaoGeneration
723
     */
724
    public function testFindFromRawSqlWithSimpleQuery()
725
    {
726
        $countryDao = new TestCountryDao($this->tdbmService);
727
        $countries = $countryDao->getCountriesUsingSimpleQuery();
728
729
        $this->assertCount(1, $countries);
730
        $this->assertEquals(1, $countries[0]->getId());
731
    }
732
733
    /**
734
     * @depends testDaoGeneration
735
     */
736
    public function testFindFromRawSqlWithDistinctQuery()
737
    {
738
        $countryDao = new TestCountryDao($this->tdbmService);
739
        $countries = $countryDao->getCountriesUsingDistinctQuery();
740
741
        $this->assertCount(1, $countries);
742
        $this->assertEquals(2, $countries[0]->getId());
743
    }
744
745
    /**
746
     * @depends testDaoGeneration
747
     */
748
    public function testFindFilters()
749
    {
750
        $userDao = new TestUserDao($this->tdbmService);
751
        $users = $userDao->getUsersByLoginStartingWith('bill');
752
753
        $this->assertCount(1, $users);
754
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
755
    }
756
757
    /**
758
     * @expectedException \TheCodingMachine\TDBM\TDBMException
759
     * @depends testDaoGeneration
760
     */
761
    public function testFindMode()
762
    {
763
        $userDao = new TestUserDao($this->tdbmService);
764
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
765
766
        $users[0];
767
    }
768
769
    /**
770
     * @depends testDaoGeneration
771
     */
772
    public function testFindAll()
773
    {
774
        $userDao = new TestUserDao($this->tdbmService);
775
        $users = $userDao->findAll();
776
777
        $this->assertCount(6, $users);
778
    }
779
780
    /**
781
     * @depends testDaoGeneration
782
     */
783
    public function testFindOne()
784
    {
785
        $userDao = new TestUserDao($this->tdbmService);
786
        $user = $userDao->getUserByLogin('bill.shakespeare');
787
788
        $this->assertEquals('bill.shakespeare', $user->getLogin());
789
    }
790
791
    /**
792
     * @depends testDaoGeneration
793
     */
794
    public function testJsonEncodeBean()
795
    {
796
        $userDao = new TestUserDao($this->tdbmService);
797
        $user = $userDao->getUserByLogin('bill.shakespeare');
798
799
        $jsonEncoded = json_encode($user);
800
        $userDecoded = json_decode($jsonEncoded, true);
801
802
        $this->assertEquals('bill.shakespeare', $userDecoded['login']);
803
804
        // test serialization of dates.
805
        $this->assertTrue(is_string($userDecoded['createdAt']));
806
        $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
807
        $this->assertNull($userDecoded['modifiedAt']);
808
809
        // testing many to 1 relationships
810
        $this->assertEquals('UK', $userDecoded['country']['label']);
811
812
        // testing many to many relationships
813
        $this->assertCount(1, $userDecoded['roles']);
814
        $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
815
        $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
816
    }
817
818
    /**
819
     * @depends testDaoGeneration
820
     */
821
    public function testNullableForeignKey()
822
    {
823
        $userDao = new TestUserDao($this->tdbmService);
824
        $user = $userDao->getUserByLogin('john.smith');
825
826
        $this->assertNull(null, $user->getManager());
827
828
        $jsonEncoded = json_encode($user);
829
        $userDecoded = json_decode($jsonEncoded, true);
830
831
        $this->assertNull(null, $userDecoded['manager']);
832
    }
833
834
    /**
835
     * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
836
     *
837
     * @depends testDaoGeneration
838
     */
839
    public function testSetToNullForeignKey()
840
    {
841
        $userDao = new TestUserDao($this->tdbmService);
842
        $user = $userDao->getUserByLogin('john.smith');
843
        $manager = $userDao->getUserByLogin('jean.dupont');
844
845
        $user->setManager($manager);
846
        $userDao->save($user);
847
848
        $user->setManager(null);
849
        $userDao->save($user);
850
    }
851
852
    /**
853
     * @depends testDaoGeneration
854
     * @expectedException \Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException
855
     * @expectedExceptionMessage Could not find table 'contacts'. Did you mean 'contact'?
856
     */
857
    public function testQueryOnWrongTableName()
858
    {
859
        $userDao = new TestUserDao($this->tdbmService);
860
        $users = $userDao->getUsersWrongTableName();
861
        $users->count();
862
    }
863
864
    /**
865
     * @depends testDaoGeneration
866
     */
867
    /*public function testQueryNullForeignKey()
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
868
    {
869
        $userDao = new TestUserDao($this->tdbmService);
870
        $users = $userDao->getUsersByManagerId(null);
871
        $this->assertCount(3, $users);
872
    }*/
873
874
    /**
875
     * @depends testDaoGeneration
876
     */
877
    public function testInnerJsonEncode()
878
    {
879
        $userDao = new TestUserDao($this->tdbmService);
880
        $user = $userDao->getUserByLogin('bill.shakespeare');
881
882
        $jsonEncoded = json_encode(['user' => $user]);
883
        $msgDecoded = json_decode($jsonEncoded, true);
884
885
        $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
886
    }
887
888
    /**
889
     * @depends testDaoGeneration
890
     */
891
    public function testArrayJsonEncode()
892
    {
893
        $userDao = new TestUserDao($this->tdbmService);
894
        $users = $userDao->getUsersByLoginStartingWith('bill');
895
896
        $jsonEncoded = json_encode($users);
897
        $msgDecoded = json_decode($jsonEncoded, true);
898
899
        $this->assertCount(1, $msgDecoded);
900
    }
901
902
    /**
903
     * @depends testDaoGeneration
904
     */
905
    public function testCursorJsonEncode()
906
    {
907
        $userDao = new TestUserDao($this->tdbmService);
908
        $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
909
910
        $jsonEncoded = json_encode($users);
911
        $msgDecoded = json_decode($jsonEncoded, true);
912
913
        $this->assertCount(1, $msgDecoded);
914
    }
915
916
    /**
917
     * @depends testDaoGeneration
918
     */
919
    public function testPageJsonEncode()
920
    {
921
        $userDao = new TestUserDao($this->tdbmService);
922
        $users = $userDao->getUsersByLoginStartingWith('bill');
923
924
        $jsonEncoded = json_encode($users->take(0, 1));
925
        $msgDecoded = json_decode($jsonEncoded, true);
926
927
        $this->assertCount(1, $msgDecoded);
928
    }
929
930
    /**
931
     * @depends testDaoGeneration
932
     */
933
    public function testFirst()
934
    {
935
        $userDao = new TestUserDao($this->tdbmService);
936
        $users = $userDao->getUsersByLoginStartingWith('bill');
937
938
        $bill = $users->first();
939
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
940
    }
941
942
    /**
943
     * @depends testDaoGeneration
944
     */
945
    public function testFirstNull()
946
    {
947
        $userDao = new TestUserDao($this->tdbmService);
948
        $users = $userDao->getUsersByLoginStartingWith('mike');
949
950
        $user = $users->first();
951
        $this->assertNull($user);
952
    }
953
954
    /**
955
     * @depends testDaoGeneration
956
     */
957
    public function testCloneBeanAttachedBean()
958
    {
959
        $userDao = new TestUserDao($this->tdbmService);
960
        $user = $userDao->getUserByLogin('bill.shakespeare');
961
        $this->assertEquals(4, $user->getId());
962
        $user2 = clone $user;
963
        $this->assertNull($user2->getId());
964
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
965
        $this->assertEquals('Bill Shakespeare', $user2->getName());
966
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
967
968
        // MANY 2 MANY must be duplicated
969
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
970
971
        // Let's test saving this clone
972
        $user2->setLogin('william.shakespeare');
973
        $userDao->save($user2);
974
975
        $user3 = $userDao->getUserByLogin('william.shakespeare');
976
        $this->assertTrue($user3 === $user2);
977
        $userDao->delete($user3);
978
979
        // Finally, let's test the origin user still exists!
980
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
981
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
982
    }
983
984
    /**
985
     * @depends testDaoGeneration
986
     */
987
    public function testCloneNewBean()
988
    {
989
        $countryDao = new CountryDao($this->tdbmService);
990
        $roleDao = new RoleDao($this->tdbmService);
991
        $role = $roleDao->getById(1);
992
993
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
994
        $userBean->addRole($role);
995
996
        $user2 = clone $userBean;
997
998
        $this->assertNull($user2->getId());
999
        $this->assertEquals('john.doe', $user2->getLogin());
1000
        $this->assertEquals('John Doe', $user2->getName());
1001
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1002
1003
        // MANY 2 MANY must be duplicated
1004
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
1005
    }
1006
1007
    /**
1008
     * @depends testDaoGeneration
1009
     */
1010
    public function testCascadeDelete()
1011
    {
1012
        $userDao = new TestUserDao($this->tdbmService);
1013
        $countryDao = new CountryDao($this->tdbmService);
1014
1015
        $spain = new CountryBean('Spain');
1016
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1017
1018
        $countryDao->save($spain);
1019
        $userDao->save($sanchez);
1020
1021
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1022
        $this->assertTrue($sanchez === $speedy2);
1023
1024
        $exceptionTriggered = false;
1025
        try {
1026
            $countryDao->delete($spain);
1027
        } catch (ForeignKeyConstraintViolationException $e) {
1028
            $exceptionTriggered = true;
1029
        }
1030
        $this->assertTrue($exceptionTriggered);
1031
1032
        $countryDao->delete($spain, true);
1033
1034
        // Let's check that speed gonzalez was removed.
1035
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1036
        $this->assertNull($speedy3);
1037
    }
1038
1039
    /**
1040
     * @depends testDaoGeneration
1041
     */
1042
    public function testDiscardChanges()
1043
    {
1044
        $contactDao = new ContactDao($this->tdbmService);
1045
        $contactBean = $contactDao->getById(1);
1046
1047
        $oldName = $contactBean->getName();
1048
1049
        $contactBean->setName('MyNewName');
1050
1051
        $contactBean->discardChanges();
1052
1053
        $this->assertEquals($oldName, $contactBean->getName());
1054
    }
1055
1056
    /**
1057
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1058
     * @depends testDaoGeneration
1059
     */
1060
    public function testDiscardChangesOnNewBeanFails()
1061
    {
1062
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1063
        $person->discardChanges();
1064
    }
1065
1066
    /**
1067
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1068
     * @depends testDaoGeneration
1069
     */
1070
    public function testDiscardChangesOnDeletedBeanFails()
1071
    {
1072
        $userDao = new TestUserDao($this->tdbmService);
1073
        $countryDao = new CountryDao($this->tdbmService);
1074
1075
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1076
1077
        $userDao->save($sanchez);
1078
1079
        $userDao->delete($sanchez);
1080
1081
        // Cannot discard changes on a bean that is already deleted.
1082
        $sanchez->discardChanges();
1083
    }
1084
1085
    /**
1086
     * @depends testDaoGeneration
1087
     */
1088
    public function testUniqueIndexBasedSearch()
1089
    {
1090
        $userDao = new UserDao($this->tdbmService);
1091
        $user = $userDao->findOneByLogin('bill.shakespeare');
1092
1093
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1094
        $this->assertEquals('Bill Shakespeare', $user->getName());
1095
    }
1096
1097
    /**
1098
     * @depends testDaoGeneration
1099
     */
1100
    public function testFindOneByRetunsNull()
1101
    {
1102
        // Let's assert that the findOneBy... methods can return null.
1103
        $userDao = new UserDao($this->tdbmService);
1104
        $userBean = $userDao->findOneByLogin('not_exist');
1105
1106
        $this->assertNull($userBean);
1107
    }
1108
1109
    /**
1110
     * @depends testDaoGeneration
1111
     */
1112
    public function testMultiColumnsIndexBasedSearch()
1113
    {
1114
        $countryDao = new CountryDao($this->tdbmService);
1115
        $userDao = new UserDao($this->tdbmService);
1116
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1117
1118
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1119
    }
1120
1121
    /**
1122
     * @depends testDaoGeneration
1123
     */
1124
    public function testPartialMultiColumnsIndexBasedSearch()
1125
    {
1126
        $userDao = new UserDao($this->tdbmService);
1127
        $users = $userDao->findByStatusAndCountry('on');
1128
1129
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1130
    }
1131
1132
    /**
1133
     * @depends testDaoGeneration
1134
     */
1135
    public function testCreationInNullableDate()
1136
    {
1137
        $roleDao = new RoleDao($this->tdbmService);
1138
1139
        $role = new RoleBean('newbee');
1140
        $roleDao->save($role);
1141
1142
        $this->assertNull($role->getCreatedAt());
1143
    }
1144
1145
    /**
1146
     * @depends testDaoGeneration
1147
     */
1148
    public function testUpdateInNullableDate()
1149
    {
1150
        $roleDao = new RoleDao($this->tdbmService);
1151
1152
        $role = new RoleBean('newbee');
1153
        $roleDao->save($role);
1154
1155
        $role->setCreatedAt(null);
1156
        $roleDao->save($role);
1157
        $this->assertNull($role->getCreatedAt());
1158
    }
1159
1160
    /**
1161
     * @depends testDaoGeneration
1162
     */
1163
    public function testFindFromSql()
1164
    {
1165
        $roleDao = new TestRoleDao($this->tdbmService);
1166
1167
        $roles = $roleDao->getRolesByRightCanSing();
1168
        $this->assertCount(2, $roles);
1169
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1170
    }
1171
1172
    /**
1173
     * @depends testDaoGeneration
1174
     */
1175
    public function testFindOneFromSql()
1176
    {
1177
        $roleDao = new TestRoleDao($this->tdbmService);
1178
1179
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1180
        $this->assertInstanceOf(RoleBean::class, $role);
1181
    }
1182
1183
    /**
1184
     * @depends testDaoGeneration
1185
     */
1186
    public function testCreateEmptyExtendedBean()
1187
    {
1188
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1189
1190
        $dogDao = new DogDao($this->tdbmService);
1191
1192
        // We are not filling no field that is part of dog table.
1193
        $dog = new DogBean('Youki');
1194
        $dog->setOrder(1);
1195
1196
        $dogDao->save($dog);
1197
    }
1198
1199
    /**
1200
     * @depends testCreateEmptyExtendedBean
1201
     */
1202
    public function testFetchEmptyExtendedBean()
1203
    {
1204
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1205
1206
        $animalDao = new AnimalDao($this->tdbmService);
1207
1208
        // We are not filling no field that is part of dog table.
1209
        $animalBean = $animalDao->getById(1);
1210
1211
        $this->assertInstanceOf(DogBean::class, $animalBean);
1212
    }
1213
1214
    /**
1215
     * @depends testDaoGeneration
1216
     */
1217
    public function testTwoBranchesHierarchy()
1218
    {
1219
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1220
1221
        $catDao = new CatDao($this->tdbmService);
1222
1223
        // We are not filling no field that is part of dog table.
1224
        $cat = new CatBean('Mew');
1225
        $cat->setOrder(2);
1226
1227
        $catDao->save($cat);
1228
    }
1229
1230
    /**
1231
     * @depends testTwoBranchesHierarchy
1232
     */
1233
    public function testFetchTwoBranchesHierarchy()
1234
    {
1235
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1236
1237
        $animalDao = new AnimalDao($this->tdbmService);
1238
1239
        $animalBean = $animalDao->getById(2);
1240
1241
        $this->assertInstanceOf(CatBean::class, $animalBean);
1242
        /* @var $animalBean CatBean */
1243
        $animalBean->setCutenessLevel(999);
1244
1245
        $animalDao->save($animalBean);
1246
    }
1247
1248
    /**
1249
     * @depends testDaoGeneration
1250
     */
1251
    public function testExceptionOnGetById()
1252
    {
1253
        $countryDao = new CountryDao($this->tdbmService);
1254
        $this->expectException(\TypeError::class);
1255
        $countryDao->getById(null);
1256
    }
1257
1258
    /**
1259
     * @depends testDaoGeneration
1260
     */
1261
    public function testDisconnectedManyToOne()
1262
    {
1263
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1264
1265
        $country = new CountryBean('Spain');
1266
1267
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1268
1269
        $this->assertCount(1, $country->getUsers());
1270
        $this->assertSame($user, $country->getUsers()[0]);
1271
    }
1272
1273
    /**
1274
     * @depends testDaoGeneration
1275
     */
1276
    public function testOrderByExternalCol()
1277
    {
1278
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1279
1280
        $userDao = new TestUserDao($this->tdbmService);
1281
        $users = $userDao->getUsersByCountryName();
1282
1283
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1284
    }
1285
1286
    /**
1287
     * @depends testDaoGeneration
1288
     */
1289
    public function testResultIteratorSort()
1290
    {
1291
        $userDao = new UserDao($this->tdbmService);
1292
        $users = $userDao->findAll()->withOrder('country.label DESC');
1293
1294
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1295
1296
        $users = $users->withOrder('country.label ASC');
1297
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1298
    }
1299
1300
    /**
1301
     * @depends testDaoGeneration
1302
     */
1303
    public function testResultIteratorWithParameters()
1304
    {
1305
        $userDao = new TestUserDao($this->tdbmService);
1306
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1307
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
0 ignored issues
show
Bug introduced by
The method getLogin() does not exist on TheCodingMachine\TDBM\AbstractTDBMObject. ( Ignorable by Annotation )

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

1307
        $this->assertEquals('bill.shakespeare', $users[0]->/** @scrutinizer ignore-call */ getLogin());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1308
1309
        $users = $users->withParameters(['login' => 'jean%']);
1310
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1311
    }
1312
1313
    /**
1314
     * @depends testDaoGeneration
1315
     */
1316
    public function testOrderByExpression()
1317
    {
1318
        $userDao = new TestUserDao($this->tdbmService);
1319
        $users = $userDao->getUsersByReversedCountryName();
1320
1321
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1322
    }
1323
1324
    /**
1325
     * @depends testDaoGeneration
1326
     */
1327
    public function testOrderByException()
1328
    {
1329
        $userDao = new TestUserDao($this->tdbmService);
1330
        $users = $userDao->getUsersByInvalidOrderBy();
1331
        $this->expectException(TDBMInvalidArgumentException::class);
1332
        $user = $users[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
1333
    }
1334
1335
    /**
1336
     * @depends testDaoGeneration
1337
     */
1338
    public function testOrderByProtectedColumn()
1339
    {
1340
        $animalDao = new AnimalDao($this->tdbmService);
1341
        $animals = $animalDao->findAll();
1342
        $animals = $animals->withOrder('`order` ASC');
1343
1344
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1345
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1346
1347
        $animals = $animals->withOrder('`order` DESC');
1348
1349
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1350
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1351
    }
1352
1353
    /**
1354
     * @depends testDaoGeneration
1355
     */
1356
    public function testGetOnAllNullableValues()
1357
    {
1358
        // Tests that a get performed on a column that has only nullable fields succeeds.
1359
        $allNullable = new AllNullableBean();
1360
        $this->assertNull($allNullable->getId());
1361
        $this->assertNull($allNullable->getLabel());
1362
        $this->assertNull($allNullable->getCountry());
1363
    }
1364
1365
    /**
1366
     * @depends testDaoGeneration
1367
     */
1368
    public function testExceptionOnMultipleInheritance()
1369
    {
1370
        $connection = self::getConnection();
1371
        self::insert($connection, 'animal', [
1372
            'id' => 99, 'name' => 'Snoofield',
1373
        ]);
1374
        self::insert($connection, 'dog', [
1375
            'id' => 99, 'race' => 'dog',
1376
        ]);
1377
        self::insert($connection, 'cat', [
1378
            'id' => 99, 'cuteness_level' => 0,
1379
        ]);
1380
1381
        $catched = false;
1382
        try {
1383
            $animalDao = new AnimalDao($this->tdbmService);
1384
            $animalDao->getById(99);
1385
        } catch (TDBMInheritanceException $e) {
1386
            $catched = true;
1387
        }
1388
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1389
1390
        self::delete($connection, 'cat', ['id' => 99]);
1391
        self::delete($connection, 'dog', ['id' => 99]);
1392
        self::delete($connection, 'animal', ['id' => 99]);
1393
    }
1394
1395
    /**
1396
     * @depends testDaoGeneration
1397
     */
1398
    public function testReferenceNotSaved()
1399
    {
1400
        $boatDao = new BoatDao($this->tdbmService);
1401
1402
        $country = new CountryBean('Atlantis');
1403
        $boat = new BoatBean($country, 'Titanic');
1404
1405
        $boatDao->save($boat);
1406
    }
1407
1408
    /**
1409
     * @depends testReferenceNotSaved
1410
     */
1411
    public function testUniqueIndexOnForeignKeyThenScalar()
1412
    {
1413
        $boatDao = new BoatDao($this->tdbmService);
1414
        $countryDao = new CountryDao($this->tdbmService);
1415
1416
        $countryBean = $countryDao->findOneByLabel('Atlantis');
1417
        $boatBean = $boatDao->findOneByAnchorageCountryAndName($countryBean, 'Titanic');
1418
1419
        $this->assertNotNull($boatBean);
1420
    }
1421
1422
    /**
1423
     * @depends testDaoGeneration
1424
     */
1425
    public function testReferenceDeleted()
1426
    {
1427
        $countryDao = new CountryDao($this->tdbmService);
1428
        $boatDao = new BoatDao($this->tdbmService);
1429
1430
        $country = new CountryBean('Bikini Bottom');
1431
        $countryDao->save($country);
1432
1433
        $boat = new BoatBean($country, 'Squirrel boat');
1434
        $countryDao->delete($country);
1435
1436
        $this->expectException(TDBMMissingReferenceException::class);
1437
        $boatDao->save($boat);
1438
    }
1439
1440
    /**
1441
     * @depends testDaoGeneration
1442
     */
1443
    public function testCyclicReferenceWithInheritance()
1444
    {
1445
        $userDao = new UserDao($this->tdbmService);
1446
1447
        $country = new CountryBean('Norrisland');
1448
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1449
1450
        $user->setManager($user);
1451
1452
        $this->expectException(TDBMCyclicReferenceException::class);
1453
        $userDao->save($user);
1454
    }
1455
1456
    /**
1457
     * @depends testDaoGeneration
1458
     */
1459
    public function testCyclicReference()
1460
    {
1461
        $categoryDao = new CategoryDao($this->tdbmService);
1462
1463
        $category = new CategoryBean('Root');
1464
1465
        $category->setParent($category);
1466
1467
        $this->expectException(TDBMCyclicReferenceException::class);
1468
        $categoryDao->save($category);
1469
    }
1470
1471
    /**
1472
     * @depends testDaoGeneration
1473
     */
1474
    public function testCorrectTypeForPrimaryKeyAfterSave()
1475
    {
1476
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1477
        $this->onlyMySql();
1478
1479
        $allNullableDao = new AllNullableDao($this->tdbmService);
1480
        $allNullable = new AllNullableBean();
1481
        $allNullableDao->save($allNullable);
1482
        $id = $allNullable->getId();
1483
1484
        $this->assertTrue(is_int($id));
1485
    }
1486
1487
    /**
1488
     * @depends testDaoGeneration
1489
     */
1490
    public function testPSR2Compliance()
1491
    {
1492
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
1493
        $process->run();
1494
1495
        // executes after the command finishes
1496
        if (!$process->isSuccessful()) {
1497
            echo $process->getOutput();
1498
            $this->fail('Generated code is not PSR-2 compliant');
1499
        }
1500
    }
1501
1502
    /**
1503
     * @depends testDaoGeneration
1504
     */
1505
    public function testFindOneByGeneration()
1506
    {
1507
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1508
        $parameters = $reflectionMethod->getParameters();
1509
1510
        $this->assertCount(2, $parameters);
1511
        $this->assertSame('login', $parameters[0]->getName());
1512
        $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
1513
    }
1514
1515
    /**
1516
     * @depends testDaoGeneration
1517
     */
1518
    public function testUuid()
1519
    {
1520
        $article = new ArticleBean('content');
1521
        $this->assertSame('content', $article->getContent());
1522
        $this->assertNotEmpty($article->getId());
1523
        $uuid = Uuid::fromString($article->getId());
1524
        $this->assertSame(1, $uuid->getVersion());
1525
    }
1526
1527
    /**
1528
     * @depends testDaoGeneration
1529
     */
1530
    public function testUuidv4()
1531
    {
1532
        $article = new Article2Bean('content');
1533
        $this->assertSame('content', $article->getContent());
1534
        $this->assertNotEmpty($article->getId());
1535
        $uuid = Uuid::fromString($article->getId());
1536
        $this->assertSame(4, $uuid->getVersion());
1537
    }
1538
1539
    /**
1540
     * @depends testDaoGeneration
1541
     */
1542
    public function testTypeHintedConstructors()
1543
    {
1544
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1545
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1546
1547
        $this->assertSame('string', (string)$nameParam->getType());
1548
    }
1549
1550
    /**
1551
     * @depends testDaoGeneration
1552
     */
1553
    public function testSaveTransaction()
1554
    {
1555
        $countryDao = new CountryDao($this->tdbmService);
1556
1557
        $boatDao = new BoatDao($this->tdbmService);
1558
        $boatBean = $boatDao->getById(1);
1559
        $boatBean->setName('Bismark');
1560
1561
        $boatBean->getCountry();
1562
1563
        // Let's insert a row without telling TDBM to trigger an error!
1564
        self::insert($this->getConnection(), 'sailed_countries', [
1565
            'boat_id' => 1,
1566
            'country_id' => 2
1567
        ]);
1568
1569
        $boatBean->addCountry($countryDao->getById(2));
1570
1571
        $this->expectException(UniqueConstraintViolationException::class);
1572
1573
        $boatDao->save($boatBean);
1574
    }
1575
1576
    /**
1577
     * @depends testSaveTransaction
1578
     */
1579
    public function testSaveTransaction2()
1580
    {
1581
        $boatDao = new BoatDao($this->tdbmService);
1582
        $boatBean = $boatDao->getById(1);
1583
1584
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1585
        $this->assertNotSame('Bismark', $boatBean->getName());
1586
    }
1587
1588
    /**
1589
     * @depends testDaoGeneration
1590
     */
1591
    public function testForeignKeyPointingToNonPrimaryKey()
1592
    {
1593
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1594
        $bean = $dao->getById(1);
1595
1596
        $this->assertSame('foo', $bean->getFrom()->getTo());
1597
1598
        $newBean = new RefNoPrimKeyBean($bean, 'baz');
1599
        $dao->save($newBean);
1600
        $this->assertSame('foo', $newBean->getFrom()->getTo());
1601
    }
1602
1603
    /**
1604
     * @depends testDaoGeneration
1605
     */
1606
    public function testCloningUuidBean()
1607
    {
1608
        $article = new ArticleBean('content');
1609
        $this->assertNotEmpty($article->getId());
1610
        $article2 = clone $article;
1611
        $this->assertNotEmpty($article2->getId());
1612
        $this->assertNotSame($article->getId(), $article2->getId());
1613
    }
1614
1615
    /**
1616
     * @depends testDaoGeneration
1617
     */
1618
    public function testRecursiveSave()
1619
    {
1620
        $categoryDao = new CategoryDao($this->tdbmService);
1621
1622
        $root1 = new CategoryBean('Root1');
1623
        $categoryDao->save($root1);
1624
        // Root 2 is not saved yet.
1625
        $root2 = new CategoryBean('Root2');
1626
        $intermediate = new CategoryBean('Intermediate');
1627
        $categoryDao->save($intermediate);
1628
1629
        // Let's switch the parent to a bean in detached state.
1630
        $intermediate->setParent($root2);
1631
1632
        // Now, let's save a new category that references the leaf category.
1633
        $leaf = new CategoryBean('Leaf');
1634
        $leaf->setParent($intermediate);
1635
        $categoryDao->save($leaf);
1636
    }
1637
1638
    /**
1639
     * @depends testDaoGeneration
1640
     */
1641
    public function testBlob()
1642
    {
1643
        $fp = fopen(__FILE__, 'r');
1644
        $file = new FileBean($fp);
1645
1646
        $fileDao = new FileDao($this->tdbmService);
1647
1648
        $fileDao->save($file);
1649
1650
        $loadedFile = $fileDao->getById($file->getId());
1651
1652
        $resource = $loadedFile->getFile();
1653
        $result = fseek($resource, 0);
1654
        $this->assertSame(0, $result);
1655
        $this->assertInternalType('resource', $resource);
1656
        $firstLine = fgets($resource);
1657
        $this->assertSame("<?php\n", $firstLine);
1658
    }
1659
1660
    /**
1661
     * @depends testBlob
1662
     */
1663
    public function testReadBlob()
1664
    {
1665
        $fileDao = new FileDao($this->tdbmService);
1666
        $loadedFile = $fileDao->getById(1);
1667
1668
        $resource = $loadedFile->getFile();
1669
        $this->assertInternalType('resource', $resource);
1670
        $firstLine = fgets($resource);
1671
        $this->assertSame("<?php\n", $firstLine);
1672
    }
1673
1674
    /**
1675
     * @depends testDaoGeneration
1676
     */
1677
    public function testBlobResourceException()
1678
    {
1679
        $this->expectException(TDBMInvalidArgumentException::class);
1680
        $this->expectExceptionMessage('Invalid argument passed to \'TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\Generated\\FileBaseBean::setFile\'. Expecting a resource. Got a string.');
1681
        new FileBean('foobar');
1682
    }
1683
1684
    /**
1685
     * @depends testDaoGeneration
1686
     */
1687
    public function testFilterBag()
1688
    {
1689
        $userDao = new TestUserDao($this->tdbmService);
1690
        $countryDao = new CountryDao($this->tdbmService);
1691
1692
        $country = $countryDao->getById(2);
1693
1694
        // Let's test filter bags by bean and filter bag with many values.
1695
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'Jane Doe']);
1696
1697
        $this->assertCount(1, $users);
1698
        $this->assertSame('John Doe', $users[0]->getName());
1699
    }
1700
}
1701