0 follower

Trait Yiisoft\View\ViewTrait

Implemented byYiisoft\View\View, Yiisoft\View\WebView

ViewTrait could be used as a base implementation of {@see ViewInterface}.

Public Methods

Hide inherited methods

Method Description Defined By
addToParameter() Add values to end of common array parameter. If specified parameter does not exist or him is not array, then parameter will be added as empty array. Yiisoft\View\ViewTrait
clear() Clears the data for working with the event loop. Yiisoft\View\ViewTrait
getBasePath() Gets the base path to the view directory. Yiisoft\View\ViewTrait
getBlock() Gets content of the block by ID. Yiisoft\View\ViewTrait
getFallbackExtensions() Gets the fallback view file extension. Yiisoft\View\ViewTrait
getLocale() Get the specified locale code. Yiisoft\View\ViewTrait
getParameter() Gets a common parameter value by ID. Yiisoft\View\ViewTrait
getPlaceholderSignature() Gets the placeholder signature. Yiisoft\View\ViewTrait
getTheme() Gets the theme instance, or null if no theme has been set. Yiisoft\View\ViewTrait
getViewFile() Gets the view file currently being rendered. Yiisoft\View\ViewTrait
hasBlock() Checks the existence of a content block by ID. Yiisoft\View\ViewTrait
hasParameter() Checks the existence of a common parameter by ID. Yiisoft\View\ViewTrait
localize() Returns the localized version of a specified file. Yiisoft\View\ViewTrait
removeBlock() Removes a content block. Yiisoft\View\ViewTrait
removeParameter() Removes a common parameter. Yiisoft\View\ViewTrait
render() Renders a view. Yiisoft\View\ViewTrait
setBlock() Sets a content block. Yiisoft\View\ViewTrait
setLocale() Set the specified locale code. Yiisoft\View\ViewTrait
setParameter() Sets a common parameter that is accessible in all view templates. Yiisoft\View\ViewTrait
setParameters() Sets a common parameters that is accessible in all view templates. Yiisoft\View\ViewTrait
setTheme() Set the specified theme instance. Yiisoft\View\ViewTrait
withBasePath() Returns a new instance with specified base path to the view directory. Yiisoft\View\ViewTrait
withContext() Returns a new instance with the specified view context instance. Yiisoft\View\ViewTrait
withContextPath() Returns a new instance with the specified view context path. Yiisoft\View\ViewTrait
withFallbackExtension() Returns a new instance with the specified fallback view file extension. Yiisoft\View\ViewTrait
withLocale() Set the specified locale code. Yiisoft\View\ViewTrait
withPlaceholderSalt() Returns a new instance with specified salt for the placeholder signature {@see getPlaceholderSignature()}. Yiisoft\View\ViewTrait
withRenderers() Returns a new instance with the specified renderers. Yiisoft\View\ViewTrait
withSourceLocale() Returns a new instance with the specified source locale. Yiisoft\View\ViewTrait
withTheme() Yiisoft\View\ViewTrait

Protected Methods

Hide inherited methods

Method Description Defined By
createAfterRenderEvent() Creates an event that occurs after rendering. Yiisoft\View\ViewTrait
createBeforeRenderEvent() Creates an event that occurs before rendering. Yiisoft\View\ViewTrait

Method Details

Hide inherited methods

addToParameter() public method

Add values to end of common array parameter. If specified parameter does not exist or him is not array, then parameter will be added as empty array.

public Yiisoft\View\ViewTrait addToParameter ( string $id, mixed $value )
$id string

The unique identifier of the parameter.

$value mixed

Value(s) for add to end of array parameter.

throws InvalidArgumentException

When specified parameter already exists and is not an array.

                public function addToParameter(string $id, mixed ...$value): static
{
    $this->state->addToParameter($id, ...$value);
    return $this;
}

            
clear() public method

Clears the data for working with the event loop.

public void clear ( )

                public function clear(): void
{
    $this->viewFiles = [];
    $this->state->clear();
    $this->localeState = new LocaleState();
    $this->themeState = new ThemeState();
}

            
createAfterRenderEvent() protected abstract method

Creates an event that occurs after rendering.

protected abstract Yiisoft\View\Event\AfterRenderEventInterface createAfterRenderEvent ( string $viewFile, array $parameters, string $result )
$viewFile string

