EtagConditionals::etagGenerateUsing()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Werk365\EtagConditionals;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Str;
8
use Symfony\Component\HttpFoundation\Response;
9
10
class EtagConditionals
11
{
12
    /**
13
     * The callback used to generate the ETag.
14
     *
15
     * @var \Closure|null
16
     */
17
    protected static $etagGenerateCallback;
18
19
    /**
20
     * Set a callback that should be used when generating the ETag.
21
     *
22
     * @param  \Closure|null  $callback
23
     * @return void
24
     */
25
    public static function etagGenerateUsing(?Closure $callback): void
26
    {
27
        static::$etagGenerateCallback = $callback;
28
    }
29
30
    /**
31
     * Get ETag value for this request and response.
32
     *
33
     * @param  \Illuminate\Http\Request  $request
34
     * @param  \Symfony\Component\HttpFoundation\Response  $response
35
     * @return string
36
     */
37
    public static function getEtag(Request $request, Response $response): string
38
    {
39
        if (static::$etagGenerateCallback) {
40
            $etag = call_user_func(static::$etagGenerateCallback, $request, $response);
41
        } else {
42
            $etag = static::defaultGetEtag($response);
43
        }
44
45
        return (string) Str::of($etag)->start('"')->finish('"');
46
    }
47
48
    /**
49
     * Get default ETag value.
50
     *
51
     * @param  \Symfony\Component\HttpFoundation\Response  $response
52
     * @return string
53
     */
54
    private static function defaultGetEtag(Response $response): string
55
    {
56
        return md5($response->getContent());
57
    }
58
}
59