Completed
Push — master ( e8d58e...20c4ee )
by ARCANEDEV
04:06
created

Trend::aggregate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 35
cts 35
cp 1
rs 9.0036
c 0
b 0
f 0
cc 3
nc 2
nop 5
crap 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Arcanedev\LaravelMetrics\Metrics;
2
3
use Arcanedev\LaravelMetrics\Exceptions\InvalidTrendUnitException;
4
use Arcanedev\LaravelMetrics\Helpers\TrendDatePeriod;
5
use Arcanedev\LaravelMetrics\Results\TrendResult;
6
use Cake\Chronos\Chronos;
7
use Illuminate\Support\Facades\DB;
8
9
/**
10
 * Class     Trend
11
 *
12
 * @package  Arcanedev\LaravelMetrics\Metrics
13
 * @author   ARCANEDEV <[email protected]>
14
 */
15
abstract class Trend extends Metric
16
{
17
    /* -----------------------------------------------------------------
18
     |  Constants
19
     | -----------------------------------------------------------------
20
     */
21
22
    /**
23
     * Trend metric unit constants.
24
     */
25
    const BY_MONTHS  = 'month';
26
    const BY_WEEKS   = 'week';
27
    const BY_DAYS    = 'day';
28
    const BY_HOURS   = 'hour';
29
    const BY_MINUTES = 'minute';
30
31
    /* -----------------------------------------------------------------
32
     |  Traits
33
     | -----------------------------------------------------------------
34
     */
35
36
    use Concerns\AggregatesTrends,
37
        Concerns\HasExpressions,
38
        Concerns\HasRanges,
39
        Concerns\FormatsTrends;
40
41
    /* -----------------------------------------------------------------
42
     |  Getters
43
     | -----------------------------------------------------------------
44
     */
45
46
    /**
47
     * Get the metric type.
48
     *
49
     * @return string
50
     */
51 16
    public function type(): string
52
    {
53 16
        return 'trend';
54
    }
55
56
    /* -----------------------------------------------------------------
57
     |  Main Methods
58
     | -----------------------------------------------------------------
59
     */
60
61
    /**
62
     * Calculate the `count` of the metric.
63
     *
64
     * @param  string                                        $unit
65
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
66
     * @param  string|null                                   $dateColumn
67
     * @param  string|null                                   $column
68
     *
69
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
70
     */
71 16
    public function count($unit, $model, $dateColumn = null, $column = null)
72
    {
73 16
        return $this->aggregate('count', $unit, $model, $column, $dateColumn);
74
    }
75
76
    /**
77
     * Return a value result showing a average aggregate over time.
78
     *
79
     * @param  string                                        $unit
80
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
81
     * @param  string                                        $column
82
     * @param  string|null                                   $dateColumn
83
     *
84
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
85
     */
86
    public function average(string $unit, $model, $column, $dateColumn = null)
87
    {
88
        return $this->aggregate('avg', $unit, $model, $column, $dateColumn);
89
    }
90
91
    /**
92
     * Return a value result showing a sum aggregate over time.
93
     *
94
     * @param  string                                        $unit
95
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
96
     * @param  string                                        $column
97
     * @param  string|null                                   $dateColumn
98
     *
99
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
100
     */
101
    public function sum(string $unit, $model, $column, $dateColumn = null)
102
    {
103
        return $this->aggregate('sum', $unit, $model, $column, $dateColumn);
104
    }
105
106
    /**
107
     * Return a value result showing a max aggregate over time.
108
     *
109
     * @param  string                                        $unit
110
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
111
     * @param  string                                        $column
112
     * @param  string|null                                   $dateColumn
113
     *
114
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
115
     */
116
    public function max(string $unit, $model, $column, $dateColumn = null)
117
    {
118
        return $this->aggregate('max', $unit, $model, $column, $dateColumn);
119
    }
120
121
    /**
122
     * Return a value result showing a min aggregate over time.
123
     *
124
     * @param  string                                        $unit
125
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
126
     * @param  string                                        $column
127
     * @param  string|null                                   $dateColumn
128
     *
129
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
130
     */
131
    public function min(string $unit, $model, $column, $dateColumn = null)
132
    {
133
        return $this->aggregate('min', $unit, $model, $column, $dateColumn);
134
    }
135
136
    /**
137
     * Make a new result instance.
138
     *
139
     * @param  mixed|null  $value
140
     *
141
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
142
     */
143 16
    protected function result($value = null)
144
    {
145 16
        return new TrendResult($value);
146
    }
147
148
    /* -----------------------------------------------------------------
149
     |  Other Methods
150
     | -----------------------------------------------------------------
151
     */
152
153
    /**
154
     * Handle the aggregate calculation of the metric.
155
     *
156
     * @param  string                                        $method
157
     * @param  string                                        $unit
158
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
159
     * @param  string|null                                   $column
160
     * @param  string|null                                   $dateColumn
161
     *
162
     * @return \Arcanedev\LaravelMetrics\Results\TrendResult|mixed
163
     */
164 16
    protected function aggregate(string $method, string $unit, $model, ?string $column = null, ?string $dateColumn = null)
165
    {
166 16
        $range          = $this->request->input('range');
167 16
        $timezone       = $this->request->input('timezone');
168 16
        $twelveHourTime = $this->request->input('twelveHourTime') === 'true';
169
170 16
        $query      = static::getQuery($model);
171 16
        $column     = $column ?? $query->getModel()->getCreatedAtColumn();
0 ignored issues
show
Bug introduced by
The method getCreatedAtColumn does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Builder.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
172 16
        $dateColumn = $dateColumn ?? $query->getModel()->getCreatedAtColumn();
173 16
        $expression = $this->getExpression($query, 'trend_date_format', $dateColumn, [$unit, $query, $timezone]);
174
175 16
        $dates = TrendDatePeriod::make(
176 16
            $startingDate = TrendDatePeriod::getStartingDate($unit, $range),
177 16
            $endingDate = Chronos::now(),
178 12
            $unit,
179 12
            $timezone
180
        )->mapWithKeys(function (Chronos $date) use ($twelveHourTime, $unit) {
181
            return [
182 16
                static::formatAggregateKey($date, $unit) => [
183 16
                    'label' => static::formatLabelBy($date, $unit, $twelveHourTime),
184 16
                    'value' => 0,
185
                ]
186
            ];
187 16
        });
188
189 16
        $wrappedColumn = $query->getQuery()->getGrammar()->wrap($column);
190
191 16
        $results = $query->select([
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
192 16
                DB::raw("{$expression} as date_result"),
193 16
                DB::raw("{$method}({$wrappedColumn}) as aggregate")
194
            ])
195 16
            ->whereBetween($dateColumn, [$startingDate, $endingDate])
196 16
            ->groupBy('date_result')
197 16
            ->orderBy('date_result')
198 16
            ->get()
199
            ->mapWithKeys(function ($result) use ($method, $unit, $twelveHourTime) {
200 16
                $date  = static::parseDateResult($result->getAttribute('date_result'), $unit);
201 16
                $value = $result->getAttribute('aggregate');
202
203
                return [
204 16
                    static::formatAggregateKey($date, $unit) => [
205 16
                        'label' => static::formatLabelBy($date, $unit, $twelveHourTime),
206 16
                        'value' => $method === 'count' ? intval($value) : round($value, 0),
207
                    ],
208
                ];
209 16
            });
210
211 16
        $results = $dates->merge($results)->sortKeys();
212
213 16
        if ($results->count() > $range)
214 16
            $results->shift();
215
216 16
        return $this->result()->trend($results->all());
217
    }
218
219
    /**
220
     * Parse the date result.
221
     *
222
     * @param  string  $date
223
     * @param  string  $unit
224
     *
225
     * @return \Cake\Chronos\Chronos
226
     */
227 16
    protected function parseDateResult(string $date, string $unit): Chronos
228
    {
229
        switch ($unit) {
230 16
            case self::BY_MONTHS:
231 4
                return Chronos::createFromFormat('Y-m', $date);
232
233 12
            case self::BY_WEEKS:
234 4
                [$year, $week] = explode('-', $date);
0 ignored issues
show
Bug introduced by
The variable $year does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $week does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
235 4
                return (new Chronos)->setISODate($year, $week)->setTime(0, 0);
236
237 8
            case self::BY_DAYS:
238 8
                return Chronos::createFromFormat('Y-m-d', $date);
239
240
            case self::BY_HOURS:
241
                return Chronos::createFromFormat('Y-m-d H:00', $date);
242
243
            case self::BY_MINUTES:
244
                return Chronos::createFromFormat('Y-m-d H:i:00', $date);
245
246
            default:
247
                throw InvalidTrendUnitException::make($unit);
248
        }
249
    }
250
251
    /**
252
     * Prepare the metric for JSON serialization.
253
     *
254
     * @return array
255
     */
256
    public function toArray(): array
257
    {
258
        return array_merge(
259
            parent::toArray(),
260
            ['ranges' => $this->rangesToArray()]
261
        );
262
    }
263
}
264