The view file being rendered.

$parameters array

The parameter array passed to the {@see \Yiisoft\View\render()} method.

$result string

The rendering result of the view file.

return Yiisoft\View\Event\AfterRenderEventInterface

The event instance.

                abstract protected function createAfterRenderEvent(
    string $viewFile,
    array $parameters,
    string $result
): AfterRenderEventInterface;

            
createBeforeRenderEvent() protected abstract method

Creates an event that occurs before rendering.

protected abstract \Psr\EventDispatcher\StoppableEventInterface createBeforeRenderEvent ( string $viewFile, array $parameters )
$viewFile string

The view file to be rendered.

$parameters array

The parameter array passed to the {@see \Yiisoft\View\render()} method.

return \Psr\EventDispatcher\StoppableEventInterface

The stoppable event instance.

                abstract protected function createBeforeRenderEvent(string $viewFile, array $parameters): StoppableEventInterface;

            
getBasePath() public method

Gets the base path to the view directory.

public string getBasePath ( )
return string

The base view path.

                public function getBasePath(): string
{
    if ($this->basePath === null) {
        throw new LogicException('The base path is not set.');
    }
    return $this->basePath;
}

            
getBlock() public method

Gets content of the block by ID.

public string getBlock ( string $id )
$id string

The unique identifier of the block.

return string

The content of the block.

                public function getBlock(string $id): string
{
    return $this->state->getBlock($id);
}

            
getFallbackExtensions() public method

Gets the fallback view file extension.

public string[] getFallbackExtensions ( )
return string[]

The fallback view file extension.

                public function getFallbackExtensions(): array
{
    return $this->fallbackExtensions;
}

            
getLocale() public method

Get the specified locale code.

public string getLocale ( )
return string

The locale code.

                public function getLocale(): string
{
    return $this->localeState->getLocale();
}

            
getParameter() public method

Gets a common parameter value by ID.

public mixed getParameter ( string $id, mixed $default )
$id string

The unique identifier of the parameter.

$default mixed

The default value to be returned if the specified parameter does not exist.

return mixed

The value of the parameter.

throws InvalidArgumentException

If specified parameter does not exist and not passed default value.

                public function getParameter(string $id, mixed ...$default): mixed
{
    return call_user_func([$this->state, 'getParameter'], $id, ...$default);
}

            
getPlaceholderSignature() public method

Gets the placeholder signature.

public string getPlaceholderSignature ( )
return string

The placeholder signature.

                public function getPlaceholderSignature(): string
{
    return $this->placeholderSignature;
}

            
getTheme() public method

Gets the theme instance, or null if no theme has been set.

public Yiisoft\View\Theme|null getTheme ( )
return Yiisoft\View\Theme|null

The theme instance, or null if no theme has been set.

                public function getTheme(): ?Theme
{
    return $this->themeState->getTheme();
}

            
getViewFile() public method

Gets the view file currently being rendered.

public string|null getViewFile ( )
return string|null

The view file currently being rendered. null if no view file is being rendered.

                public function getViewFile(): ?string
{
    /** @psalm-suppress InvalidArrayOffset */
    return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
}

            
hasBlock() public method

Checks the existence of a content block by ID.

public boolean hasBlock ( string $id )
$id string

The unique identifier of the block.

return boolean

Whether a content block exists.

                public function hasBlock(string $id): bool
{
    return $this->state->hasBlock($id);
}

            
hasParameter() public method

Checks the existence of a common parameter by ID.

public boolean hasParameter ( string $id )
$id string

The unique identifier of the parameter.

return boolean

Whether a custom parameter that is common for all view templates exists.

                public function hasParameter(string $id): bool
{
    return $this->state->hasParameter($id);
}

            
localize() public method

Returns the localized version of a specified file.

The searching is based on the specified locale code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the locale code. For example, given the file "path/to/view.php" and locale code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a locale code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.

If the target and the source locale codes are the same, the original file will be returned.

public string localize ( string $file, string|null $locale null, string|null $sourceLocale null )
$file string

The original file

$locale string|null

The target locale that the file should be localized to.

$sourceLocale string|null

The locale that the original file is in.

return string

