Passed
Push — main ( d71b68...a743f7 )
by Dimitri
08:12 queued 04:09
created

AbstractAdapter::resetData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 0
cts 2
cp 0
crap 2
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\View\Adapters;
13
14
use BlitzPHP\Container\Services;
15
use BlitzPHP\Contracts\Autoloader\LocatorInterface;
16
use BlitzPHP\Contracts\View\RendererInterface;
17
use BlitzPHP\Exceptions\ViewException;
18
use BlitzPHP\Utilities\Helpers;
19
use BlitzPHP\View\ViewDecoratorTrait;
20
21
abstract class AbstractAdapter implements RendererInterface
22
{
23
    use ViewDecoratorTrait;
24
25
    /**
26
     * Données mises à la disposition des vues.
27
     *
28
     * @var array
29
     */
30
    protected $data = [];
31
32
    /**
33
     * Les variables de rendu
34
     *
35
     * @var array
36
     */
37
    protected $renderVars = [];
38
39
    /**
40
     * Le répertoire de base dans lequel rechercher nos vues.
41
     *
42
     * @var string
43
     */
44
    protected $viewPath = '';
45
46
    /**
47
     * Extension des fichiers de vue
48
     */
49
    protected string $ext = '';
50
51
    /**
52
     * Instance de Locator lorsque nous devons tenter de trouver une vue qui n'est pas à l'emplacement standard.
53
     */
54
    protected ?LocatorInterface $locator = null;
55
56
    /**
57
     * Le nom de la mise en page utilisée, le cas échéant.
58
     * Défini par la méthode "extend" utilisée dans les vues.
59
     *
60
     * @var string|null
61
     */
62
    protected $layout;
63
64
    /**
65
     * Les statistiques sur nos performances ici
66
     *
67
     * @var array
68
     */
69
    protected $performanceData = [];
70
71
    /**
72
     * {@inheritDoc}
73
     *
74
     * @param array $config Configuration actuelle de l'adapter
75
     * @param bool  $debug  Devrions-nous stocker des informations sur les performances ?
76
     */
77
    public function __construct(protected array $config, $viewPathLocator = null, protected bool $debug = BLITZ_DEBUG)
78
    {
79 30
        helper('assets');
80
81
        if (! empty($viewPathLocator)) {
82
            if (is_string($viewPathLocator)) {
83 16
                $this->viewPath = rtrim($viewPathLocator, '\\/ ') . DS;
84
            } elseif ($viewPathLocator instanceof LocatorInterface) {
85 16
                $this->locator = $viewPathLocator;
86
            }
87
        }
88
89
        if (! $this->locator instanceof LocatorInterface && ! is_dir($this->viewPath)) {
90 16
            $this->viewPath = '';
91 16
            $this->locator  = Services::locator();
92
        }
93
94 30
        $this->ext = preg_replace('#^\.#', '', $config['extension'] ?? $this->ext);
95
    }
96
97
    /**
98
     * {@inheritDoc}
99
     */
100
    public function setData(array $data = [], ?string $context = null): self
101
    {
102
        if ($context !== null && $context !== '' && $context !== '0') {
103
            $data = esc($data, $context);
104
        }
105
106
        $this->data = $data;
107
108
        return $this;
109
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114
    public function getData(): array
115
    {
116
        return $this->data;
117
    }
118
119
    /**
120
     * {@inheritDoc}
121
     */
122
    public function addData(array $data = [], ?string $context = null): self
123
    {
124
        if ($context !== null && $context !== '' && $context !== '0') {
125
            $data = esc($data, $context);
126
        }
127
128
        $this->data = array_merge($this->data, $data);
129
130
        return $this;
131
    }
132
133
    /**
134
     * {@inheritDoc}
135
     */
136
    public function setVar(string $name, $value = null, ?string $context = null): self
137
    {
138
        if ($context !== null && $context !== '' && $context !== '0') {
139
            $value = esc($value, $context);
140
        }
141
142
        $this->data[$name] = $value;
143
144
        return $this;
145
    }
146
147
    /**
148
     * Définit plusieurs éléments de données de vue à la fois.
149
     */
150
    public function with(array|string $key, mixed $value = null, ?string $context = null): self
151
    {
152
        if (is_array($key)) {
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
153
            $context = $value;
154
        } else {
155
            $key = [$key => $value];
156
        }
157
158
        return $this->addData($key, $context);
159
    }
160
161
    /**
162
     * {@inheritDoc}
163
     */
164
    public function resetData(): self
165
    {
166
        $this->data = [];
167
168
        return $this;
169
    }
170
171
    /**
172
     * {@inheritDoc}
173
     */
174
    public function setLayout(?string $layout): self
175
    {
176 8
        $this->layout = $layout;
177
178 8
        return $this;
179
    }
180
181
    /**
182
     * {@inheritDoc}
183
     */
184
    public function renderString(string $view, ?array $options = null, bool $saveData = false): string
185
    {
186
        return $this->render($view, $options, $saveData);
187
    }
188
189
    /**
190
     * {@inheritDoc}
191
     */
192
    public function getPerformanceData(): array
193
    {
194 2
        return $this->performanceData;
195
    }
196
197
    /**
198
     * Consigne les données de performances pour le rendu d'une vue.
199
     */
200
    protected function logPerformance(float $start, float $end, string $view)
201
    {
202
        if ($this->debug) {
203
            $this->performanceData[] = [
204
                'start' => $start,
205
                'end'   => $end,
206
                'view'  => $view,
207 20
            ];
208
        }
209
    }
210
211
    /**
212
     * Recupère ou modifie le titre de la page
213
     *
214
     * @return self|string
215
     */
216
    public function title(?string $title = null)
217
    {
218
        if ($title === null || $title === '' || $title === '0') {
219
            return $this->getData()['title'] ?? '';
220
        }
221
222 2
        return $this->setVar('title', $title);
223
    }
224
225
    /**
226
     * Recupère ou modifie les elements de balises "meta"
227
     *
228
     * @return self|string
229
     */
230
    public function meta(string $key, ?string $value = null)
231
    {
232 2
        $meta = $this->getData()['meta'] ?? [];
233
234
        if ($value === null || $value === '' || $value === '0') {
235 2
            return $meta[$key] ?? '';
236
        }
237
238 2
        $meta[$key] = esc($value);
239
240 2
        return $this->setVar('meta', $meta);
241
    }
242
243
    /**
244
     * {@inheritDoc}
245
     */
246
    public function exists(string $view, ?string $ext = null, array $options = []): bool
247
    {
248
        try {
249 4
            return str_contains($this->getRenderedFile($options, $view, $ext), 'Views');
250
        } catch (ViewException) {
251 2
            return false;
252
        }
253
    }
254
255
    /**
256
     * Recupere le chemin absolue du fichier de vue a rendre
257
     */
258
    protected function getRenderedFile(?array $options, string $view, ?string $ext = null): string
259
    {
260 18
        $options = (array) $options;
261 18
        $ext ??= $this->ext;
262
263 18
        $viewPath = $options['viewPath'] ?? $this->viewPath;
264 18
        $file     = ! empty($viewPath) ? str_replace('/', DS, rtrim($viewPath, '/\\') . DS . ltrim($view, '/\\')) : $view;
265
266 18
        $file = Helpers::ensureExt($file, $ext);
267
268
        if (! is_file($file) && $this->locator instanceof LocatorInterface) {
269 18
            $file = $this->locator->locateFile($view, 'Views', $ext);
270
        }
271
272 18
        $file = realpath($file);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $path of realpath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

272
        $file = realpath(/** @scrutinizer ignore-type */ $file);
Loading history...
273
274
        // locateFile renverra une chaîne vide si le fichier est introuvable.
275
        if (! is_file($file)) {
276 4
            throw ViewException::invalidFile($view);
277
        }
278
279 18
        return $file;
280
    }
281
282
    /**
283
     * Construit la sortie en fonction d'un nom de fichier et de tout données déjà définies.
284
     *
285
     * Options valides :
286
     * - cache Nombre de secondes à mettre en cache pour
287
     * - cache_name Nom à utiliser pour le cache
288
     *
289
     * @param string     $view     Nom de fichier de la source de la vue
290
     * @param array|null $options  Réservé à des utilisations tierces car
291
     *                             il peut être nécessaire de transmettre des
292
     *                             informations supplémentaires à d'autres moteurs de modèles.
293
     * @param bool|null  $saveData Si vrai, enregistre les données pour les appels suivants,
294
     *                             si faux, nettoie les données après affichage,
295
     *                             si null, utilise le paramètre de configuration.
296
     */
297
    abstract public function render(string $view, ?array $options = null, ?bool $saveData = null): string;
298
}
299