Completed
Push — master ( 2414f9...f8d33c )
by ARCANEDEV
03:36
created

Metric::setRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
nc 1
cc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelMetrics\Metrics;
2
3
use Arcanedev\LaravelMetrics\Concerns\ConvertsToArray;
4
use Closure;
5
use DateInterval;
6
use Illuminate\Contracts\Support\{Arrayable, Jsonable, Responsable};
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Http\{JsonResponse, Request};
9
use Illuminate\Support\Facades\Cache;
10
use Illuminate\Support\Str;
11
use JsonSerializable;
12
13
/**
14
 * Class     Metric
15
 *
16
 * @package  Arcanedev\LaravelMetrics\Metrics
17
 * @author   ARCANEDEV <[email protected]>
18
 */
19
abstract class Metric implements Arrayable, Jsonable, JsonSerializable, Responsable
20
{
21
    /* -----------------------------------------------------------------
22
     |  Traits
23
     | -----------------------------------------------------------------
24
     */
25
26
    use ConvertsToArray;
27
28
    /* -----------------------------------------------------------------
29
     |  Properties
30
     | -----------------------------------------------------------------
31
     */
32
33
    /**
34
     * The Http request instance.
35
     *
36
     * @var \Illuminate\Http\Request
37
     */
38
    protected $request;
39
40
    /* -----------------------------------------------------------------
41
     |  Getters & Setters
42
     | -----------------------------------------------------------------
43
     */
44
45
    /**
46
     * Get the metric's type.
47
     *
48
     * @return string
49
     */
50
    abstract public function type(): string;
51
52
    /**
53
     * Get the metric's title.
54
     *
55
     * @return string
56
     */
57 8
    public function title(): string
58
    {
59 8
        $class = class_basename(static::class);
60
61 8
        return Str::title(Str::snake($class, ' '));
62
    }
63
64
    /**
65
     * Set the Http request.
66
     *
67
     * @param  \Illuminate\Http\Request  $request
68
     *
69
     * @return $this
70
     */
71 92
    public function setRequest(Request $request)
1 ignored issue
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
72
    {
73 92
        $this->request = $request;
74
75 92
        return $this;
76
    }
77
78
    /**
79
     * Determine for how many minutes the metric should be cached.
80
     *
81
     * @return \DateTimeInterface|\DateInterval|float|int|void
82
     */
83 84
    public function cacheFor()
84
    {
85
        //
86 84
    }
87
88
    /* -----------------------------------------------------------------
89
     |  Main Methods
90
     | -----------------------------------------------------------------
91
     */
92
93
    /**
94
     * Resolve & calculate the metric.
95
     *
96
     * @param  \Illuminate\Http\Request  $request
97
     *
98
     * @return \Arcanedev\LaravelMetrics\Results\Result|mixed
99
     */
100 92
    public function resolve(Request $request)
101
    {
102 92
        $this->setRequest($request);
103
104
        $resolver = function () use ($request) {
105 84
            return $this->calculate($request);
106 92
        };
107
108 92
        return ($cacheFor = $this->cacheFor())
109 8
            ? $this->cacheResult($cacheFor, $resolver)
110 92
            : $resolver();
111
    }
112
113
    /**
114
     * Calculate the metric.
115
     *
116
     * @param  \Illuminate\Http\Request  $request
117
     *
118
     * @return \Arcanedev\LaravelMetrics\Results\Result|mixed
119
     */
120
    abstract public function calculate(Request $request);
121
122
    /**
123
     * Make a new result instance.
124
     *
125
     * @param  mixed|null  $value
126
     *
127
     * @return \Arcanedev\LaravelMetrics\Results\Result
128
     */
129
    abstract protected function result($value = null);
130
131
    /* -----------------------------------------------------------------
132
     |  Other Methods
133
     | -----------------------------------------------------------------
134
     */
135
136
    /**
137
     * Get the instance as an array.
138
     *
139
     * @return array
140
     */
141 8
    public function toArray(): array
142
    {
143
        return [
144 8
            'class' => static::class,
145 8
            'type'  => $this->type(),
146 8
            'title' => $this->title(),
147
        ];
148
    }
149
150
    /**
151
     * Create an HTTP response that represents the object.
152
     *
153
     * @param  \Illuminate\Http\Request  $request
154
     *
155
     * @return \Illuminate\Http\JsonResponse
156
     */
157
    public function toResponse($request)
158
    {
159
        return new JsonResponse($this->toArray());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Illuminate\H...onse($this->toArray()); (Illuminate\Http\JsonResponse) is incompatible with the return type declared by the interface Illuminate\Contracts\Sup...Responsable::toResponse of type Illuminate\Http\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
160
    }
161
162
    /**
163
     * Get the query builder.
164
     *
165
     * @param  \Illuminate\Database\Eloquent\Builder|string  $model
166
     *
167
     * @return \Illuminate\Database\Eloquent\Builder
168
     */
169 84
    protected static function getQuery($model): Builder
170
    {
171 84
        return $model instanceof Builder ? $model : (new $model)->newQuery();
172
    }
173
174
    /**
175
     * Cache the result.
176
     *
177
     * @param  mixed     $cacheFor
178
     * @param  \Closure  $callback
179
     *
180
     * @return mixed
181
     */
182 8
    protected function cacheResult($cacheFor, Closure $callback)
183
    {
184 8
        if (is_numeric($cacheFor))
185 4
            $cacheFor = new DateInterval(sprintf('PT%dS', $cacheFor * 60));
186
187 8
        $key = sprintf(
188 8
            '%s.%s.%s.%s.%s',
189 8
            Str::slug($this->getCachePrefix(), '.'),
190 8
            Str::slug(str_replace('\\', '_', static::class)),
191 8
            $this->request->input('range', 'no-range'),
192 8
            $this->request->input('timezone', 'no-timezone'),
193 8
            $this->request->input('twelveHourTime', '24-hour-time')
194
        );
195
196 8
        return Cache::remember($key, $cacheFor, $callback);
197
    }
198
199
    /**
200
     * Get the cache's prefix.
201
     *
202
     * @return string
203
     */
204 8
    protected function getCachePrefix(): string
205
    {
206 8
        return config('metrics.cache.prefix', 'arcanedev.metrics');
207
    }
208
}
209