Passed
Pull Request — master (#108)
by Kevin
08:37 queued 05:18
created

TDBMDaoGeneratorTest::testInnerJsonEncode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
50
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...
51
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...
52
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...
53
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...
54
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...
55
use TheCodingMachine\TDBM\Test\Dao\ContractDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\ContractDao 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\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...
57
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...
58
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...
59
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...
60
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...
61
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...
62
use TheCodingMachine\TDBM\Test\Dao\StateDao;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\StateDao was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
942
        $this->assertEquals('bill.shakespeare', $bill->getLogin());
943
    }
944
945
    /**
946
     * @depends testDaoGeneration
947
     */
948
    public function testFirstNull()
949
    {
950
        $userDao = new TestUserDao($this->tdbmService);
951
        $users = $userDao->getUsersByLoginStartingWith('mike');
952
953
        $user = $users->first();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $user is correct as $users->first() targeting TheCodingMachine\TDBM\ResultIterator::first() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
954
        $this->assertNull($user);
955
    }
956
957
    /**
958
     * @depends testDaoGeneration
959
     */
960
    public function testCloneBeanAttachedBean()
961
    {
962
        $userDao = new TestUserDao($this->tdbmService);
963
        $user = $userDao->getUserByLogin('bill.shakespeare');
964
        $this->assertEquals(4, $user->getId());
965
        $user2 = clone $user;
966
        $this->assertNull($user2->getId());
967
        $this->assertEquals('bill.shakespeare', $user2->getLogin());
968
        $this->assertEquals('Bill Shakespeare', $user2->getName());
969
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
970
971
        // MANY 2 MANY must be duplicated
972
        $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
973
974
        // Let's test saving this clone
975
        $user2->setLogin('william.shakespeare');
976
        $userDao->save($user2);
977
978
        $user3 = $userDao->getUserByLogin('william.shakespeare');
979
        $this->assertTrue($user3 === $user2);
980
        $userDao->delete($user3);
981
982
        // Finally, let's test the origin user still exists!
983
        $user4 = $userDao->getUserByLogin('bill.shakespeare');
984
        $this->assertEquals('bill.shakespeare', $user4->getLogin());
985
    }
986
987
    /**
988
     * @depends testDaoGeneration
989
     */
990
    public function testCloneNewBean()
991
    {
992
        $countryDao = new CountryDao($this->tdbmService);
993
        $roleDao = new RoleDao($this->tdbmService);
994
        $role = $roleDao->getById(1);
995
996
        $userBean = new UserBean('John Doe', '[email protected]', $countryDao->getById(2), 'john.doe');
997
        $userBean->addRole($role);
998
999
        $user2 = clone $userBean;
1000
1001
        $this->assertNull($user2->getId());
1002
        $this->assertEquals('john.doe', $user2->getLogin());
1003
        $this->assertEquals('John Doe', $user2->getName());
1004
        $this->assertEquals('UK', $user2->getCountry()->getLabel());
1005
1006
        // MANY 2 MANY must be duplicated
1007
        $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
1008
    }
1009
1010
    /**
1011
     * @depends testDaoGeneration
1012
     */
1013
    public function testCascadeDelete()
1014
    {
1015
        $userDao = new TestUserDao($this->tdbmService);
1016
        $countryDao = new CountryDao($this->tdbmService);
1017
1018
        $spain = new CountryBean('Spain');
1019
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $spain, 'manuel.sanchez');
1020
1021
        $countryDao->save($spain);
1022
        $userDao->save($sanchez);
1023
1024
        $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
1025
        $this->assertTrue($sanchez === $speedy2);
1026
1027
        $exceptionTriggered = false;
1028
        try {
1029
            $countryDao->delete($spain);
1030
        } catch (ForeignKeyConstraintViolationException $e) {
1031
            $exceptionTriggered = true;
1032
        }
1033
        $this->assertTrue($exceptionTriggered);
1034
1035
        $countryDao->delete($spain, true);
1036
1037
        // Let's check that speed gonzalez was removed.
1038
        $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
1039
        $this->assertNull($speedy3);
1040
    }
1041
1042
    /**
1043
     * @depends testDaoGeneration
1044
     */
1045
    public function testDiscardChanges()
