Passed
Pull Request — master (#77)
by
unknown
01:40
created

View::setDefaultExtension()   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 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\Log\LoggerInterface;
9
use Yiisoft\I18n\Locale;
10
use Yiisoft\View\Event\AfterRender;
11
use Yiisoft\View\Event\BeforeRender;
12
use Yiisoft\View\Event\PageBegin;
13
use Yiisoft\View\Event\PageEnd;
14
use Yiisoft\View\Exception\ViewNotFoundException;
15
16
/**
17
 * View represents a view object in the MVC pattern.
18
 *
19
 * View provides a set of methods (e.g. {@see render()}) for rendering purpose.
20
 *
21
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
22
 */
23
class View implements DynamicContentAwareInterface
24
{
25
    /**
26
     * @var string $basePath view path
27
     */
28
    private string $basePath;
29
30
    /**
31
     * @var array a list of named output blocks. The keys are the block names and the values are the corresponding block
32
     * content. You can call {@see beginBlock()} and {@see endBlock()} to capture small fragments of a view.
33
     * They can be later accessed somewhere else through this property.
34
     */
35
    private array $blocks;
36
37
    /**
38
     * @var ViewContextInterface the context under which the {@see {renderFile()} method is being invoked.
39
     */
40
    private ?ViewContextInterface $context = null;
41
42
    /**
43
     * @var string the default view file extension. This will be appended to view file names if they don't have file
44
     * extensions.
45
     */
46
    private string $defaultExtension = 'php';
47
48
    /**
49
     * @var array custom parameters that are shared among view templates.
50
     */
51
    private array $defaultParameters = [];
52
53
    /**
54
     * @var EventDispatcherInterface $eventDispatcher
55
     */
56
    protected EventDispatcherInterface $eventDispatcher;
57
58
    /**
59
     * @var array a list of available renderers indexed by their corresponding supported file extensions. Each renderer
60
     * may be a view renderer object or the configuration for creating the renderer object. For example, the
61
     * following configuration enables the Twig view renderer:
62
     *
63
     * ```php
64
     * [
65
     *     'twig' => ['__class' => \Yiisoft\Yii\Twig\ViewRenderer::class],
66
     * ]
67
     * ```
68
     *
69
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered
70
     * via PhpTemplateRenderer.
71
     */
72
    protected array $renderers = [];
73
74
    /**
75
     * @var Theme the theme object.
76
     */
77
    protected Theme $theme;
78
79
    /**
80
     * @var DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
81
     */
82
    private $cacheStack = [];
83
84
    /**
85
     * @var array a list of placeholders for embedding dynamic contents.
86
     */
87
    private array $dynamicPlaceholders = [];
88
89
    /**
90
     * @var string $language
91
     */
92
    private string $language = 'en';
93
94
    /**
95
     * @var LoggerInterface $logger
96
     */
97
    private LoggerInterface $logger;
98
99
    /**
100
     * @var string $sourceLanguage
101
     */
102
    private string $sourceLanguage = 'en';
103
104
    /**
105
     * @var Locale source locale used to find localized view file.
106
     */
107
    private $sourceLocale;
108
109
    private $beginPageIsCalled = false;
110
111
    /**
112
     * @var array the view files currently being rendered. There may be multiple view files being
113
     * rendered at a moment because one view may be rendered within another.
114
     */
115
    private array $viewFiles = [];
116
117 21
    public function __construct(string $basePath, Theme $theme, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
118
    {
119 21
        $this->basePath = $basePath;
120 21
        $this->theme = $theme;
121 21
        $this->eventDispatcher = $eventDispatcher;
122 21
        $this->logger = $logger;
123
    }
124
125
    public function getBasePath(): string
126
    {
127
        return $this->basePath;
128
    }
129
130
    public function setRenderers(array $renderers): void
131
    {
132
        $this->renderers = $renderers;
133
    }
134
135
    public function setSourceLanguage(string $language): void
136
    {
137
        $this->sourceLanguage = $language;
138
    }
139
140
    public function setLanguage(string $language): void
141
    {
142
        $this->language = $language;
143
    }
144
145
    public function setContext(ViewContextInterface $context): void
146
    {
147
        $this->context = $context;
148
    }
149
150
    public function getDefaultExtension(): string
151
    {
152
        return $this->defaultExtension;
153
    }
154
155
    public function setDefaultExtension(string $defaultExtension): void
156
    {
157
        $this->defaultExtension = $defaultExtension;
158
    }
159
160
    public function getDefaultParameters(): array
161
    {
162
        return $this->defaultParameters;
163
    }
164
165 2
    public function setDefaultParameters(array $defaultParameters): void
166
    {
167 2
        $this->defaultParameters = $defaultParameters;
168
    }
169
170
    /**
171
     * {@see blocks}
172
     *
173
     * @param string $id
174
     * @param string $value
175
     *
176
     * @return void
177
     */
178
    public function setBlocks(string $id, string $value): void
179
    {
180
        $this->blocks[$id] = $value;
181
    }
182
183
    /**
184
     * {@see blocks}
185
     *
186
     * @param string $value
187
     *
188
     * @return string
189
     */
190
    public function getBlock(string $value): string
191
    {
192
        if (isset($this->blocks[$value])) {
193
            return $this->blocks[$value];
194
        }
195
196
        throw new \InvalidArgumentException('Block: ' . $value.  ' not found.');
197
    }
198
199
    /**
200
     * Renders a view.
201
     *
202
     * The view to be rendered can be specified in one of the following formats:
203
     *
204
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
205
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
206
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
207
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
208
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
209
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
210
     *   looked for under the {@see ViewContextInterface::getViewPath()|view path} of the view `$context`.
211
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
212
     *   being rendered (i.e., this happens when rendering a view within another view).
213
     *
214
     * @param string $view the view name.
215
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
216
     * file.
217
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
218
     * [[context]] in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate
219
     * the view file corresponding to a relative view name.
220
     *
221
     * @return string the rendering result
222
     *
223
     * @throws InvalidCallException  if the view cannot be resolved.
224
     * @throws ViewNotFoundException if the view file does not exist.
225
     * @throws \Throwable
226
     *
227
     * {@see renderFile()}
228
     */
229 4
    public function render(string $view, array $parameters = [], ?ViewContextInterface $context = null): string
230
    {
231 4
        $viewFile = $this->findTemplateFile($view, $context);
232
233 4
        return $this->renderFile($viewFile, $parameters, $context);
234
    }
235
236
    /**
237
     * Finds the view file based on the given view name.
238
     *
239
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
240
     * {@see render()} on how to specify this parameter.
241
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
242
     * [[context]] in the view. If the context implements [[ViewContextInterface]], it may also be used to locate the
243
     * view file corresponding to a relative view name.
244
     *
245
     * @throws InvalidCallException if a relative view name is given while there is no active context to determine the
246
     * corresponding view file.
247
     *
248
     * @return string the view file path. Note that the file may not exist.
249
     */
250 4
    protected function findTemplateFile(string $view, ?ViewContextInterface $context = null): string
251
    {
252 4
        if (strncmp($view, '//', 2) === 0) {
253
            // path relative to basePath e.g. "//layouts/main"
254 4
            $file = $this->basePath . '/' . ltrim($view, '/');
255 1
        } elseif ($context instanceof ViewContextInterface) {
256
            // path provided by context
257
            $file = $context->getViewPath() . '/' . $view;
258 1
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== null) {
259
            // path relative to currently rendered view
260 1
            $file = dirname($currentViewFile) . '/' . $view;
261
        } else {
262
            throw new \RuntimeException("Unable to resolve view file for view '$view': no active view context.");
263
        }
264
265 4
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
266 1
            return $file;
267
        }
268
269 3
        $path = $file . '.' . $this->defaultExtension;
270
271 3
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
272
            $path = $file . '.php';
273
        }
274
275 3
        return $path;
276
    }
277
278
    /**
279
     * Renders a view file.
280
     *
281
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
282
     * is available.
283
     *
284
     * If {@see renderers|renderer} is enabled (not null), the method will use it to render the view file. Otherwise,
285
     * it will simply include the view file as a normal PHP file, capture its output and
286
     * return it as a string.
287
     *
288
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
289
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
290
     * file.
291
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
292
     * existing [[context]] will be used.
293
     *
294
     * @return string the rendering result
295
     * @throws \Throwable
296
     *
297
     * @throws ViewNotFoundException if the view file does not exist
298
     */
299 7
    public function renderFile(string $viewFile, array $parameters = [], ?ViewContextInterface $context = null): string
300
    {
301 7
        $parameters = array_merge($this->defaultParameters, $parameters);
302
303
        // TODO: these two match now
304 7
        $requestedFile = $viewFile;
305
306 7
        if (!empty($this->theme)) {
307 7
            $viewFile = $this->theme->applyTo($viewFile);
308
        }
309
310 7
        if (is_file($viewFile)) {
311 7
            $viewFile = $this->localize($viewFile);
312
        } else {
313
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
314
        }
315
316 7
        $oldContext = $this->context;
317 7
        if ($context !== null) {
318
            $this->context = $context;
319
        }
320 7
        $output = '';
321 7
        $this->viewFiles[] = [
322 7
            'resolved' => $viewFile,
323 7
            'requested' => $requestedFile,
324
        ];
325
326 7
        if ($this->beforeRender($viewFile, $parameters)) {
327 7
            $this->logger->debug("Rendering view file: $viewFile");
328 7
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
329 7
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
330 7
            $output = $renderer->render($this, $viewFile, $parameters);
331
332 7
            $output = $this->afterRender($viewFile, $parameters, $output);
333
        }
334
335 7
        array_pop($this->viewFiles);
336 7
        $this->context = $oldContext;
337
338 7
        return $output;
339
    }
340
341
    /**
342
     * Returns the localized version of a specified file.
343
     *
344
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
345
     * for under the subdirectory whose name is the same as the language code. For example, given the file
346
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
347
     * 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".
348
     * If it is not found as well the original file will be returned.
349
     *
350
     * If the target and the source language codes are the same, the original file will be returned.
351
     *
352
     * @param string $file the original file
353
     * @param string|null $language the target language that the file should be localized to.
354
     * @param string|null $sourceLanguage the language that the original file is in.
355
     *
356
     * @return string the matching localized file, or the original file if the localized version is not found.
357
     * If the target and the source language codes are the same, the original file will be returned.
358
     */
359 8
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
360
    {
361 8
        $language = $language ?? $this->language;
362 8
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
363
364 8
        if ($language === $sourceLanguage) {
365 8
            return $file;
366
        }
367 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
368 1
        if (is_file($desiredFile)) {
369 1
            return $desiredFile;
370
        }
371
372
        $language = substr($language, 0, 2);
373
        if ($language === $sourceLanguage) {
374
            return $file;
375
        }
376
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
377
378
        return is_file($desiredFile) ? $desiredFile : $file;
379
    }
380
381
    /**
382
     * @return string|null the view file currently being rendered. NULL if no view file is being rendered.
383
     */
384 6
    public function getViewFile(): ?string
385
    {
386 6
        return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
387
    }
388
389
    /**
390
     * @return string|null the requested view currently being rendered. NULL if no view file is being rendered.
391
     */
392 1
    protected function getRequestedViewFile(): ?string
393
    {
394 1
        return empty($this->viewFiles) ? null : end($this->viewFiles)['requested'];
395
    }
396
397
    /**
398
     * This method is invoked right before {@see renderFile()} renders a view file.
399
     *
400
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
401
     * you call the parent implementation first.
402
     *
403
     * @param string $viewFile the view file to be rendered.
404
     * @param array $parameters the parameter array passed to the {@see render()} method.
405
     *
406
     * @return bool whether to continue rendering the view file.
407
     */
408 7
    public function beforeRender(string $viewFile, array $parameters): bool
409
    {
410 7
        $event = new BeforeRender($viewFile, $parameters);
411 7
        $event = $this->eventDispatcher->dispatch($event);
412
413 7
        return !$event->isPropagationStopped();
414
    }
415
416
    /**
417
     * This method is invoked right after {@see renderFile()} renders a view file.
418
     *
419
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
420
     * call the parent implementation first.
421
     *
422
     * @param string $viewFile the view file being rendered.
423
     * @param array $parameters the parameter array passed to the {@see render()} method.
424
     * @param string $output the rendering result of the view file. Updates to this parameter
425
     * will be passed back and returned by {@see renderFile()}.
426
     */
427 7
    public function afterRender(string $viewFile, array $parameters, &$output): string
428
    {
429 7
        $event = new AfterRender($viewFile, $parameters, $output);
430 7
        $event = $this->eventDispatcher->dispatch($event);
431
432 7
        return $event->getResult();
433
    }
434
435
    /**
436
     * Renders dynamic content returned by the given PHP statements.
437
     *
438
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
439
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
440
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
441
     * statement:.
442
     *
443
     * ```php
444
     * <?= $this->renderDynamic('return foo($myVar);', [
445
     *     'myVar' => $model->getMyComplexVar(),
446
     * ]) ?>
447
     * ```
448
     *
449
     * @param string $statements the PHP statements for generating the dynamic content.
450
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
451
     * available in the $statement context. The parameters will be stored in the cache and be reused
452
     * each time $statement is executed. You should make sure, that these are safely serializable.
453
     *
454
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
455
     *                cache currently.
456
     */
457
    public function renderDynamic(string $statements, array $parameters = []): string
458
    {
459
        if (!empty($parameters)) {
460
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
461
        }
462
463
        if (!empty($this->cacheStack)) {
464
            $n = count($this->dynamicPlaceholders);
465
            $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
466
            $this->addDynamicPlaceholder($placeholder, $statements);
467
468
            return $placeholder;
469
        }
470
471
        return $this->evaluateDynamicContent($statements);
472
    }
473
474
    /**
475
     * Get source locale.
476
     *
477
     * @return Locale
478
     */
479
    public function getSourceLocale(): Locale
480
    {
481
        if ($this->sourceLocale === null) {
482
            $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

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

595
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
596
        ob_end_flush();
597
        $this->setBeginPageIsCalled(false);
598
    }
599
600 5
    protected function getBeginPageIsCalled(): bool
601
    {
602 5
        return $this->beginPageIsCalled;
603
    }
604
605 3
    protected function setBeginPageIsCalled(bool $set): void
606
    {
607 3
        $this->beginPageIsCalled = $set;
608
    }
609
}
610