Passed
Push — laravel-5.3 ( f7c693 )
by Dimitrios
80:24 queued 73:31
created

TestsBase   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 7
Bugs 2 Features 1
Metric Value
wmc 20
c 7
b 2
f 1
lcom 1
cbo 2
dl 0
loc 170
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A dropDb() 0 4 1
A createDb() 0 4 1
A runQuery() 0 11 2
A getPackageProviders() 0 4 1
A testRunningMigration() 0 5 1
A setUp() 0 10 1
A getEnvironmentSetUp() 0 16 1
A getPackageAliases() 0 4 1
A countQueries() 0 12 1
A beautifyQuery() 0 16 3
B resetDatabase() 0 24 1
A formatBindingsForSqlInjection() 0 14 4
A insertBindingsIntoQuery() 0 10 2
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' => '127.0.0.1',
69
            'database' => static::DB_NAME,
70
            'username' => static::DB_USERNAME,
71
            'password' => static::DB_PASSWORD,
72
            'charset' => 'utf8',
73
            'collation' => 'utf8_unicode_ci',
74
            'strict' => false,
75
        ]);
76
        $app['config']->set('translatable.locales', ['el', 'en', 'fr', 'de', 'id']);
77
    }
78
79
    protected function getPackageAliases($app)
80
    {
81
        return ['Eloquent' => 'Illuminate\Database\Eloquent\Model'];
82
    }
83
84
    protected function countQueries()
85
    {
86
        $that = $this;
87
        $event = App::make('events');
88
        $event->listen('illuminate.query', function ($query, $bindings) use ($that) {
89
            $that->queriesCount++;
90
            $bindings = $this->formatBindingsForSqlInjection($bindings);
91
            $query = $this->insertBindingsIntoQuery($query, $bindings);
92
            $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...
93
            // 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...
94
        });
95
    }
96
97
    private function beautifyQuery($query)
98
    {
99
        $capitalizeWords = ['select ', ' from ', ' where ', ' on ', ' join '];
100
        $newLineWords = ['select ', 'from ', 'where ', 'join '];
101
        foreach ($capitalizeWords as $word) {
102
            $query = str_replace($word, strtoupper($word), $query);
103
        }
104
105
        foreach ($newLineWords as $word) {
106
            $query = str_replace($word, "\n$word", $query);
107
            $word = strtoupper($word);
108
            $query = str_replace($word, "\n$word", $query);
109
        }
110
111
        return $query;
112
    }
113
114
    private function resetDatabase()
115
    {
116
        // Relative to the testbench app folder: vendors/orchestra/testbench/src/fixture
117
        $migrationsPath = __DIR__.'/migrations';
118
        $artisan = $this->app->make('Illuminate\Contracts\Console\Kernel');
119
120
        // Makes sure the migrations table is created
121
        $artisan->call('migrate', [
122
            '--database' => 'mysql',
123
            '--realpath'     => $migrationsPath,
124
        ]);
125
126
        // We empty all tables
127
        $artisan->call('migrate:reset', [
128
            '--database' => 'mysql',
129
            '--realpath'     => $migrationsPath,
130
        ]);
131
132
        // Migrate
133
        $artisan->call('migrate', [
134
            '--database' => 'mysql',
135
            '--realpath'     => $migrationsPath,
136
        ]);
137
    }
138
139
    /**
140
     * @param $bindings
141
     *
142
     * @return mixed
143
     */
144
    private function formatBindingsForSqlInjection($bindings)
145
    {
146
        foreach ($bindings as $i => $binding) {
147
            if ($binding instanceof DateTime) {
148
                $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
149
            } else {
150
                if (is_string($binding)) {
151
                    $bindings[$i] = "'$binding'";
152
                }
153
            }
154
        }
155
156
        return $bindings;
157
    }
158
159
    /**
160
     * @param $query
161
     * @param $bindings
162
     *
163
     * @return string
164
     */
165
    private function insertBindingsIntoQuery($query, $bindings)
166
    {
167
        if (empty($bindings)) {
168
            return $query;
169
        }
170
171
        $query = str_replace(['%', '?'], ['%%', '%s'], $query);
172
173
        return vsprintf($query, $bindings);
174
    }
175
}
176