The matching localized file, or the original file if the localized version is not found. If the target and the source locale codes are the same, the original file will be returned.

                public function localize(string $file, ?string $locale = null, ?string $sourceLocale = null): string
{
    $locale ??= $this->localeState->getLocale();
    $sourceLocale ??= $this->sourceLocale;
    if ($locale === $sourceLocale) {
        return $file;
    }
    $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . basename($file);
    if (is_file($desiredFile)) {
        return $desiredFile;
    }
    $locale = substr($locale, 0, 2);
    if ($locale === $sourceLocale) {
        return $file;
    }
    $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . basename($file);
    return is_file($desiredFile) ? $desiredFile : $file;
}

            
removeBlock() public method

Removes a content block.

public Yiisoft\View\ViewTrait removeBlock ( string $id )
$id string

The unique identifier of the block.

                public function removeBlock(string $id): static
{
    $this->state->removeBlock($id);
    return $this;
}

            
removeParameter() public method

Removes a common parameter.

public Yiisoft\View\ViewTrait removeParameter ( string $id )
$id string

The unique identifier of the parameter.

                public function removeParameter(string $id): static
{
    $this->state->removeParameter($id);
    return $this;
}

            
render() public method

Renders a view.

The view to be rendered can be specified in one of the following formats:

  • the absolute path to the view file, e.g. "/path/to/view.php";
  • the name of the view starting with // to join the base path {@see \Yiisoft\View\getBasePath()}, e.g. "//site/index";
  • the name of the view starting with ./ to join the directory containing the view currently being rendered (i.e., this happens when rendering a view within another view), e.g. "./widget";
  • the name of the view starting with ../ to join the parent directory containing the view currently being rendered, e.g. "../_header";
  • the name of the view without the starting //, ./ or ../ (e.g. "site/index"). The corresponding view file will be looked for under the {@see \Yiisoft\View\ViewContextInterface::getViewPath()} of the context set via {@see \Yiisoft\View\withContext()}. If the context instance was not set {@see \Yiisoft\View\withContext()}, it will be looked for under the base path.

Warning: Using .. in view path can lead to accessing unsafe data, e.g., //../../etc/passwd. Ensure that such cases are handled properly.

public string render ( string $view, array $parameters = [] )
$view string

The view name.

$parameters array

The parameters (name-value pairs) that will be extracted and made available in the view file.

return string

The rendering result.

throws LogicException

If the view cannot be resolved.

throws Yiisoft\View\Exception\ViewNotFoundException

If the view file does not exist.

throws Throwable

                public function render(string $view, array $parameters = []): string
{
    $viewFile = $this->findTemplateFile($view);
    $parameters = array_merge($this->state->getParameters(), $parameters);
    // TODO: these two match now
    $requestedFile = $viewFile;
    $theme = $this->getTheme();
    if ($theme !== null) {
        $viewFile = $theme->applyTo($viewFile);
    }
    if (is_file($viewFile)) {
        $viewFile = $this->localize($viewFile);
    } else {
        throw new ViewNotFoundException("The view file \"$viewFile\" does not exist.");
    }
    $output = '';
    $this->viewFiles[] = [
        'resolved' => $viewFile,
        'requested' => $requestedFile,
    ];
    if ($this->beforeRender($viewFile, $parameters)) {
        $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
        $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
        $output = $renderer->render($this, $viewFile, $parameters);
        $output = $this->afterRender($viewFile, $parameters, $output);
    }
    array_pop($this->viewFiles);
    return $output;
}

            
setBlock() public method

Sets a content block.

public Yiisoft\View\ViewTrait setBlock ( string $id, string $content )
$id string

The unique identifier of the block.

$content string

The content of the block.

                public function setBlock(string $id, string $content): static
{
    $this->state->setBlock($id, $content);
    return $this;
}

            
setLocale() public method

Set the specified locale code.

public Yiisoft\View\ViewTrait setLocale ( string $locale )
$locale string

The locale code.

                public function setLocale(string $locale): static
{
    $this->localeState->setLocale($locale);
    return $this;
}

            
setParameter() public method

Sets a common parameter that is accessible in all view templates.

public Yiisoft\View\ViewTrait setParameter ( string $id, mixed $value )
$id string

The unique identifier of the parameter.

$value mixed

The value of the parameter.

                public function setParameter(string $id, mixed $value): static
{
    $this->state->setParameter($id, $value);
    return $this;
}

            
setParameters() public method

