Passed
Push — tests-L5.3 ( f63cac )
by Dimitrios
22:52
created

TestsBase::resetDatabase()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
c 3
b 2
f 0
dl 0
loc 24
rs 8.9713
cc 1
eloc 12
nc 1
nop 0
1
<?php
2
3
use Dimsav\Translatable\Test\Model\Country;
4
use Orchestra\Testbench\TestCase;
5
6
class TestsBase extends TestCase
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
7
{
8
    protected $queriesCount;
9
10
    const DB_NAME = 'translatable_test';
11
    const DB_USERNAME = 'homestead';
12
    const DB_PASSWORD = 'secret';
13
14
    public function setUp()
15
    {
16
        $this->dropDb();
17
        $this->createDb();
18
19
        parent::setUp();
20
21
        $this->resetDatabase();
22
        $this->countQueries();
23
    }
24
25
    private function dropDb()
26
    {
27
        $this->runQuery('DROP DATABASE IF EXISTS '.static::DB_NAME);
28
    }
29
30
    private function createDb()
31
    {
32
        $this->runQuery('CREATE DATABASE '.static::DB_NAME);
33
    }
34
35
    /**
36
     * @param $query
37
     * return void
38
     */
39
    private function runQuery($query)
40
    {
41
        $dbUsername = static::DB_USERNAME;
42
        $dbPassword = static::DB_PASSWORD;
43
44
        $command = "mysql -u $dbUsername ";
45
        $command .= $dbPassword ? " -p$dbPassword" : '';
46
        $command .= " -e '$query'";
47
48
        exec($command.' 2>/dev/null');
49
    }
50
51
    public function testRunningMigration()
52
    {
53
        $country = Country::find(1);
54
        $this->assertEquals('gr', $country->code);
55
    }
56
57
    protected function getPackageProviders($app)
58
    {
59
        return ['Dimsav\Translatable\TranslatableServiceProvider'];
60
    }
61
62
    protected function getEnvironmentSetUp($app)
63
    {
64
        $app['path.base'] = __DIR__.'/..';
65
        $app['config']->set('database.default', 'mysql');
66
        $app['config']->set('database.connections.mysql', [
67
            'driver'   => 'mysql',
68
            'host' => 'localhost',
69
            'database' => static::DB_NAME,
70
            'username' => static::DB_USERNAME,
71
            'password' => static::DB_PASSWORD,
72
            'charset' => 'utf8',
73
            'collation' => 'utf8_unicode_ci',
74
        ]);
75
        $app['config']->set('translatable.locales', ['el', 'en', 'fr', 'de', 'id']);
76
    }
77
78
    protected function getPackageAliases($app)
79
    {
80
        return ['Eloquent' => 'Illuminate\Database\Eloquent\Model'];
81
    }
82
83
    protected function countQueries()
84
    {
85
        $that = $this;
86
        $event = App::make('events');
87
        $event->listen('illuminate.query', function ($query, $bindings) use ($that) {
88
            $that->queriesCount++;
89
            $bindings = $this->formatBindingsForSqlInjection($bindings);
90
            $query = $this->insertBindingsIntoQuery($query, $bindings);
91
            $query = $this->beautifyQuery($query);
0 ignored issues
show
Unused Code introduced by
$query is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
92
            // echo("\n--- Query {$that->queriesCount}--- $query\n");
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
93
        });
94
    }
95
96
    private function beautifyQuery($query)
97
    {
98
        $capitalizeWords = ['select ', ' from ', ' where ', ' on ', ' join '];
99
        $newLineWords = ['select ', 'from ', 'where ', 'join '];
100
        foreach ($capitalizeWords as $word) {
101
            $query = str_replace($word, strtoupper($word), $query);
102
        }
103
104
        foreach ($newLineWords as $word) {
105
            $query = str_replace($word, "\n$word", $query);
106
            $word = strtoupper($word);
107
            $query = str_replace($word, "\n$word", $query);
108
        }
109
110
        return $query;
111
    }
112
113
    private function resetDatabase()
114
    {
115
        // Relative to the testbench app folder: vendors/orchestra/testbench/src/fixture
116
        $migrationsPath = __DIR__.'/migrations';
117
        $artisan = $this->app->make('Illuminate\Contracts\Console\Kernel');
118
119
        // Makes sure the migrations table is created
120
        $artisan->call('migrate', [
121
            '--database' => 'mysql',
122
            '--realpath'     => $migrationsPath,
123
        ]);
124
125
        // We empty all tables
126
        $artisan->call('migrate:reset', [
127
            '--database' => 'mysql',
128
            '--realpath'     => $migrationsPath,
129
        ]);
130
131
        // Migrate
132
        $artisan->call('migrate', [
133
            '--database' => 'mysql',
134
            '--realpath'     => $migrationsPath,
135
        ]);
136
    }
137
138
    /**
139
     * @param $bindings
140
     *
141
     * @return mixed
142
     */
143
    private function formatBindingsForSqlInjection($bindings)
144
    {
145
        foreach ($bindings as $i => $binding) {
146
            if ($binding instanceof DateTime) {
147
                $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
148
            } else {
149
                if (is_string($binding)) {
150
                    $bindings[$i] = "'$binding'";
151
                }
152
            }
153
        }
154
155
        return $bindings;
156
    }
157
158
    /**
159
     * @param $query
160
     * @param $bindings
161
     *
162
     * @return string
163
     */
164
    private function insertBindingsIntoQuery($query, $bindings)
165
    {
166
        if (empty($bindings)) {
167
            return $query;
168
        }
169
170
        $query = str_replace(['%', '?'], ['%%', '%s'], $query);
171
172
        return vsprintf($query, $bindings);
173
    }
174
}
175