Test Setup Failed
Pull Request — master (#1)
by
unknown
06:50
created

PeriodicQuota::setLogTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 3
cp 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of laravel-quota
5
 *
6
 * (c) David Faith <[email protected]>
7
 *
8
 * Full copyright and license information is available
9
 * in the LICENSE file distributed with this source code.
10
 */
11
12
namespace Projectmentor\Quota;
13
14
use DB;
15
use Carbon\Carbon;
16
17
/**
18
 * This is the periodic quota class.
19
 * It is used to limit access to a resource
20
 * over a defined period of time.
21
 *
22
 * NOTE: Currently only supports daily quota
23
 * period. i.e. $this->period = 'day'
24
 *
25
 * TODO: REFACTOR for different period types.
26
 * @See constants in bandwidthThrottle\tokenBucket\Rate.php
27
 * for allowed period types.
28
 */
29
30
class PeriodicQuota extends Quota 
0 ignored issues
show
Coding Style introduced by
The property $log_table is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
31
{
32
    /**
33
     * The timezone authority.
34
     * Used to roll the log records in the database.
35
     *
36
     * @var string
37
     */
38
    protected $timezone;
39
40
    /**
41
     * The database table name
42
     *
43
     * @var string
44
     */
45
    protected $log_table;
0 ignored issues
show
Coding Style introduced by
$log_table does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
46
47
    /**
48
     *  Construct instance.
49
     *
50
     *  @param string $connection
51
     *  @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
52
     */
53 8
    public function __construct($connection)
54
    {
55 8
        parent::__construct($connection);
56
57 8
        $this->connection = $connection;
58 8
        $this->index = 'quota.connections.' . $connection;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
59
60 8
        $this->timezone = config($this->index . '.timezone');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
61 8
        if(is_null($this->timezone))
62 8
            $this->timezone = config('quota.default_timezone');
63
64 8
        $this->log_table = config($this->index . '.log_table');
65
66
        //Bootstrap log if record does not exist.
67 8
        $dtz = new \DateTimeZone($this->timezone);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 9 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
68 8
        $now = new \DateTime(date("Y-m-d"), $dtz);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 9 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Coding Style Comprehensibility introduced by
The string literal Y-m-d does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
69 8
        $date = $now->format("Y-m-d");
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Coding Style Comprehensibility introduced by
The string literal Y-m-d does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
70 8
        $log_records = DB::select(
0 ignored issues
show
Coding Style introduced by
$log_records does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
71
            'SELECT * FROM' .
72 8
            ' ' .  $this->log_table .
73 8
            ' WHERE date = ' . '\'' . $date . '\'' .
74 8
            '  AND connection = ' . '\'' . $connection . '\''
75 8
        );
76
77 8
        if(empty($log_records))
0 ignored issues
show
Coding Style introduced by
$log_records does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
78 8
            \Artisan::call('quota:reset', [
79 8
                'date' => $date,
80
                'connection' =>  $connection
81 8
            ]);
82 8
    }
83
84 1
    public function enforce()
85
    {
86 1
        return $this->consume();
87
    }
88
89
    /**
90
     * Helper.
91
     *
92
     * TODO: make static?
93
     *
94
     * @param PeriodicQuota $quota
0 ignored issues
show
Bug introduced by
There is no parameter named $quota. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
95
     * @return string
96
     */
97 8
    public function dateInTimezone()
98
    {
99 8
        $dtz = new \DateTimeZone($this->getTimezone());
100 8
        $now = new \DateTime(date("Y-m-d"), $dtz);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Y-m-d does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
101 8
        return($now->format("Y-m-d"));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Y-m-d does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
102
    }
103
104
    /**
105
     * Hiiiiit iiiiiit ! :)
106
     * Record a hit in the log table.
107
     *
108
     * @param int $hits so far
109
     * @return void
110
     */
111 3 View Code Duplication
    public function hit($hits)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
    {
113 3
        $date = $this->dateInTimezone();
114 3
        $hits = $hits + 1;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $hits. This often makes code more readable.
Loading history...
115
116 3
        DB::statement(
117 3
            'UPDATE ' . $this->log_table .
118 3
            ' SET hits = ' . $hits .
119 3
            ', updated_at = ' . '\'' . Carbon::now()->toDateTimeString() . '\'' .
120 3
            ' WHERE date = ' . '\'' . $date . '\'' .
121 3
            ' AND connection = ' . '\'' . $this->connection . '\''
122 3
        );
123 3
    }
124
125
    /**
126
     * Record a miss in the log table.
127
     *
128
     * @param int $misses so far
129
     * @return void
130
     */
131 1 View Code Duplication
    public function miss($misses)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133 1
        $date = $this->dateInTimezone();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
134 1
        $misses = $misses + 1;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $misses. This often makes code more readable.
Loading history...
135
136 1
        DB::statement(
137 1
            'UPDATE ' . $this->log_table .
138 1
            ' SET misses = ' . $misses .
139 1
            ', updated_at = ' . '\'' . Carbon::now()->toDateTimeString() . '\'' .
140 1
            ' WHERE date = ' . '\'' . $date . '\'' .
141 1
            ' AND connection = ' . '\'' . $this->connection . '\''
142 1
        );
143 1
    }
144
145
    /**
146
     * Attempt to... HIT dat a$$!  :)
147
     *
148
     * @param integer $tokens future use.
149
     * @return boolean true on success
150
     *
151
     * @throws ErrorException
152
     */
153 2
    public function consume($tokens = 1)
0 ignored issues
show
Coding Style introduced by
function consume() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Unused Code introduced by
The parameter $tokens is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
154
    {
155 2
        $date = $this->dateInTimezone();
156
157 2
        $stats = $this->getStats($date);
158 2
        $hits = (integer) $stats->hits;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
159
160 2
        if($this->limit < ($hits + 1))
161 2
        {
162
           $this->miss($stats->misses);
163
           throw new \ErrorException(
164
               __CLASS__ . '::' . __FUNCTION__ .
165
               ' Overquota. Exceeded daily limit: ' . $this->limit);
166
        }
167
        else
168
        {
169 2
            $this->hit($stats->hits);
170 2
            $result = true;
171
        }
172 2
         return isset($result);
173
    }
174
175
    /**
176
     * Get statistics from log table.
177
     *
178
     * TODO: REFACTOR rename `date` to `period`
179
     * to reflect ability to track different periodic
180
     * limits.
181
     *
182
     * @param string $date
183
     * @return stdObject
184
     * @throws Exception
185
     */
186 3
    public function getStats($date)
187
    {
188 3
        return DB::table('quotalog')
189 3
           ->where('date', $date)
190 3
           ->where('connection', $this->connection)
191 3
           ->first();
192
    }
193
194
    /**
195
     * Get the timezone
196
     *
197
     * @return string
198
     */
199 8
    public function getTimezone()
200
    {
201 8
        return $this->timezone;
202
    }
203
204
    /**
205
     * Get the log table name
206
     *
207
     * @return string
208
     */
209 5
    public function getLogTable()
210
    {
211 5
        return $this->log_table;
212
    }
213
214
    /**
215
     * Set the timezone authority
216
     *
217
     * @param string
218
     * @return void
219
     */
220
    public function setTimezone($timezone)
221
    {
222
        $this->timezone = $timezone;
223
    }
224
225
    /**
226
     * Set the log_table name
227
     *
228
     * @param string
229
     * @return void
230
     */
231
    public function setLogTable($log_table)
0 ignored issues
show
Coding Style introduced by
$log_table does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Coding Style Naming introduced by
The parameter $log_table is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
232
    {
233
        $this->log_table = $log_table;
0 ignored issues
show
Coding Style introduced by
$log_table does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
234
    }
235
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
236