Passed
Pull Request — master (#72)
by Wilmer
01:24
created

View::getDefaultExtension()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
ccs 0
cts 2
cp 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Yiisoft\View;
5
6
use Psr\EventDispatcher\EventDispatcherInterface;
7
use Psr\Log\LoggerInterface;
8
use Yiisoft\I18n\Locale;
9
use Yiisoft\View\Event\AfterRender;
10
use Yiisoft\View\Event\BeforeRender;
11
use Yiisoft\View\Event\PageBegin;
12
use Yiisoft\View\Event\PageEnd;
13
use Yiisoft\View\Exception\ViewNotFoundException;
14
15
/**
16
 * View represents a view object in the MVC pattern.
17
 *
18
 * View provides a set of methods (e.g. {@see render()}) for rendering purpose.
19
 *
20
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
21
 */
22
class View implements DynamicContentAwareInterface
23
{
24
    /**
25
     * @var string $basePath view path
26
     */
27
    private string $basePath;
28
29
    /**
30
     * @var array a list of named output blocks. The keys are the block names and the values are the corresponding block
31
     * content. You can call {@see beginBlock()} and {@see endBlock()} to capture small fragments of a view.
32
     * They can be later accessed somewhere else through this property.
33
     */
34
    private array $blocks;
35
36
    /**
37
     * @var ViewContextInterface the context under which the {@see {renderFile()} method is being invoked.
38
     */
39
    private ?ViewContextInterface $context = null;
40
41
    /**
42
     * @var string the default view file extension. This will be appended to view file names if they don't have file
43
     * extensions.
44
     */
45
    private string $defaultExtension = 'php';
46
47
    /**
48
     * @var array custom parameters that are shared among view templates.
49
     */
50
    private array $defaultParameters = [];
51
52
    /**
53
     * @var EventDispatcherInterface $eventDispatcher
54
     */
55
    protected EventDispatcherInterface $eventDispatcher;
56
57
    /**
58
     * @var array a list of available renderers indexed by their corresponding supported file extensions. Each renderer
59
     * may be a view renderer object or the configuration for creating the renderer object. For example, the
60
     * following configuration enables the Twig view renderer:
61
     *
62
     * ```php
63
     * [
64
     *     'twig' => ['__class' => \Yiisoft\Yii\Twig\ViewRenderer::class],
65
     * ]
66
     * ```
67
     *
68
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered
69
     * via PhpTemplateRenderer.
70
     */
71
    protected array $renderers = [];
72
73
    /**
74
     * @var Theme the theme object.
75
     */
76
    protected Theme $theme;
77
78
    /**
79
     * @var DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
80
     */
81
    private $cacheStack = [];
82
83
    /**
84
     * @var array a list of placeholders for embedding dynamic contents.
85
     */
86
    private array $dynamicPlaceholders = [];
87
88
    /**
89
     * @var string $language
90
     */
91
    private string $language = 'en';
92
93
    /**
94
     * @var LoggerInterface $logger
95
     */
96
    private LoggerInterface $logger;
97
98
    /**
99
     * @var string $sourceLanguage
100
     */
101
    private string $sourceLanguage = 'en';
102
103
    /**
104
     * @var Locale source locale used to find localized view file.
105
     */
106
    private $sourceLocale;
107
108
    /**
109
     * @var array the view files currently being rendered. There may be multiple view files being
110
     * rendered at a moment because one view may be rendered within another.
111
     */
112
    private array $viewFiles = [];
113
114 16
    public function __construct(string $basePath, Theme $theme, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
115
    {
116 16
        $this->basePath = $basePath;
117 16
        $this->theme = $theme;
118 16
        $this->eventDispatcher = $eventDispatcher;
119 16
        $this->logger = $logger;
120
    }
121
122
    public function getBasePath(): string
123
    {
124
        return $this->basePath;
125
    }
126
127
    public function setRenderers(array $renderers): void
128
    {
129
        $this->renderers = $renderers;
130
    }
131
132
    public function setSourceLanguage(string $language): void
133
    {
134
        $this->sourceLanguage = $language;
135
    }
136
137
    public function setLanguage(string $language): void
138
    {
139
        $this->language = $language;
140
    }
141
142
    public function setContext(ViewContextInterface $context): void
143
    {
144
        $this->context = $context;
145
    }
146
147
    public function getDefaultExtension(): string
148
    {
149
        return $this->defaultExtension;
150
    }
151
152
    public function setDefaultExtension(string $defaultExtension): void
153
    {
154
        $this->defaultExtension = $defaultExtension;
155
    }
156
157
    public function getDefaultParameters(): array
158
    {
159
        return $this->defaultParameters;
160
    }
161
162 2
    public function setDefaultParameters(array $defaultParameters): void
163
    {
164 2
        $this->defaultParameters = $defaultParameters;
165
    }
166
167
    /**
168
     * {@see blocks}
169
     *
170
     * @param string $id
171
     * @param string $value
172
     *
173
     * @return void
174
     */
175
    public function setBlocks(string $id, string $value): void
176
    {
177
        $this->blocks[$id] = $value;
178
    }
179
180
    /**
181
     * {@see blocks}
182
     *
183
     * @param string $value
184
     *
185
     * @return string
186
     */
187
    public function getBlock(string $value): string
188
    {
189
        if (isset($this->blocks[$value])) {
190
            return $this->blocks[$value];
191
        }
192
193
        throw new \InvalidArgumentException('Block: ' . $value.  ' not found.');
194
    }
195
196
    /**
197
     * Renders a view.
198
     *
199
     * The view to be rendered can be specified in one of the following formats:
200
     *
201
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
202
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
203
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
204
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
205
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
206
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
207
     *   looked for under the {@see ViewContextInterface::getViewPath()|view path} of the view `$context`.
208
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
209
     *   being rendered (i.e., this happens when rendering a view within another view).
210
     *
211
     * @param string $view the view name.
212
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
213
     * file.
214
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
215
     * [[context]] in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate
216
     * the view file corresponding to a relative view name.
217
     *
218
     * @return string the rendering result
219
     *
220
     * @throws InvalidCallException  if the view cannot be resolved.
221
     * @throws ViewNotFoundException if the view file does not exist.
222
     * @throws \Throwable
223
     *
224
     * {@see renderFile()}
225
     */
226 4
    public function render(string $view, array $parameters = [], ?ViewContextInterface $context = null): string
227
    {
228 4
        $viewFile = $this->findTemplateFile($view, $context);
229
230 4
        return $this->renderFile($viewFile, $parameters, $context);
231
    }
232
233
    /**
234
     * Finds the view file based on the given view name.
235
     *
236
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
237
     * {@see render()} on how to specify this parameter.
238
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
239
     * [[context]] in the view. If the context implements [[ViewContextInterface]], it may also be used to locate the
240
     * view file corresponding to a relative view name.
241
     *
242
     * @throws InvalidCallException if a relative view name is given while there is no active context to determine the
243
     * corresponding view file.
244
     *
245
     * @return string the view file path. Note that the file may not exist.
246
     */
247 4
    protected function findTemplateFile(string $view, ?ViewContextInterface $context = null): string
248
    {
249 4
        if (strncmp($view, '//', 2) === 0) {
250
            // path relative to basePath e.g. "//layouts/main"
251 4
            $file = $this->basePath . '/' . ltrim($view, '/');
252 1
        } elseif ($context instanceof ViewContextInterface) {
253
            // path provided by context
254
            $file = $context->getViewPath() . '/' . $view;
255 1
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
256
            // path relative to currently rendered view
257 1
            $file = dirname($currentViewFile) . '/' . $view;
0 ignored issues
show
Bug introduced by
It seems like $currentViewFile can also be of type true; however, parameter $path of dirname() 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

257
            $file = dirname(/** @scrutinizer ignore-type */ $currentViewFile) . '/' . $view;
Loading history...
258
        } else {
259
            throw new \RuntimeException("Unable to resolve view file for view '$view': no active view context.");
260
        }
261
262 4
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
263 1
            return $file;
264
        }
265
266 3
        $path = $file . '.' . $this->defaultExtension;
267
268 3
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
269
            $path = $file . '.php';
270
        }
271
272 3
        return $path;
273
    }
274
275
    /**
276
     * Renders a view file.
277
     *
278
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
279
     * is available.
280
     *
281
     * If {@see renderers|renderer} is enabled (not null), the method will use it to render the view file. Otherwise,
282
     * it will simply include the view file as a normal PHP file, capture its output and
283
     * return it as a string.
284
     *
285
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
286
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
287
     * file.
288
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
289
     * existing [[context]] will be used.
290
     *
291
     * @return string the rendering result
292
     * @throws \Throwable
293
     *
294
     * @throws ViewNotFoundException if the view file does not exist
295
     */
296 7
    public function renderFile(string $viewFile, array $parameters = [], ?ViewContextInterface $context = null): string
297
    {
298 7
        $parameters = array_merge($this->defaultParameters, $parameters);
299
300
        // TODO: these two match now
301 7
        $requestedFile = $viewFile;
302
303 7
        if (!empty($this->theme)) {
304 7
            $viewFile = $this->theme->applyTo($viewFile);
305
        }
306
307 7
        if (is_file($viewFile)) {
308 7
            $viewFile = $this->localize($viewFile);
309
        } else {
310
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
311
        }
312
313 7
        $oldContext = $this->context;
314 7
        if ($context !== null) {
315
            $this->context = $context;
316
        }
317 7
        $output = '';
318 7
        $this->viewFiles[] = [
319 7
            'resolved' => $viewFile,
320 7
            'requested' => $requestedFile,
321
        ];
322
323 7
        if ($this->beforeRender($viewFile, $parameters)) {
324 7
            $this->logger->debug("Rendering view file: $viewFile");
325 7
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
326 7
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
327 7
            $output = $renderer->render($this, $viewFile, $parameters);
328
329 7
            $output = $this->afterRender($viewFile, $parameters, $output);
330
        }
331
332 7
        array_pop($this->viewFiles);
333 7
        $this->context = $oldContext;
334
335 7
        return $output;
336
    }
337
338
    /**
339
     * Returns the localized version of a specified file.
340
     *
341
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
342
     * for under the subdirectory whose name is the same as the language code. For example, given the file
343
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
344
     * If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php".
345
     * If it is not found as well the original file will be returned.
346
     *
347
     * If the target and the source language codes are the same, the original file will be returned.
348
     *
349
     * @param string $file the original file
350
     * @param string|null $language the target language that the file should be localized to.
351
     * @param string|null $sourceLanguage the language that the original file is in.
352
     *
353
     * @return string the matching localized file, or the original file if the localized version is not found.
354
     * If the target and the source language codes are the same, the original file will be returned.
355
     */
356 8
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
357
    {
358 8
        $language = $language ?? $this->language;
359 8
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
360
361 8
        if ($language === $sourceLanguage) {
362 8
            return $file;
363
        }
364 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
365 1
        if (is_file($desiredFile)) {
366 1
            return $desiredFile;
367
        }
368
369
        $language = substr($language, 0, 2);
370
        if ($language === $sourceLanguage) {
371
            return $file;
372
        }
373
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
374
375
        return is_file($desiredFile) ? $desiredFile : $file;
376
    }
377
378
    /**
379
     * @return string|bool the view file currently being rendered. False if no view file is being rendered.
380
     */
381 3
    public function getViewFile()
382
    {
383 3
        return empty($this->viewFiles) ? false : end($this->viewFiles)['resolved'];
384
    }
385
386
    /**
387
     * @return string|bool the requested view currently being rendered. False if no view file is being rendered.
388
     */
389 1
    protected function getRequestedViewFile()
390
    {
391 1
        return empty($this->viewFiles) ? false : end($this->viewFiles)['requested'];
392
    }
393
394
    /**
395
     * This method is invoked right before {@see renderFile()} renders a view file.
396
     *
397
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
398
     * you call the parent implementation first.
399
     *
400
     * @param string $viewFile the view file to be rendered.
401
     * @param array $parameters the parameter array passed to the {@see render()} method.
402
     *
403
     * @return bool whether to continue rendering the view file.
404
     */
405 7
    public function beforeRender(string $viewFile, array $parameters): bool
406
    {
407 7
        $event = new BeforeRender($viewFile, $parameters);
408 7
        $event = $this->eventDispatcher->dispatch($event);
409
410 7
        return !$event->isPropagationStopped();
411
    }
412
413
    /**
414
     * This method is invoked right after {@see renderFile()} renders a view file.
415
     *
416
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
417
     * call the parent implementation first.
418
     *
419
     * @param string $viewFile the view file being rendered.
420
     * @param array $parameters the parameter array passed to the {@see render()} method.
421
     * @param string $output the rendering result of the view file. Updates to this parameter
422
     * will be passed back and returned by {@see renderFile()}.
423
     */
424 7
    public function afterRender(string $viewFile, array $parameters, &$output): string
425
    {
426 7
        $event = new AfterRender($viewFile, $parameters, $output);
427 7
        $event = $this->eventDispatcher->dispatch($event);
428
429 7
        return $event->getResult();
430
    }
431
432
    /**
433
     * Renders dynamic content returned by the given PHP statements.
434
     *
435
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
436
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
437
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
438
     * statement:.
439
     *
440
     * ```php
441
     * <?= $this->renderDynamic('return foo($myVar);', [
442
     *     'myVar' => $model->getMyComplexVar(),
443
     * ]) ?>
444
     * ```
445
     *
446
     * @param string $statements the PHP statements for generating the dynamic content.
447
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
448
     * available in the $statement context. The parameters will be stored in the cache and be reused
449
     * each time $statement is executed. You should make sure, that these are safely serializable.
450
     *
451
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
452
     *                cache currently.
453
     */
454
    public function renderDynamic(string $statements, array $parameters = []): string
455
    {
456
        if (!empty($parameters)) {
457
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
458
        }
459
460
        if (!empty($this->cacheStack)) {
461
            $n = count($this->dynamicPlaceholders);
462
            $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
463
            $this->addDynamicPlaceholder($placeholder, $statements);
464
465
            return $placeholder;
466
        }
467
468
        return $this->evaluateDynamicContent($statements);
469
    }
470
471
    /**
472
     * Get source locale.
473
     *
474
     * @return Locale
475
     */
476
    public function getSourceLocale(): Locale
477
    {
478
        if ($this->sourceLocale === null) {
479
            $this->sourceLocale = Locale::create('en-US');
0 ignored issues
show
Bug introduced by
The method create() does not exist on Yiisoft\I18n\Locale. ( Ignorable by Annotation )

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

479
            /** @scrutinizer ignore-call */ 
480
            $this->sourceLocale = Locale::create('en-US');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
480
        }
481
482
        return $this->sourceLocale;
483
    }
484
485
    /**
486
     * Set source locale.
487
     *
488
     * @param string $locale
489
     * @return self
490
     */
491
    public function setSourceLocale(string $locale): self
492
    {
493
        $this->sourceLocale = Locale::create($locale);
494
495
        return $this;
496
    }
497
498
    public function getDynamicPlaceholders(): array
499
    {
500
        return $this->dynamicPlaceholders;
501
    }
502
503
    public function setDynamicPlaceholders(array $placeholders): void
504
    {
505
        $this->dynamicPlaceholders = $placeholders;
506
    }
507
508
    public function addDynamicPlaceholder(string $placeholder, string $statements): void
509
    {
510
        foreach ($this->cacheStack as $cache) {
511
            $cache->addDynamicPlaceholder($placeholder, $statements);
512
        }
513
514
        $this->dynamicPlaceholders[$placeholder] = $statements;
515
    }
516
517
    /**
518
     * Evaluates the given PHP statements.
519
     *
520
     * This method is mainly used internally to implement dynamic content feature.
521
     *
522
     * @param string $statements the PHP statements to be evaluated.
523
     *
524
     * @return mixed the return value of the PHP statements.
525
     */
526
    public function evaluateDynamicContent(string $statements)
527
    {
528
        return eval($statements);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
529
    }
530
531
    /**
532
     * Returns a list of currently active dynamic content class instances.
533
     *
534
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
535
     */
536
    public function getDynamicContents(): array
537
    {
538
        return $this->cacheStack;
539
    }
540
541
    /**
542
     * Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class
543
     * instances.
544
     *
545
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
546
     *
547
     * @return void
548
     */
549
    public function pushDynamicContent(DynamicContentAwareInterface $instance): void
550
    {
551
        $this->cacheStack[] = $instance;
552
    }
553
554
    /**
555
     * Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class
556
     * instances.
557
     *
558
     * @return void
559
     */
560
    public function popDynamicContent(): void
561
    {
562
        array_pop($this->cacheStack);
563
    }
564
565
    /**
566
     * Marks the beginning of a page.
567
     *
568
     * @return void
569
     */
570 3
    public function beginPage(): void
571
    {
572 3
        ob_start();
573 3
        ob_implicit_flush(0);
574
575 3
        $this->eventDispatcher->dispatch(new PageBegin($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageBegin::__construct() 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

575
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
576
    }
577
578
    /**
579
     * Marks the ending of a page.
580
     *
581
     * @return void
582
     */
583
    public function endPage(): void
584
    {
585
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageEnd::__construct() 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

585
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
586
        ob_end_flush();
587
    }
588
}
589