Passed
Pull Request — master (#125)
by David
04:07
created

TDBMDaoGeneratorTest::testProtectedGetterSetter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 21
rs 9.8333
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 ReflectionMethod;
30
use TheCodingMachine\TDBM\Dao\TestArticleDao;
31
use TheCodingMachine\TDBM\Dao\TestCountryDao;
32
use TheCodingMachine\TDBM\Dao\TestRoleDao;
33
use TheCodingMachine\TDBM\Dao\TestUserDao;
34
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...
35
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...
36
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...
37
use TheCodingMachine\TDBM\Test\Dao\Bean\AnimalBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Test\Dao\Bean\AnimalBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
38
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...
39
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...
40
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...
41
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...
42
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...
43
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...
44
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...
45
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...
46
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...
47
use TheCodingMachine\TDBM\Test\Dao\Bean\Generated\FileBaseBean;
0 ignored issues
show
Bug introduced by
The type TheCodingMachine\TDBM\Te...\Generated\FileBaseBean was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

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

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

1673
        /** @scrutinizer ignore-deprecated */ $this->assertInternalType('resource', $resource);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
1674
        $firstLine = fgets($resource);
1675
        $this->assertSame("<?php\n", $firstLine);
1676
    }
1677
1678
    /**
1679
     * @depends testBlob
1680
     */
1681
    public function testReadBlob()
1682
    {
1683
        $fileDao = new FileDao($this->tdbmService);
1684
        $loadedFile = $fileDao->getById(1);
1685
1686
        $resource = $loadedFile->getFile();
1687
        $this->assertInternalType('resource', $resource);
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\Assert::assertInternalType() has been deprecated: https://github.com/sebastianbergmann/phpunit/issues/3369 ( Ignorable by Annotation )

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

1687
        /** @scrutinizer ignore-deprecated */ $this->assertInternalType('resource', $resource);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

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