Passed
Push — main ( 79ccdf...097cc9 )
by Dimitri
03:17
created

ResponseTrait::view()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 13
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
use GuzzleHttp\Psr7\Utils;
19
20
trait ResponseTrait
21
{
22
    /**
23
     * Définit l'en-tête de date
24
     */
25
    public function withDate(DateTime $date): self
26
    {
27
        $date->setTimezone(new DateTimeZone('UTC'));
28
29
        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

29
        return $this->/** @scrutinizer ignore-call */ withHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT');
Loading history...
30
    }
31
32
    /**
33
     * Convertit le $body en JSON et définit l'en-tête Content Type.
34
     */
35
    public function json(array|string $body, int $status = StatusCode::OK): self
36
    {
37
        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

37
        return $this->/** @scrutinizer ignore-call */ withType('application/json')
Loading history...
38
            ->withStringBody(Formatter::type('json')->format($body))
39
            ->withStatus($status);
40
    }
41
42
    /**
43
     * Renvoie le corps actuel, converti en JSON s'il ne l'est pas déjà.
44
     *
45
     * @throws InvalidArgumentException Si la propriété body n'est pas un json valide.
46
     */
47
    public function toJson(): array
48
    {
49
        $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

49
        $body = $this->/** @scrutinizer ignore-call */ getBody()->getContents();
Loading history...
50
51
        return Formatter::type('json')->parse($body);
52
    }
53
54
    /**
55
     * Convertit $body en XML et définit le Content-Type correct.
56
     */
57
    public function xml(array|string $body, int $status = StatusCode::OK): self
58
    {
59
        return $this->withType('application/xml')
60
            ->withStringBody(Formatter::type('xml')->format($body))
61
            ->withStatus($status);
62
    }
63
64
    /**
65
     * Récupère le corps actuel dans XML et le renvoie.
66
     */
67
    public function toXml()
68
    {
69
        $body = $this->getBody()->getContents();
70
71
        return Formatter::type('xml')->parse($body);
72
    }
73
74
    /**
75
     * Définit les en-têtes appropriés pour garantir que cette réponse n'est pas mise en cache par les navigateurs.
76
     *
77
     * @todo Recommander la recherche de ces directives, pourrait avoir besoin: 'private', 'no-transform', 'no-store', 'must-revalidate'
78
     */
79
    public function noCache(): self
80
    {
81
        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

81
        return $this->/** @scrutinizer ignore-call */ withoutHeader('Cache-Control')
Loading history...
82
            ->withHeader('Cache-Control', ['no-store', 'max-age=0', 'no-cache']);
83
    }
84
85
    /**
86
     * Génère les en-têtes qui forcent un téléchargement à se produire.
87
     * Et envoie le fichier au navigateur.
88
     *
89
     * @param string      $filename Le nom que vous souhaitez donner au fichier téléchargé ou le chemin d'accès au fichier à envoyer
90
     * @param string|null $data     Les données à télécharger. Définissez null si le $filename est le chemin du fichier
91
     */
92
    public function download(string $filename, ?string $data = ''): static
93
    {
94
        if (is_file($filename)) {
95
            $filepath = realpath($filename);
96
            $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));
97
            $filename = end($filename);
98
99
            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

99
            return $this->/** @scrutinizer ignore-call */ withFile($filepath, ['download' => true, 'name' => $filename]);
Loading history...
100
        }
101
102
        if (! empty($data)) {
103
            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

103
            return $this->/** @scrutinizer ignore-call */ withStringBody($data)
Loading history...
104
                ->withType(pathinfo($filename, PATHINFO_EXTENSION))
105
                ->withDownload($filename);
106
        }
107
108
        return $this;
109
    }
110
111
    /**
112
     * Renvoi une vue comme reponse
113
     */
114
    public function view(string $view, array $data = [], array|int $optionsOrStatus = StatusCode::OK): static
115
    {
116
        if (is_int($optionsOrStatus)) {
117
            $status  = $optionsOrStatus;
118
            $options = [];
119
        } else{
120
            $status = $optionsOrStatus['status'] ?? StatusCode::OK;
121
            $options = array_filter($optionsOrStatus, fn($k) => $k !== 'status', ARRAY_FILTER_USE_KEY);
122
        }
123
124
        $viewContent = view($view, $data, $options)->get();
125
126
        return $this->withStatus($status)->withBody(Utils::streamFor($viewContent));
0 ignored issues
show
Bug introduced by
It seems like withStatus() 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

126
        return $this->/** @scrutinizer ignore-call */ withStatus($status)->withBody(Utils::streamFor($viewContent));
Loading history...
127
    }
128
}
129