Test Setup Failed
Pull Request — master (#366)
by
unknown
64:34
created

TestsBase::testRunningMigration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
use Orchestra\Testbench\TestCase;
4
use Dimsav\Translatable\Test\Model\Country;
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...
Bug introduced by
There is at least one abstract method in this class. Maybe declare it as abstract, or implement the remaining methods: artisan, be, call, seed
Loading history...
7
{
8
    protected $queriesCount;
9
    protected static $db2Setup = false;
10
11
    const DB_NAME = 'translatable_test';
12
    const DB_NAME2 = 'translatable_test2';
13
    const DB_USERNAME = 'homestead';
14
    const DB_PASSWORD = 'secret';
15
16
    public function setUp()
17
    {
18
        $this->makeSureDatabaseExists(static::DB_NAME);
19
20
        if (! static::$db2Setup) {
21
            $this->makeSureDatabaseExists(static::DB_NAME2);
22
        }
23
24
        parent::setUp();
25
26
        if (! static::$db2Setup) {
27
            $this->makeSureSchemaIsCreated('mysql2');
28
            $this->truncateAllTablesButMigrations(static::DB_NAME2);
29
            static::$db2Setup = true;
30
        }
31
32
        $this->makeSureSchemaIsCreated('mysql');
33
        $this->enableQueryCounter();
34
        $this->refreshSeedData();
35
    }
36
37
    private function refreshSeedData()
38
    {
39
        $this->truncateAllTablesButMigrations(static::DB_NAME);
40
        $seeder = new AddFreshSeeds;
41
        $seeder->run();
42
    }
43
44
    private function makeSureDatabaseExists($dbName)
45
    {
46
        $this->runQuery('CREATE DATABASE IF NOT EXISTS '.$dbName);
47
    }
48
49
    private function makeSureSchemaIsCreated($dbConnectionName)
50
    {
51
        $migrationsPath = '../../../../tests/migrations';
52
        $artisan = $this->app->make('Illuminate\Contracts\Console\Kernel');
53
54
        // Makes sure the migrations table is created
55
        $artisan->call('migrate', [
56
            '--database' => $dbConnectionName,
57
            '--path'     => $migrationsPath,
58
        ]);
59
    }
60
61
    private function truncateAllTablesButMigrations($dbName)
62
    {
63
        $db = $this->app->make('db');
64
        $db->statement('SET FOREIGN_KEY_CHECKS=0;');
65
66
        foreach ($tables = $db->select('SHOW TABLES') as $table) {
67
            $table = $table->{'Tables_in_'.$dbName};
68
            if ($table != 'migrations') {
69
                $db->table($table)->truncate();
70
            }
71
        }
72
        $db->statement('SET FOREIGN_KEY_CHECKS=1;');
73
    }
74
75
    /**
76
     * @param $query
77
     * return void
78
     */
79
    private function runQuery($query)
80
    {
81
        $dbUsername = static::DB_USERNAME;
82
        $dbPassword = static::DB_PASSWORD;
83
84
        $command = "mysql -u $dbUsername ";
85
        $command .= $dbPassword ? " -p$dbPassword" : '';
86
        $command .= " -e '$query'";
87
88
        exec($command.' 2>/dev/null');
89
    }
90
91
    public function testRunningMigration()
92
    {
93
        $country = Country::find(1);
94
        $this->assertEquals('gr', $country->code);
95
    }
96
97
    protected function getPackageProviders($app)
98
    {
99
        return ['Dimsav\Translatable\TranslatableServiceProvider'];
100
    }
101
102
    protected function getEnvironmentSetUp($app)
103
    {
104
        $app['path.base'] = __DIR__.'/..';
105
        $app['config']->set('database.default', 'mysql');
106
        $app['config']->set('database.connections.mysql', [
107
            'driver'   => 'mysql',
108
            'host' => '127.0.0.1',
109
            'database' => static::DB_NAME,
110
            'username' => static::DB_USERNAME,
111
            'password' => static::DB_PASSWORD,
112
            'charset' => 'utf8',
113
            'collation' => 'utf8_unicode_ci',
114
            'strict' => false,
115
        ]);
116
        $app['config']->set('database.connections.mysql2', [
117
            'driver'   => 'mysql',
118
            'host' => '127.0.0.1',
119
            'database' => static::DB_NAME2,
120
            'username' => static::DB_USERNAME,
121
            'password' => static::DB_PASSWORD,
122
            'charset' => 'utf8',
123
            'collation' => 'utf8_unicode_ci',
124
            'strict' => false,
125
        ]);
126
        $app['config']->set('translatable.locales', ['el', 'en', 'fr', 'de', 'id']);
127
    }
128
129
    protected function getPackageAliases($app)
130
    {
131
        return ['Eloquent' => 'Illuminate\Database\Eloquent\Model'];
132
    }
133
134
    protected function enableQueryCounter()
135
    {
136
        $that = $this;
137
        $event = App::make('events');
138
        $event->listen('illuminate.query', function ($query, $bindings) use ($that) {
139
            $that->queriesCount++;
140
            $bindings = $this->formatBindingsForSqlInjection($bindings);
141
            $query = $this->insertBindingsIntoQuery($query, $bindings);
142
            $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...
143
            // 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...
144
        });
145
    }
146
147
    private function beautifyQuery($query)
148
    {
149
        $capitalizeWords = ['select ', ' from ', ' where ', ' on ', ' join '];
150
        $newLineWords = ['select ', 'from ', 'where ', 'join '];
151
        foreach ($capitalizeWords as $word) {
152
            $query = str_replace($word, strtoupper($word), $query);
153
        }
154
155
        foreach ($newLineWords as $word) {
156
            $query = str_replace($word, "\n$word", $query);
157
            $word = strtoupper($word);
158
            $query = str_replace($word, "\n$word", $query);
159
        }
160
161
        return $query;
162
    }
163
164
    /**
165
     * @param $bindings
166
     *
167
     * @return mixed
168
     */
169
    private function formatBindingsForSqlInjection($bindings)
170
    {
171
        foreach ($bindings as $i => $binding) {
172
            if ($binding instanceof DateTime) {
173
                $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
174
            } else {
175
                if (is_string($binding)) {
176
                    $bindings[$i] = "'$binding'";
177
                }
178
            }
179
        }
180
181
        return $bindings;
182
    }
183
184
    /**
185
     * @param $query
186
     * @param $bindings
187
     *
188
     * @return string
189
     */
190
    private function insertBindingsIntoQuery($query, $bindings)
191
    {
192
        if (empty($bindings)) {
193
            return $query;
194
        }
195
196
        $query = str_replace(['%', '?'], ['%%', '%s'], $query);
197
198
        return vsprintf($query, $bindings);
199
    }
200
}
201