Completed
Push — master ( 7f9e22...63c78c )
by David
46s queued 29s
created

ManyToOneBench::initDatabase()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 15
rs 8.4444
cc 8
nc 1
nop 0
1
<?php
2
3
4
namespace TheCodingMachine\TDBM\Performance;
5
6
use Doctrine\Common\Cache\ArrayCache;
7
use Doctrine\DBAL\Connection;
8
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
9
use PhpBench\Benchmark\Metadata\Annotations\Iterations;
10
use TheCodingMachine\FluidSchema\TdbmFluidSchema;
11
use TheCodingMachine\TDBM\Configuration;
12
use TheCodingMachine\TDBM\ConfigurationInterface;
13
use TheCodingMachine\TDBM\ConnectionFactory;
14
use TheCodingMachine\TDBM\DummyGeneratorListener;
15
use TheCodingMachine\TDBM\TDBMAbstractServiceTest;
16
use TheCodingMachine\TDBM\TDBMSchemaAnalyzer;
17
use TheCodingMachine\TDBM\TDBMService;
18
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...
19
use TheCodingMachine\TDBM\Utils\PathFinder\PathFinder;
20
use TheCodingMachine\TDBM\Utils\TDBMDaoGenerator;
21
use function dirname;
22
use function getenv;
23
use function glob;
24
use function is_dir;
25
use function is_file;
26
use function rmdir;
27
use function rtrim;
28
use function unlink;
29
30
/**
31
 * @BeforeClassMethods({"initDatabase"})
32
 */
33
class ManyToOneBench
34
{
35
    public static function initDatabase(): void
36
    {
37
        $dbConnection = ConnectionFactory::resetDatabase(
38
            getenv('DB_DRIVER') ?: null,
0 ignored issues
show
Bug introduced by
It seems like getenv('DB_DRIVER') ?: null can also be of type null; however, parameter $dbDriver of TheCodingMachine\TDBM\Co...actory::resetDatabase() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

38
            /** @scrutinizer ignore-type */ getenv('DB_DRIVER') ?: null,
Loading history...
39
            getenv('DB_HOST') ?: null,
40
            getenv('DB_PORT') ?: null,
41
            getenv('DB_USERNAME') ?: null,
42
            getenv('DB_ADMIN_USERNAME') ?: null,
43
            getenv('DB_PASSWORD') ?: null,
44
            getenv('DB_NAME') ?: null
45
        );
46
47
        self::initSchema($dbConnection);
48
49
        self::generateDaosAndBeans($dbConnection);
50
    }
51
52
    private static function initSchema(Connection $connection): void
53
    {
54
        $fromSchema = $connection->getSchemaManager()->createSchema();
55
        $toSchema = clone $fromSchema;
56
57
        $db = new TdbmFluidSchema($toSchema, new \TheCodingMachine\FluidSchema\DefaultNamingStrategy($connection->getDatabasePlatform()));
58
59
        $db->table('countries')
60
            ->column('id')->integer()->primaryKey()
61
            ->column('label')->string(255)->unique();
62
63
        $db->table('users')
64
            ->column('id')->integer()->primaryKey()
65
            ->column('name')->string(255)
66
            ->column('country_id')->references('countries');
67
68
        $sqlStmts = $toSchema->getMigrateFromSql($fromSchema, $connection->getDatabasePlatform());
69
70
        foreach ($sqlStmts as $sqlStmt) {
71
            $connection->exec($sqlStmt);
72
        }
73
74
        for ($i = 1; $i<200; $i++) {
75
            TDBMAbstractServiceTest::insert($connection, 'countries', [
76
                'id' => $i,
77
                'label' => 'Country '.$i,
78
            ]);
79
        }
80
81
        for ($i = 1; $i<1000; $i++) {
82
            TDBMAbstractServiceTest::insert($connection, 'users', [
83
                'id' => $i,
84
                'name' => 'User '.$i,
85
                'country_id' => ($i%199) +1,
86
            ]);
87
        }
88
    }
89
90
    private static function generateDaosAndBeans(Connection $connection): void
91
    {
92
        $schemaManager = $connection->getSchemaManager();
93
        $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
94
        $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, new ArrayCache(), $schemaAnalyzer);
95
        $tdbmDaoGenerator = new TDBMDaoGenerator(self::createConfiguration(), $tdbmSchemaAnalyzer);
96
        $rootPath = __DIR__ . '/../';
0 ignored issues
show
Unused Code introduced by
The assignment to $rootPath is dead and can be removed.
Loading history...
97
        self::recursiveDelete(__DIR__. '/../../src/Test/Dao/');
98
99
        $tdbmDaoGenerator->generateAllDaosAndBeans();
100
    }
101
102
    /**
103
     * Delete a file or recursively delete a directory.
104
     *
105
     * @param string $str Path to file or directory
106
     * @return bool
107
     */
108
    private static function recursiveDelete(string $str): bool
109
    {
110
        if (is_file($str)) {
111
            return @unlink($str);
112
        } elseif (is_dir($str)) {
113
            $scan = glob(rtrim($str, '/') . '/*');
114
            foreach ($scan as $index => $path) {
115
                self::recursiveDelete($path);
116
            }
117
118
            return @rmdir($str);
119
        }
120
        return false;
121
    }
122
123
    private function getConnection(): Connection
124
    {
125
        return ConnectionFactory::createConnection(
126
            getenv('DB_DRIVER') ?: null,
0 ignored issues
show
Bug introduced by
It seems like getenv('DB_DRIVER') ?: null can also be of type null; however, parameter $dbDriver of TheCodingMachine\TDBM\Co...ory::createConnection() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

126
            /** @scrutinizer ignore-type */ getenv('DB_DRIVER') ?: null,
Loading history...
127
            getenv('DB_HOST') ?: null,
128
            getenv('DB_PORT') ?: null,
129
            getenv('DB_USERNAME') ?: null,
130
            getenv('DB_PASSWORD') ?: null,
131
            getenv('DB_NAME') ?: null
132
        );
133
    }
134
135
    protected function getTdbmService(): TDBMService
136
    {
137
        return new TDBMService($this->getConfiguration());
138
    }
139
140
    private static $cache;
141
142
    protected static function getCache(): ArrayCache
143
    {
144
        if (self::$cache === null) {
145
            self::$cache = new ArrayCache();
146
        }
147
        return self::$cache;
148
    }
149
150
    private static function createConfiguration(): ConfigurationInterface
151
    {
152
        $configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), null, self::getCache(), null, null, []);
0 ignored issues
show
Bug Best Practice introduced by
The method TheCodingMachine\TDBM\Pe...eBench::getConnection() is not static, but was called statically. ( Ignorable by Annotation )

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

152
        $configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::/** @scrutinizer ignore-call */ getConnection(), null, self::getCache(), null, null, []);
Loading history...
153
        $configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 5)));
154
        return $configuration;
155
    }
156
157
    /**
158
     * @var ConfigurationInterface
159
     */
160
    private $configuration;
161
162
    protected function getConfiguration() : ConfigurationInterface
163
    {
164
        if ($this->configuration === null) {
165
            return self::createConfiguration();
166
        }
167
        return $this->configuration;
168
    }
169
170
    /**
171
     * @Iterations(10)
172
     */
173
    public function benchManyToOne(): void
174
    {
175
        $tdbmService = $this->getTdbmService();
176
        $userDao = new UserDao($tdbmService);
177
        foreach ($userDao->findAll() as $user) {
178
            $label = $user->getCountry()->getLabel();
0 ignored issues
show
Unused Code introduced by
The assignment to $label is dead and can be removed.
Loading history...
179
        }
180
    }
181
}
182