Passed
Push — tests-speed ( 2b6c5e )
by Dimitrios
10:14
created

TestsBase::enableQueryCounter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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