Sets a common parameters that is accessible in all view templates.

See also setParameter().

public Yiisoft\View\ViewTrait setParameters ( array $parameters )
$parameters array

Parameters that are common for all view templates.

                public function setParameters(array $parameters): static
{
    $this->state->setParameters($parameters);
    return $this;
}

            
setTheme() public method

Set the specified theme instance.

public Yiisoft\View\ViewTrait setTheme ( Yiisoft\View\Theme|null $theme )
$theme Yiisoft\View\Theme|null

The theme instance or null for reset theme.

                public function setTheme(?Theme $theme): static
{
    $this->themeState->setTheme($theme);
    return $this;
}

            
withBasePath() public method

Returns a new instance with specified base path to the view directory.

public Yiisoft\View\ViewTrait withBasePath ( string|null $basePath )
$basePath string|null

The base path to the view directory.

                public function withBasePath(string|null $basePath): static
{
    $new = clone $this;
    $new->basePath = $basePath;
    return $new;
}

            
withContext() public method

Returns a new instance with the specified view context instance.

public Yiisoft\View\ViewTrait withContext ( Yiisoft\View\ViewContextInterface|null $context )
$context Yiisoft\View\ViewContextInterface|null

The context under which the {@see \Yiisoft\View\render()} method is being invoked.

                public function withContext(ViewContextInterface|null $context): static
{
    $new = clone $this;
    $new->context = $context;
    $new->viewFiles = [];
    return $new;
}

            
withContextPath() public method

Returns a new instance with the specified view context path.

public Yiisoft\View\ViewTrait withContextPath ( string $path )
$path string

The context path under which the {@see \Yiisoft\View\render()} method is being invoked.

                public function withContextPath(string $path): static
{
    return $this->withContext(new ViewContext($path));
}

            
withFallbackExtension() public method

Returns a new instance with the specified fallback view file extension.

public Yiisoft\View\ViewTrait withFallbackExtension ( string $fallbackExtension, string $otherFallbacks )
$fallbackExtension string

The fallback view file extension. Default is {@see \Yiisoft\View\ViewInterface::PHP_EXTENSION}. This will be appended to view file names if they don't exist.

$otherFallbacks string

                public function withFallbackExtension(string $fallbackExtension, string ...$otherFallbacks): static
{
    $new = clone $this;
    $new->fallbackExtensions = [$fallbackExtension, ...array_values($otherFallbacks)];
    return $new;
}

            
withLocale() public method

Set the specified locale code.

public Yiisoft\View\ViewTrait withLocale ( string $locale )
$locale string

The locale code.

                public function withLocale(string $locale): static
{
    $new = clone $this;
    $new->localeState = new LocaleState($locale);
    return $new;
}

            
withPlaceholderSalt() public method

Returns a new instance with specified salt for the placeholder signature {@see getPlaceholderSignature()}.

public Yiisoft\View\ViewTrait withPlaceholderSalt ( string $salt )
$salt string

The placeholder salt.

                public function withPlaceholderSalt(string $salt): static
{
    $new = clone $this;
    $new->setPlaceholderSalt($salt);
    return $new;
}

            
withRenderers() public method

Returns a new instance with the specified renderers.

public Yiisoft\View\ViewTrait withRenderers ( array $renderers )
$renderers array

A list of available renderers indexed by their corresponding supported file extensions.

$view = $view->withRenderers(['twig' => new \Yiisoft\View\Twig\ViewRenderer($environment)]);

If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered via {@see \Yiisoft\View\PhpTemplateRenderer}.

                public function withRenderers(array $renderers): static
{
    $new = clone $this;
    $new->renderers = $renderers;
    return $new;
}

            
withSourceLocale() public method

Returns a new instance with the specified source locale.

public Yiisoft\View\ViewTrait withSourceLocale ( string $locale )
$locale string

The source locale.

                public function withSourceLocale(string $locale): static
{
    $new = clone $this;
    $new->sourceLocale = $locale;
    return $new;
}

            
withTheme() public method

public Yiisoft\View\ViewTrait withTheme ( Yiisoft\View\Theme|null $theme )
$theme Yiisoft\View\Theme|null

                public function withTheme(?Theme $theme): static
{
    $new = clone $this;
    $new->themeState = new ThemeState($theme);
    return $new;
}