Passed
Pull Request — master (#71)
by David
03:02
created

TDBMDaoGeneratorTest::testBlobResourceException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
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 testCreationInNullableDate()
1125
    {
1126
        $roleDao = new RoleDao($this->tdbmService);
1127
1128
        $role = new RoleBean('newbee');
1129
        $roleDao->save($role);
1130
1131
        $this->assertNull($role->getCreatedAt());
1132
    }
1133
1134
    /**
1135
     * @depends testDaoGeneration
1136
     */
1137
    public function testUpdateInNullableDate()
1138
    {
1139
        $roleDao = new RoleDao($this->tdbmService);
1140
1141
        $role = new RoleBean('newbee');
1142
        $roleDao->save($role);
1143
1144
        $role->setCreatedAt(null);
1145
        $roleDao->save($role);
1146
        $this->assertNull($role->getCreatedAt());
1147
    }
1148
1149
    /**
1150
     * @depends testDaoGeneration
1151
     */
1152
    public function testFindFromSql()
1153
    {
1154
        $roleDao = new TestRoleDao($this->tdbmService);
1155
1156
        $roles = $roleDao->getRolesByRightCanSing();
1157
        $this->assertCount(2, $roles);
1158
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1159
    }
1160
1161
    /**
1162
     * @depends testDaoGeneration
1163
     */
1164
    public function testFindOneFromSql()
1165
    {
1166
        $roleDao = new TestRoleDao($this->tdbmService);
1167
1168
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1169
        $this->assertInstanceOf(RoleBean::class, $role);
1170
    }
1171
1172
    /**
1173
     * @depends testDaoGeneration
1174
     */
1175
    public function testCreateEmptyExtendedBean()
1176
    {
1177
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1178
1179
        $dogDao = new DogDao($this->tdbmService);
1180
1181
        // We are not filling no field that is part of dog table.
1182
        $dog = new DogBean('Youki');
1183
        $dog->setOrder(1);
1184
1185
        $dogDao->save($dog);
1186
    }
1187
1188
    /**
1189
     * @depends testCreateEmptyExtendedBean
1190
     */
1191
    public function testFetchEmptyExtendedBean()
1192
    {
1193
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1194
1195
        $animalDao = new AnimalDao($this->tdbmService);
1196
1197
        // We are not filling no field that is part of dog table.
1198
        $animalBean = $animalDao->getById(1);
1199
1200
        $this->assertInstanceOf(DogBean::class, $animalBean);
1201
    }
1202
1203
    /**
1204
     * @depends testDaoGeneration
1205
     */
1206
    public function testTwoBranchesHierarchy()
1207
    {
1208
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1209
1210
        $catDao = new CatDao($this->tdbmService);
1211
1212
        // We are not filling no field that is part of dog table.
1213
        $cat = new CatBean('Mew');
1214
        $cat->setOrder(2);
1215
1216
        $catDao->save($cat);
1217
    }
1218
1219
    /**
1220
     * @depends testTwoBranchesHierarchy
1221
     */
1222
    public function testFetchTwoBranchesHierarchy()
1223
    {
1224
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1225
1226
        $animalDao = new AnimalDao($this->tdbmService);
1227
1228
        $animalBean = $animalDao->getById(2);
1229
1230
        $this->assertInstanceOf(CatBean::class, $animalBean);
1231
        /* @var $animalBean CatBean */
1232
        $animalBean->setCutenessLevel(999);
1233
1234
        $animalDao->save($animalBean);
1235
    }
1236
1237
    /**
1238
     * @depends testDaoGeneration
1239
     */
1240
    public function testExceptionOnGetById()
1241
    {
1242
        $countryDao = new CountryDao($this->tdbmService);
1243
        $this->expectException(\TypeError::class);
1244
        $countryDao->getById(null);
1245
    }
1246
1247
    /**
1248
     * @depends testDaoGeneration
1249
     */
1250
    public function testDisconnectedManyToOne()
1251
    {
1252
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1253
1254
        $country = new CountryBean('Spain');
1255
1256
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1257
1258
        $this->assertCount(1, $country->getUsers());
1259
        $this->assertSame($user, $country->getUsers()[0]);
1260
    }
1261
1262
    /**
1263
     * @depends testDaoGeneration
1264
     */
1265
    public function testOrderByExternalCol()
1266
    {
1267
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1268
1269
        $userDao = new TestUserDao($this->tdbmService);
1270
        $users = $userDao->getUsersByCountryName();
1271
1272
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1273
    }
1274
1275
    /**
1276
     * @depends testDaoGeneration
1277
     */
1278
    public function testResultIteratorSort()
1279
    {
1280
        $userDao = new UserDao($this->tdbmService);
1281
        $users = $userDao->findAll()->withOrder('country.label DESC');
1282
1283
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1284
1285
        $users = $users->withOrder('country.label ASC');
1286
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1287
    }
1288
1289
    /**
1290
     * @depends testDaoGeneration
1291
     */
1292
    public function testResultIteratorWithParameters()
1293
    {
1294
        $userDao = new TestUserDao($this->tdbmService);
1295
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1296
        $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

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