Countable   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAmount() 0 3 3
A incrementCounter() 0 8 2
A decrementCounter() 0 18 4
1
<?php
2
3
namespace OkayBueno\Repositories\src\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
/**
8
 * Class Countable
9
 * @package OkayBueno\Repositories\Traits
10
 */
11
trait Countable
12
{
13
14
    /**
15
     * @param Model $model
16
     * @param $counter
17
     * @param int $amount
18
     * @return Model
19
     */
20
    public function incrementCounter( Model $model, $counter, $amount = 1 )
21
    {
22
        $amount = $this->getAmount( $amount );
23
24
        if ( $amount ) $model->increment( $counter, $amount );
0 ignored issues
show
Bug Best Practice introduced by
The expression $amount of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
25
        else $model->increment( $counter );
26
27
        return $model;
28
    }
29
30
31
    /**
32
     * @param Model $model
33
     * @param $counter
34
     * @param int $amount
35
     * @param bool|FALSE $allowNegative
36
     * @return Model
37
     */
38
    public function decrementCounter( Model $model, $counter, $amount = 1, $allowNegative = FALSE )
39
    {
40
        $amount = $this->getAmount( $amount, 1 );
41
42
        $currentValue = $model->{$counter};
43
        $final = $model->{$counter} - $amount;
44
45
        if ( !$allowNegative )
46
        {
47
            if ( $currentValue && $final < 0 )
48
            {
49
                $model->{$counter} = 0;
50
                $model->save();
51
            }
52
53
        } else $model->decrement( $counter, $amount );
54
55
        return $model;
56
    }
57
58
59
    /**
60
     * @param $amount
61
     * @param null $default
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
62
     * @return int|null
63
     */
64
    private function getAmount( $amount, $default = NULL )
65
    {
66
        return is_int( $amount ) && $amount > 1 ? $amount : $default;
67
    }
68
}