Completed
Push — master ( adc131...6e9eb4 )
by Kevin
03:32
created

DBFakerTest::testFaker()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 9.0472
c 0
b 0
f 0
cc 3
nc 2
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace DBFaker;
3
4
use DBFaker\Generators\BlobGenerator;
5
use DBFaker\Generators\BlobGeneratorFactory;
6
use DBFaker\Generators\Conditions\CallBackCondition;
7
use DBFaker\Generators\Conditions\CheckTypeCondition;
8
use DBFaker\Generators\SimpleGenerator;
9
use DBFaker\Generators\SimpleGeneratorFactory;
10
use DBFaker\Helpers\SchemaHelper;
11
use Doctrine\Common\EventManager;
12
use Doctrine\DBAL\Connection;
13
use Doctrine\DBAL\Driver\PDOMySql\Driver;
14
use Doctrine\DBAL\DriverManager;
15
use Doctrine\DBAL\Types\Type;
16
use PHPUnit\Framework\TestCase;
17
use TheCodingMachine\FluidSchema\DefaultNamingStrategy;
18
use TheCodingMachine\FluidSchema\FluidSchema;
19
20
class DBFakerTest extends TestCase
21
{
22
23
    public static function setUpBeforeClass()
24
    {
25
        $adminConn = self::getAdminConnection();
26
        $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
27
28
        $dbConnection = self::getConnection();
29
        $dbalSchema = $dbConnection->getSchemaManager()->createSchema();
30
        $namingStrategy = new DefaultNamingStrategy();
31
32
        $db = new FluidSchema($dbalSchema, $namingStrategy);
33
        $fromSchema = clone $dbalSchema;
34
35
        $persons = $db->table("persons")
0 ignored issues
show
Unused Code introduced by
The assignment to $persons is dead and can be removed.
Loading history...
36
            ->id()
37
            ->column("email")->string(50)->unique()
38
            ->column("password")->string(100)->then()
39
            ->timestamps();
40
41
        $users = $db->table("users")
42
            ->extends("persons")
43
            ->column("lastname")->string(50)
44
            ->column("firstname")->string(50)
45
            ->column("password")->string(200)
46
            ->column("uuid")->guid()->null()
47
            ->column("parent_id")->references("users")
48
            ->column("birth_date")->date()
49
            ->column("access_level")->smallInt()
50
            ->column("last_access")->datetime();
51
52
53
        $roles = $db->table("roles")
0 ignored issues
show
Unused Code introduced by
The assignment to $roles is dead and can be removed.
Loading history...
54
            ->id()
55
            ->column("label")->string(20);
56
57
        $db->junctionTable("users", "roles");
58
        $usersRolesTableName = $namingStrategy->getJointureTableName("users", "roles");
0 ignored issues
show
Unused Code introduced by
The assignment to $usersRolesTableName is dead and can be removed.
Loading history...
59
60
        $countries = $db->table("countries")
0 ignored issues
show
Unused Code introduced by
The assignment to $countries is dead and can be removed.
Loading history...
61
            ->id()
62
            ->column("name")->string(100)
63
            ->column("population")->bigInt()
64
            ->column("birthrate")->float()
65
            ->column("president_id")->references("persons")
66
            ->column("population_density")->decimal(10,2)
67
            ->column("summary")->text();
68
69
        $users->column("country_id")->references("countries");
70
71
        $regions = $db->table("regions")
0 ignored issues
show
Unused Code introduced by
The assignment to $regions is dead and can be removed.
Loading history...
72
            ->id()
73
            ->column("country_id")->references("countries")
74
            ->column("name")->string("50")
75
            ->column("is_active")->boolean()
76
            ->column("binary")->binary()
77
            ->column("datetimeTz")->datetimeTz()
78
            ->column("time")->time()
79
            ->column("dateImmutable")->dateImmutable()
80
            ->column("datetimeImmutable")->datetimeImmutable()
81
            ->column("datetimeTzImmutable")->datetimeTzImmutable()
82
            ->column("timeImmutable")->timeImmutable()
83
            ->column("dateInterval")->dateInterval()
84
            ->column("blob")->blob()
85
            ->column("array")->array()
86
            ->column("json")->json()
87
            ->column("jsonArray")->jsonArray()
88
            ->column("object")->object();
89
90
        $sqlStmts = $dbalSchema->getMigrateFromSql($fromSchema, $dbConnection->getDatabasePlatform());
91
        foreach ($sqlStmts as $sqlStmt) {
92
            $dbConnection->exec($sqlStmt);
93
        }
94
95
        $dbConnection->insert("roles", ["label" => "ADMIN"]);
96
        $dbConnection->insert("roles", ["label" => "SIMPLE USER"]);
97
98
    }
99
100
    public function testFaker()
101
    {
102
        $conn = self::getConnection();
103
104
        $generatorFinderBuilder = \DBFaker\Generators\GeneratorFinderBuilder::buildDefaultFinderBuilder();
105
106
        /* Don't hesitate to use the Faker package to generate random data,
107
           there is plenty of data types available (IBAN, address, country code, ...).
108
        */
109
//        $dataFaker = \Faker\Factory::create();//you could pass the locale to generate localized data !
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
111
        // address.postal_code column is a varchar, so default generated data will be text. Here we want a postal code :
112
        $generatorFinderBuilder->addGenerator(
113
            new \DBFaker\Generators\Conditions\CallBackCondition(function(\Doctrine\DBAL\Schema\Table $table,  \Doctrine\DBAL\Schema\Column $column){
114
                return $table->getName() == "address" && $column->getName() == "postal_code";
115
            }),
116
            new SimpleGeneratorFactory("postcode")
117
        );
118
119
        // all columns that end with "_email" or are named exactly "email" should be emails
120
        $generatorFinderBuilder->addGenerator(
121
            new CallBackCondition(function(\Doctrine\DBAL\Schema\Table $table,  \Doctrine\DBAL\Schema\Column $column){
122
                return preg_match("/([(.*_)|_|]|^)email$/", $column->getName()) === 1;
123
            }),
124
            new SimpleGeneratorFactory("email")
125
        );
126
127
        $generatorFinderBuilder->addGenerator(
128
            new CheckTypeCondition(Type::getType(Type::BLOB)),
129
            new BlobGeneratorFactory(__DIR__ . "/fixtures/*")
130
        );
131
        $generatorFinderBuilder->addGenerator(
132
            new CheckTypeCondition(Type::getType(Type::BINARY)),
133
            new BlobGeneratorFactory(__DIR__ . "/fixtures/*")
134
        );
135
136
        $faker = new \DBFaker\DBFaker($conn, $generatorFinderBuilder->buildFinder());
137
138
        $tableRowNumbers = [
139
            "users" => 20,
140
            "persons" => 30,
141
            "users_roles" => 30,
142
            "countries" => 10,
143
            "regions" => 3
144
145
        ];
146
        $faker->setFakeTableRowNumbers($tableRowNumbers);
147
        $faker->fakeDB();
148
149
        foreach ($tableRowNumbers as $tableName => $expectedCount){
150
            $count = $conn->fetchColumn('SELECT count(*) from ' . $tableName);
151
            $this->assertEquals($expectedCount, $count);
152
        }
153
    }
154
155
    private static function getAdminConnection()
156
    {
157
        $config = new \Doctrine\DBAL\Configuration();
158
159
        $connectionParams = array(
160
            'user' => $GLOBALS['db_username'],
161
            'password' => $GLOBALS['db_password'],
162
            'host' => $GLOBALS['db_host'],
163
            'port' => $GLOBALS['db_port'],
164
            'driver' => $GLOBALS['db_driver'],
165
        );
166
167
        return DriverManager::getConnection($connectionParams, $config);
168
    }
169
170
    private static function getConnection()
171
    {
172
        $connectionParams = array(
173
            'user' => $GLOBALS['db_username'],
174
            'password' => $GLOBALS['db_password'],
175
            'host' => $GLOBALS['db_host'],
176
            'port' => $GLOBALS['db_port'],
177
            'driver' => $GLOBALS['db_driver'],
178
            'dbname' => $GLOBALS['db_name'],
179
            "charset" => "utf8",
180
            "driverOptions" => array(
181
                1002 =>"SET NAMES utf8"
182
            )
183
        );
184
185
        return new Connection($connectionParams, new Driver(), null, new EventManager());
186
    }
187
188
189
190
}
191