Passed
Push — main ( 625462...aa68b0 )
by Dimitri
03:08
created

ResponseTrait::noCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 2
c 1
b 1
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Http\Concerns;
13
14
use BlitzPHP\Contracts\Http\StatusCode;
15
use BlitzPHP\Formatter\Formatter;
16
use DateTime;
17
use DateTimeZone;
18
19
trait ResponseTrait
20
{
21
    /**
22
     * Définit l'en-tête de date
23
     */
24
    public function withDate(DateTime $date): self
25
    {
26
        $date->setTimezone(new DateTimeZone('UTC'));
27
28
        return $this->withHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT');
0 ignored issues
show
Bug introduced by
It seems like withHeader() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

28
        return $this->/** @scrutinizer ignore-call */ withHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT');
Loading history...
29
    }
30
31
    /**
32
     * Convertit le $body en JSON et définit l'en-tête Content Type.
33
     */
34
    public function json(array|string $body, int $status = StatusCode::OK): self
35
    {
36
        return $this->withType('application/json')
0 ignored issues
show
Bug introduced by
It seems like withType() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

36
        return $this->/** @scrutinizer ignore-call */ withType('application/json')
Loading history...
37
                    ->withStringBody(Formatter::type('json')->format($body))
38
                    ->withStatus($status);
39
    }
40
41
    /**
42
     * Renvoie le corps actuel, converti en JSON s'il ne l'est pas déjà.
43
     *
44
     * @throws InvalidArgumentException Si la propriété body n'est pas un json valide.
45
     */
46
    public function toJson(): array
47
    {
48
        $body = $this->getBody()->getContents();
0 ignored issues
show
Bug introduced by
It seems like getBody() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

48
        $body = $this->/** @scrutinizer ignore-call */ getBody()->getContents();
Loading history...
49
50
        return Formatter::type('json')->parse($body);
51
    }
52
53
    /**
54
     * Convertit $body en XML et définit le Content-Type correct.
55
     */
56
    public function xml(array|string $body, int $status = StatusCode::OK): self
57
    {
58
        return $this->withType('application/xml')
59
                    ->withStringBody(Formatter::type('xml')->format($body))
60
                    ->withStatus($status);
61
    }
62
63
    /**
64
     * Récupère le corps actuel dans XML et le renvoie.
65
     */
66
    public function toXml()
67
    {
68
        $body = $this->getBody()->getContents();
69
70
        return Formatter::type('xml')->parse($body);
71
    }
72
73
    /**
74
     * Définit les en-têtes appropriés pour garantir que cette réponse n'est pas mise en cache par les navigateurs.
75
     *
76
     * @todo Recommander la recherche de ces directives, pourrait avoir besoin: 'private', 'no-transform', 'no-store', 'must-revalidate'
77
     */
78
    public function noCache(): self
79
    {
80
        return $this->withoutHeader('Cache-Control')
0 ignored issues
show
Bug introduced by
It seems like withoutHeader() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
        return $this->/** @scrutinizer ignore-call */ withoutHeader('Cache-Control')
Loading history...
81
                    ->withHeader('Cache-Control', ['no-store', 'max-age=0', 'no-cache']);
82
    }
83
    
84
    /**
85
     * Génère les en-têtes qui forcent un téléchargement à se produire.
86
     * Et envoie le fichier au navigateur.
87
     *
88
     * @param string      $filename Le nom que vous souhaitez donner au fichier téléchargé ou le chemin d'accès au fichier à envoyer
89
     * @param string|null $data     Les données à télécharger. Définissez null si le $filename est le chemin du fichier
90
     */
91
    public function download(string $filename, ?string $data = ''): static
92
    {
93
        if (is_file($filename)) {
94
            $filepath = realpath($filename);
95
            $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));
96
            $filename = end($filename);
97
98
            return $this->withFile($filepath, ['download' => true, 'name' => $filename]);
0 ignored issues
show
Bug introduced by
It seems like withFile() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

98
            return $this->/** @scrutinizer ignore-call */ withFile($filepath, ['download' => true, 'name' => $filename]);
Loading history...
99
        }
100
        
101
        if (! empty($data)) {
102
            return $this->withStringBody($data)
0 ignored issues
show
Bug introduced by
It seems like withStringBody() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

102
            return $this->/** @scrutinizer ignore-call */ withStringBody($data)
Loading history...
103
                    ->withType(pathinfo($filename, PATHINFO_EXTENSION))
104
                    ->withDownload($filename);
105
        }
106
107
        return $this;
108
    }
109
}
110