1046
    {
1047
        $contactDao = new ContactDao($this->tdbmService);
1048
        $contactBean = $contactDao->getById(1);
1049
1050
        $oldName = $contactBean->getName();
1051
1052
        $contactBean->setName('MyNewName');
1053
1054
        $contactBean->discardChanges();
1055
1056
        $this->assertEquals($oldName, $contactBean->getName());
1057
    }
1058
1059
    /**
1060
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1061
     * @depends testDaoGeneration
1062
     */
1063
    public function testDiscardChangesOnNewBeanFails()
1064
    {
1065
        $person = new PersonBean('John Foo', new \DateTimeImmutable());
1066
        $person->discardChanges();
1067
    }
1068
1069
    /**
1070
     * @expectedException \TheCodingMachine\TDBM\TDBMException
1071
     * @depends testDaoGeneration
1072
     */
1073
    public function testDiscardChangesOnDeletedBeanFails()
1074
    {
1075
        $userDao = new TestUserDao($this->tdbmService);
1076
        $countryDao = new CountryDao($this->tdbmService);
1077
1078
        $sanchez = new UserBean('Manuel Sanchez', '[email protected]', $countryDao->getById(1), 'manuel.sanchez');
1079
1080
        $userDao->save($sanchez);
1081
1082
        $userDao->delete($sanchez);
1083
1084
        // Cannot discard changes on a bean that is already deleted.
1085
        $sanchez->discardChanges();
1086
    }
1087
1088
    /**
1089
     * @depends testDaoGeneration
1090
     */
1091
    public function testUniqueIndexBasedSearch()
1092
    {
1093
        $userDao = new UserDao($this->tdbmService);
1094
        $user = $userDao->findOneByLogin('bill.shakespeare');
1095
1096
        $this->assertEquals('bill.shakespeare', $user->getLogin());
1097
        $this->assertEquals('Bill Shakespeare', $user->getName());
1098
    }
1099
1100
    /**
1101
     * @depends testDaoGeneration
1102
     */
1103
    public function testFindOneByRetunsNull()
1104
    {
1105
        // Let's assert that the findOneBy... methods can return null.
1106
        $userDao = new UserDao($this->tdbmService);
1107
        $userBean = $userDao->findOneByLogin('not_exist');
1108
1109
        $this->assertNull($userBean);
1110
    }
1111
1112
    /**
1113
     * @depends testDaoGeneration
1114
     */
1115
    public function testMultiColumnsIndexBasedSearch()
1116
    {
1117
        $countryDao = new CountryDao($this->tdbmService);
1118
        $userDao = new UserDao($this->tdbmService);
1119
        $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
1120
1121
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1122
    }
1123
1124
    /**
1125
     * @depends testDaoGeneration
1126
     */
1127
    public function testPartialMultiColumnsIndexBasedSearch()
1128
    {
1129
        $userDao = new UserDao($this->tdbmService);
1130
        $users = $userDao->findByStatusAndCountry('on');
1131
1132
        $this->assertCount(2, $users);
1133
    }
1134
1135
    /**
1136
     * @depends testDaoGeneration
1137
     */
1138
    public function testCreationInNullableDate()
1139
    {
1140
        $roleDao = new RoleDao($this->tdbmService);
1141
1142
        $role = new RoleBean('newbee');
1143
        $roleDao->save($role);
1144
1145
        $this->assertNull($role->getCreatedAt());
1146
    }
1147
1148
    /**
1149
     * @depends testDaoGeneration
1150
     */
1151
    public function testUpdateInNullableDate()
1152
    {
1153
        $roleDao = new RoleDao($this->tdbmService);
1154
1155
        $role = new RoleBean('newbee');
1156
        $roleDao->save($role);
1157
1158
        $role->setCreatedAt(null);
1159
        $roleDao->save($role);
1160
        $this->assertNull($role->getCreatedAt());
1161
    }
1162
1163
    /**
1164
     * @depends testDaoGeneration
1165
     */
1166
    public function testFindFromSql()
1167
    {
1168
        $roleDao = new TestRoleDao($this->tdbmService);
1169
1170
        $roles = $roleDao->getRolesByRightCanSing();
1171
        $this->assertCount(2, $roles);
1172
        $this->assertInstanceOf(RoleBean::class, $roles[0]);
1173
    }
1174
1175
    /**
1176
     * @depends testDaoGeneration
1177
     */
