Completed
Push — master ( a24d11...86afc5 )
by David
17s
created

TDBMDaoGeneratorTest::testFindOneFromSql()   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
declare(strict_types=1);
3
4
/*
5
 Copyright (C) 2006-2014 David Négrier - THE CODING MACHINE
6
7
This program is free software; you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 2 of the License, or
10
(at your option) any later version.
11
12
This program is distributed in the hope that it will be useful,
13
but WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
GNU General Public License for more details.
16
17
You should have received a copy of the GNU General Public License
18
along with this program; if not, write to the Free Software
19
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
*/
21
22
namespace TheCodingMachine\TDBM;
23
24
use Doctrine\Common\Cache\ArrayCache;
25
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
26
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
27
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
28
use Ramsey\Uuid\Uuid;
29
use TheCodingMachine\TDBM\Dao\TestArticleDao;
30
use TheCodingMachine\TDBM\Dao\TestCountryDao;
31
use TheCodingMachine\TDBM\Dao\TestRoleDao;
32
use TheCodingMachine\TDBM\Dao\TestUserDao;
33
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...
34
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...
35
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...
36
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...
37
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...
38
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...
39
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...
40
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...
41
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...
42
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...
43
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...
44
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\BoatBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...\Generated\BoatBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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