1178
    public function testFindOneFromSql()
1179
    {
1180
        $roleDao = new TestRoleDao($this->tdbmService);
1181
1182
        $role = $roleDao->getRoleByRightCanSingAndNameSinger();
1183
        $this->assertInstanceOf(RoleBean::class, $role);
1184
    }
1185
1186
    /**
1187
     * @depends testDaoGeneration
1188
     */
1189
    public function testCreateEmptyExtendedBean()
1190
    {
1191
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1192
1193
        $dogDao = new DogDao($this->tdbmService);
1194
1195
        // We are not filling no field that is part of dog table.
1196
        $dog = new DogBean('Youki');
1197
        $dog->setOrder(1);
1198
1199
        $dogDao->save($dog);
1200
    }
1201
1202
    /**
1203
     * @depends testCreateEmptyExtendedBean
1204
     */
1205
    public function testFetchEmptyExtendedBean()
1206
    {
1207
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
1208
1209
        $animalDao = new AnimalDao($this->tdbmService);
1210
1211
        // We are not filling no field that is part of dog table.
1212
        $animalBean = $animalDao->getById(1);
1213
1214
        $this->assertInstanceOf(DogBean::class, $animalBean);
1215
    }
1216
1217
    /**
1218
     * @depends testDaoGeneration
1219
     */
1220
    public function testTwoBranchesHierarchy()
1221
    {
1222
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1223
1224
        $catDao = new CatDao($this->tdbmService);
1225
1226
        // We are not filling no field that is part of dog table.
1227
        $cat = new CatBean('Mew');
1228
        $cat->setOrder(2);
1229
1230
        $catDao->save($cat);
1231
    }
1232
1233
    /**
1234
     * @depends testTwoBranchesHierarchy
1235
     */
1236
    public function testFetchTwoBranchesHierarchy()
1237
    {
1238
        // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
1239
1240
        $animalDao = new AnimalDao($this->tdbmService);
1241
1242
        $animalBean = $animalDao->getById(2);
1243
1244
        $this->assertInstanceOf(CatBean::class, $animalBean);
1245
        /* @var $animalBean CatBean */
1246
        $animalBean->setCutenessLevel(999);
1247
        $animalBean->setUppercaseColumn('foobar');
1248
1249
        $animalDao->save($animalBean);
1250
    }
1251
1252
    /**
1253
     * @depends testDaoGeneration
1254
     */
1255
    public function testExceptionOnGetById()
1256
    {
1257
        $countryDao = new CountryDao($this->tdbmService);
1258
        $this->expectException(\TypeError::class);
1259
        $countryDao->getById(null);
1260
    }
1261
1262
    /**
1263
     * @depends testDaoGeneration
1264
     */
1265
    public function testDisconnectedManyToOne()
1266
    {
1267
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
1268
1269
        $country = new CountryBean('Spain');
1270
1271
        $user = new UserBean('John Doe', '[email protected]', $country, 'john.doe');
1272
1273
        $this->assertCount(1, $country->getUsers());
1274
        $this->assertSame($user, $country->getUsers()[0]);
1275
    }
1276
1277
    /**
1278
     * @depends testDaoGeneration
1279
     */
1280
    public function testOrderByExternalCol()
1281
    {
1282
        // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
1283
1284
        $userDao = new TestUserDao($this->tdbmService);
1285
        $users = $userDao->getUsersByCountryName();
1286
1287
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1288
    }
1289
1290
    /**
1291
     * @depends testDaoGeneration
1292
     */
1293
    public function testResultIteratorSort()
1294
    {
1295
        $userDao = new UserDao($this->tdbmService);
1296
        $users = $userDao->findAll()->withOrder('country.label DESC');
1297
1298
        $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
1299
1300
        $users = $users->withOrder('country.label ASC');
1301
        $this->assertEquals('France', $users[0]->getCountry()->getLabel());
1302
    }
1303
1304
    /**
1305
     * @depends testDaoGeneration
1306
     */
1307
    public function testResultIteratorWithParameters()
1308
    {
1309
        $userDao = new TestUserDao($this->tdbmService);
1310
        $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
1311
        $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
1312
1313
        $users = $users->withParameters(['login' => 'jean%']);
1314
        $this->assertEquals('jean.dupont', $users[0]->getLogin());
1315
    }
1316
1317
    /**
1318
     * @depends testDaoGeneration
1319
     */
1320
    public function testOrderByExpression()
1321
    {
1322
        $userDao = new TestUserDao($this->tdbmService);
1323
        $users = $userDao->getUsersByReversedCountryName();
1324
1325
        $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
1326
    }
1327
1328
    /**
1329
     * @depends testDaoGeneration
1330
     */
1331
    public function testOrderByException()
1332
    {
1333
        $userDao = new TestUserDao($this->tdbmService);
1334
        $users = $userDao->getUsersByInvalidOrderBy();
1335
        $this->expectException(TDBMInvalidArgumentException::class);
1336
        $user = $users[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
1337
    }
1338
1339
    /**
1340
     * @depends testDaoGeneration
1341
     */
1342
    public function testOrderByProtectedColumn()
1343
    {
1344
        $animalDao = new AnimalDao($this->tdbmService);
1345
        $animals = $animalDao->findAll();
1346
        $animals = $animals->withOrder('`order` ASC');
1347
1348
        $this->assertInstanceOf(DogBean::class, $animals[0]);
1349
        $this->assertInstanceOf(CatBean::class, $animals[1]);
1350
1351
        $animals = $animals->withOrder('`order` DESC');
1352
1353
        $this->assertInstanceOf(CatBean::class, $animals[0]);
1354
        $this->assertInstanceOf(DogBean::class, $animals[1]);
1355
    }
1356
1357
    /**
1358
     * @depends testDaoGeneration
1359
     */
1360
    public function testGetOnAllNullableValues()
1361
    {
1362
        // Tests that a get performed on a column that has only nullable fields succeeds.
1363
        $allNullable = new AllNullableBean();
1364
        $this->assertNull($allNullable->getId());
1365
        $this->assertNull($allNullable->getLabel());
1366
        $this->assertNull($allNullable->getCountry());
1367
    }
1368
1369
    /**
1370
     * @depends testDaoGeneration
1371
     */
1372
    public function testExceptionOnMultipleInheritance()
1373
    {
1374
        $connection = self::getConnection();
1375
        self::insert($connection, 'animal', [
1376
            'id' => 99, 'name' => 'Snoofield',
1377
        ]);
1378
        self::insert($connection, 'dog', [
1379
            'id' => 99, 'race' => 'dog',
1380
        ]);
1381
        self::insert($connection, 'cat', [
1382
            'id' => 99, 'cuteness_level' => 0,
1383
        ]);
1384
1385
        $catched = false;
1386
        try {
1387
            $animalDao = new AnimalDao($this->tdbmService);
1388
            $animalDao->getById(99);
1389
        } catch (TDBMInheritanceException $e) {
1390
            $catched = true;
1391
        }
1392
        $this->assertTrue($catched, 'Exception TDBMInheritanceException was not caught');
1393
1394
        self::delete($connection, 'cat', ['id' => 99]);
1395
        self::delete($connection, 'dog', ['id' => 99]);
1396
        self::delete($connection, 'animal', ['id' => 99]);
1397
    }
1398
1399
    /**
1400
     * @depends testDaoGeneration
1401
     */
1402
    public function testReferenceNotSaved()
1403
    {
1404
        $boatDao = new BoatDao($this->tdbmService);
1405
1406
        $country = new CountryBean('Atlantis');
1407
        $boat = new BoatBean($country, 'Titanic');
1408
1409
        $boatDao->save($boat);
1410
    }
1411
1412
    /**
1413
     * @depends testReferenceNotSaved
1414
     */
1415
    public function testUniqueIndexOnForeignKeyThenScalar()
1416
    {
1417
        $boatDao = new BoatDao($this->tdbmService);
1418
        $countryDao = new CountryDao($this->tdbmService);
1419
1420
        $countryBean = $countryDao->findOneByLabel('Atlantis');
1421
        $boatBean = $boatDao->findOneByAnchorageCountryAndName($countryBean, 'Titanic');
1422
1423
        $this->assertNotNull($boatBean);
1424
    }
1425
1426
    /**
1427
     * @depends testDaoGeneration
1428
     */
1429
    public function testReferenceDeleted()
1430
    {
1431
        $countryDao = new CountryDao($this->tdbmService);
1432
        $boatDao = new BoatDao($this->tdbmService);
1433
1434
        $country = new CountryBean('Bikini Bottom');
1435
        $countryDao->save($country);
1436
1437
        $boat = new BoatBean($country, 'Squirrel boat');
1438
        $countryDao->delete($country);
1439
1440
        $this->expectException(TDBMMissingReferenceException::class);
1441
        $boatDao->save($boat);
1442
    }
1443
1444
    /**
1445
     * @depends testDaoGeneration
1446
     */
1447
    public function testCyclicReferenceWithInheritance()
1448
    {
1449
        $userDao = new UserDao($this->tdbmService);
1450
1451
        $country = new CountryBean('Norrisland');
1452
        $user = new UserBean('Chuck Norris', '[email protected]', $country, 'chuck.norris');
1453
1454
        $user->setManager($user);
1455
1456
        $this->expectException(TDBMCyclicReferenceException::class);
1457
        $userDao->save($user);
1458
    }
1459
1460
    /**
1461
     * @depends testDaoGeneration
1462
     */
1463
    public function testCyclicReference()
1464
    {
1465
        $categoryDao = new CategoryDao($this->tdbmService);
1466
1467
        $category = new CategoryBean('Root');
1468
1469
        $category->setParent($category);
1470
1471
        $this->expectException(TDBMCyclicReferenceException::class);
1472
        $categoryDao->save($category);
1473
    }
1474
1475
    /**
1476
     * @depends testDaoGeneration
1477
     */
1478
    public function testCorrectTypeForPrimaryKeyAfterSave()
1479
    {
1480
        // PosqtgreSQL does not particularly like empty inserts (i.e.: "INSERT INTO all_nullable () VALUES ()" )
1481
        $this->onlyMySql();
1482
1483
        $allNullableDao = new AllNullableDao($this->tdbmService);
1484
        $allNullable = new AllNullableBean();
1485
        $allNullableDao->save($allNullable);
1486
        $id = $allNullable->getId();
1487
1488
        $this->assertTrue(is_int($id));
1489
    }
1490
1491
    /**
1492
     * @depends testDaoGeneration
1493
     */
1494
    public function testPSR2Compliance()
1495
    {
1496
        $process = new Process('vendor/bin/php-cs-fixer fix src/Test/  --dry-run --diff --rules=@PSR2');
1497
        $process->run();
1498
1499
        // executes after the command finishes
1500
        if (!$process->isSuccessful()) {
1501
            echo $process->getOutput();
1502
            $this->fail('Generated code is not PSR-2 compliant');
1503
        }
1504
    }
1505
1506
    /**
1507
     * @depends testDaoGeneration
1508
     */
1509
    public function testFindOneByGeneration()
1510
    {
1511
        $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
1512
        $parameters = $reflectionMethod->getParameters();
1513
1514
        $this->assertCount(2, $parameters);
1515
        $this->assertSame('login', $parameters[0]->getName());
1516
        $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
1517
    }
1518
1519
    /**
1520
     * @depends testDaoGeneration
1521
     */
1522
    public function testUuid()
1523
    {
1524
        $article = new ArticleBean('content');
1525
        $this->assertSame('content', $article->getContent());
1526
        $this->assertNotEmpty($article->getId());
1527
        $uuid = Uuid::fromString($article->getId());
1528
        $this->assertSame(1, $uuid->getVersion());
1529
    }
1530
1531
    /**
1532
     * @depends testDaoGeneration
1533
     */
1534
    public function testUuidv4()
1535
    {
1536
        $article = new Article2Bean('content');
1537
        $this->assertSame('content', $article->getContent());
1538
        $this->assertNotEmpty($article->getId());
1539
        $uuid = Uuid::fromString($article->getId());
1540
        $this->assertSame(4, $uuid->getVersion());
1541
    }
1542
1543
    /**
1544
     * @depends testDaoGeneration
1545
     */
1546
    public function testTypeHintedConstructors()
1547
    {
1548
        $userBaseBeanReflectionConstructor = new \ReflectionMethod(UserBaseBean::class, '__construct');
1549
        $nameParam = $userBaseBeanReflectionConstructor->getParameters()[0];
1550
1551
        $this->assertSame('string', (string)$nameParam->getType());
1552
    }
1553
1554
    /**
1555
     * @depends testDaoGeneration
1556
     */
1557
    public function testSaveTransaction()
1558
    {
1559
        $countryDao = new CountryDao($this->tdbmService);
1560
1561
        $boatDao = new BoatDao($this->tdbmService);
1562
        $boatBean = $boatDao->getById(1);
1563
        $boatBean->setName('Bismark');
1564
1565
        $boatBean->getCountry();
1566
1567
        // Let's insert a row without telling TDBM to trigger an error!
1568
        self::insert($this->getConnection(), 'sailed_countries', [
1569
            'boat_id' => 1,
1570
            'country_id' => 2
1571
        ]);
1572
1573
        $boatBean->addCountry($countryDao->getById(2));
1574
1575
        $this->expectException(UniqueConstraintViolationException::class);
1576
1577
        $boatDao->save($boatBean);
1578
    }
1579
1580
    /**
1581
     * @depends testSaveTransaction
1582
     */
1583
    public function testSaveTransaction2()
1584
    {
1585
        $boatDao = new BoatDao($this->tdbmService);
1586
        $boatBean = $boatDao->getById(1);
1587
1588
        // The name should not have been saved because the transaction of the previous test should have rollbacked.
1589
        $this->assertNotSame('Bismark', $boatBean->getName());
1590
    }
1591
1592
    /**
1593
     * @depends testDaoGeneration
1594
     */
1595
    public function testForeignKeyPointingToNonPrimaryKey()
1596
    {
1597
        $dao = new RefNoPrimKeyDao($this->tdbmService);
1598
        $bean = $dao->getById(1);
1599
1600
        $this->assertSame('foo', $bean->getFrom()->getTo());
1601
1602
        $newBean = new RefNoPrimKeyBean($bean, 'baz');
1603
        $dao->save($newBean);
1604
        $this->assertSame('foo', $newBean->getFrom()->getTo());
1605
1606
        $resultSet = $bean->getRefNoPrimKey();
1607
        $this->assertCount(2, $resultSet);
1608
    }
1609
1610
    /**
1611
     * @depends testDaoGeneration
1612
     */
1613
    public function testCloningUuidBean()
1614
    {
1615
        $article = new ArticleBean('content');
1616
        $this->assertNotEmpty($article->getId());
1617
        $article2 = clone $article;
1618
        $this->assertNotEmpty($article2->getId());
1619
        $this->assertNotSame($article->getId(), $article2->getId());
1620
    }
1621
1622
    /**
1623
     * @depends testDaoGeneration
1624
     */
1625
    public function testRecursiveSave()
1626
    {
1627
        $categoryDao = new CategoryDao($this->tdbmService);
1628
1629
        $root1 = new CategoryBean('Root1');
1630
        $categoryDao->save($root1);
1631
        // Root 2 is not saved yet.
1632
        $root2 = new CategoryBean('Root2');
1633
        $intermediate = new CategoryBean('Intermediate');
1634
        $categoryDao->save($intermediate);
1635
1636
        // Let's switch the parent to a bean in detached state.
1637
        $intermediate->setParent($root2);
1638
1639
        // Now, let's save a new category that references the leaf category.
1640
        $leaf = new CategoryBean('Leaf');
1641
        $leaf->setParent($intermediate);
1642
        $categoryDao->save($leaf);
1643
    }
1644
1645
    /**
1646
     * @depends testDaoGeneration
1647
     */
1648
    public function testBlob()
1649
    {
1650
        $fp = fopen(__FILE__, 'r');
1651
        $file = new FileBean($fp);
1652
1653
        $fileDao = new FileDao($this->tdbmService);
1654
1655
        $fileDao->save($file);
1656
1657
        $loadedFile = $fileDao->getById($file->getId());
1658
1659
        $resource = $loadedFile->getFile();
1660
        $result = fseek($resource, 0);
1661
        $this->assertSame(0, $result);
1662
        $this->assertInternalType('resource', $resource);
1663
        $firstLine = fgets($resource);
1664
        $this->assertSame("<?php\n", $firstLine);
1665
    }
1666
1667
    /**
1668
     * @depends testBlob
1669
     */
1670
    public function testReadBlob()
1671
    {
1672
        $fileDao = new FileDao($this->tdbmService);
1673
        $loadedFile = $fileDao->getById(1);
1674
1675
        $resource = $loadedFile->getFile();
1676
        $this->assertInternalType('resource', $resource);
1677
        $firstLine = fgets($resource);
1678
        $this->assertSame("<?php\n", $firstLine);
1679
1680
        stream_get_contents($resource);
1681
1682
        $loadedFile->setId($loadedFile->getId());
1683
1684
        $fileDao->save($loadedFile);
1685
    }
1686
1687
    /**
1688
     * @depends testReadBlob
1689
     */
1690
    public function testReadAndSaveBlob()
1691
    {
1692
        $fileDao = new FileDao($this->tdbmService);
1693
        $loadedFile = $fileDao->getById(1);
1694
1695
        $resource = $loadedFile->getFile();
1696
1697
        $firstLine = fgets($resource);
1698
        $this->assertSame("<?php\n", $firstLine);
1699
    }
1700
1701
    /**
1702
     * @depends testDaoGeneration
1703
     */
1704
    public function testBlobResourceException()
1705
    {
1706
        $this->expectException(TDBMInvalidArgumentException::class);
1707
        $this->expectExceptionMessage('Invalid argument passed to \'TheCodingMachine\\TDBM\\Test\\Dao\\Bean\\Generated\\FileBaseBean::setFile\'. Expecting a resource. Got a string.');
1708
        new FileBean('foobar');
1709
    }
1710
1711
    /**
1712
     * @depends testDaoGeneration
1713
     */
1714
    public function testFilterBag()
1715
    {
1716
        $userDao = new TestUserDao($this->tdbmService);
1717
        $countryDao = new CountryDao($this->tdbmService);
1718
1719
        $country = $countryDao->getById(2);
1720
1721
        // Let's test filter bags by bean and filter bag with many values.
1722
        $users = $userDao->getUsersByComplexFilterBag($country, ['John Doe', 'Jane Doe']);
1723
1724
        $this->assertCount(1, $users);
1725
        $this->assertSame('John Doe', $users[0]->getName());
1726
    }
1727
1728
    /**
1729
     * @depends testDaoGeneration
1730
     */
1731
    public function testDecimalIsMappedToString()
1732
    {
1733
        $reflectionClass = new \ReflectionClass(BoatBaseBean::class);
1734
        $this->assertSame('string', (string) $reflectionClass->getMethod('getLength')->getReturnType());
1735
    }
1736
1737
    /**
1738
     * @depends testDaoGeneration
1739
     */
1740
    public function testNoGetByIdOnMultiPrimaryKeys()
1741
    {
1742
        $reflectionClass = new \ReflectionClass(StateDao::class);
1743
        $this->assertFalse($reflectionClass->hasMethod('getById'));
1744
    }
1745
1746
    /**
1747
     * @depends testDaoGeneration
1748
     */
1749
    public function testInsertMultiPrimaryKeysBean()
1750
    {
1751
        $countryDao = new CountryDao($this->tdbmService);
1752
1753
        $country = $countryDao->getById(1);
1754
1755
        $stateDao = new StateDao($this->tdbmService);
1756
        $state = new StateBean($country, 'IDF', 'Ile de France');
1757
        $stateDao->save($state);
1758
1759
        $this->assertSame($state, $stateDao->findAll()[0]);
1760
    }
1761
1762
    /**
1763
     * @depends testInsertMultiPrimaryKeysBean
1764
     */
1765
    public function testDeleteMultiPrimaryKeysBean()
1766
    {
1767
        $stateDao = new StateDao($this->tdbmService);
1768
1769
        $state = $stateDao->findAll()[0];
1770
        $stateDao->delete($state);
1771
        $this->assertCount(0, $stateDao->findAll());
1772
1773
    }
1774
1775
    public function testGetContractOnMultipleUniqueIndexWithNullValue(){
1776
        $contractDao = new ContractDao($this->tdbmService);
1777
        $contract = (new ContactDao($this->tdbmService))->getById(1);
1778
        $contract = $contractDao->findOneByContactAndCountry($contract, null);
1779
        var_dump($contract);exit;
0 ignored issues
show
Security Debugging Code introduced by
var_dump($contract) looks like debug code. Are you sure you do not want to remove it?
Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1780
        $this->assertCount(1, $contract);
0 ignored issues
show
Unused Code introduced by
$this->assertCount(1, $contract) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1781
    }
1782
}
1783