This commit is contained in:
Markus
2022-04-28 09:40:10 +02:00
commit 795794f992
9586 changed files with 1146991 additions and 0 deletions

213
system/View/Cell.php Normal file
View File

@@ -0,0 +1,213 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\View\Exceptions\ViewException;
use Config\Services;
use ReflectionException;
use ReflectionMethod;
/**
* Class Cell
*
* A simple class that can call any other class that can be loaded,
* and echo out it's result. Intended for displaying small blocks of
* content within views that can be managed by other libraries and
* not require they are loaded within controller.
*
* Used with the helper function, it's use will look like:
*
* viewCell('\Some\Class::method', 'limit=5 sort=asc', 60, 'cache-name');
*
* Parameters are matched up with the callback method's arguments of the same name:
*
* class Class {
* function method($limit, $sort)
* }
*
* Alternatively, the params will be passed into the callback method as a simple array
* if matching params are not found.
*
* class Class {
* function method(array $params=null)
* }
*/
class Cell
{
/**
* Instance of the current Cache Instance
*
* @var CacheInterface
*/
protected $cache;
/**
* Cell constructor.
*/
public function __construct(CacheInterface $cache)
{
$this->cache = $cache;
}
/**
* Render a cell, returning its body as a string.
*
* @param null $params
*
* @throws ReflectionException
*/
public function render(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string
{
[$class, $method] = $this->determineClass($library);
// Is it cached?
$cacheName = ! empty($cacheName)
? $cacheName
: str_replace(['\\', '/'], '', $class) . $method . md5(serialize($params));
if (! empty($this->cache) && $output = $this->cache->get($cacheName)) {
return $output;
}
// Not cached - so grab it...
$instance = new $class();
if (method_exists($instance, 'initController')) {
$instance->initController(Services::request(), Services::response(), Services::logger());
}
if (! method_exists($instance, $method)) {
throw ViewException::forInvalidCellMethod($class, $method);
}
// Try to match up the parameter list we were provided
// with the parameter name in the callback method.
$paramArray = $this->prepareParams($params);
$refMethod = new ReflectionMethod($instance, $method);
$paramCount = $refMethod->getNumberOfParameters();
$refParams = $refMethod->getParameters();
if ($paramCount === 0) {
if (! empty($paramArray)) {
throw ViewException::forMissingCellParameters($class, $method);
}
$output = $instance->{$method}();
} elseif (($paramCount === 1)
&& ((! array_key_exists($refParams[0]->name, $paramArray))
|| (array_key_exists($refParams[0]->name, $paramArray)
&& count($paramArray) !== 1))
) {
$output = $instance->{$method}($paramArray);
} else {
$fireArgs = [];
$methodParams = [];
foreach ($refParams as $arg) {
$methodParams[$arg->name] = true;
if (array_key_exists($arg->name, $paramArray)) {
$fireArgs[$arg->name] = $paramArray[$arg->name];
}
}
foreach (array_keys($paramArray) as $key) {
if (! isset($methodParams[$key])) {
throw ViewException::forInvalidCellParameter($key);
}
}
$output = $instance->{$method}(...array_values($fireArgs));
}
// Can we cache it?
if (! empty($this->cache) && $ttl !== 0) {
$this->cache->save($cacheName, $output, $ttl);
}
return $output;
}
/**
* Parses the params attribute. If an array, returns untouched.
* If a string, it should be in the format "key1=value key2=value".
* It will be split and returned as an array.
*
* @param mixed $params
*
* @return array|null
*/
public function prepareParams($params)
{
if (empty($params) || (! is_string($params) && ! is_array($params))) {
return [];
}
if (is_string($params)) {
$newParams = [];
$separator = ' ';
if (strpos($params, ',') !== false) {
$separator = ',';
}
$params = explode($separator, $params);
unset($separator);
foreach ($params as $p) {
if (! empty($p)) {
[$key, $val] = explode('=', $p);
$newParams[trim($key)] = trim($val, ', ');
}
}
$params = $newParams;
unset($newParams);
}
if ($params === []) {
return [];
}
return $params;
}
/**
* Given the library string, attempts to determine the class and method
* to call.
*/
protected function determineClass(string $library): array
{
// We don't want to actually call static methods
// by default, so convert any double colons.
$library = str_replace('::', ':', $library);
[$class, $method] = explode(':', $library);
if (empty($class)) {
throw ViewException::forNoCellClass();
}
if (! class_exists($class, true)) {
throw ViewException::forInvalidCellClass($class);
}
if (empty($method)) {
$method = 'index';
}
return [
$class,
$method,
];
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
class ViewException extends FrameworkException
{
public static function forInvalidCellMethod(string $class, string $method)
{
return new static(lang('View.invalidCellMethod', ['class' => $class, 'method' => $method]));
}
public static function forMissingCellParameters(string $class, string $method)
{
return new static(lang('View.missingCellParameters', ['class' => $class, 'method' => $method]));
}
public static function forInvalidCellParameter(string $key)
{
return new static(lang('View.invalidCellParameter', [$key]));
}
public static function forNoCellClass()
{
return new static(lang('View.noCellClass'));
}
public static function forInvalidCellClass(?string $class = null)
{
return new static(lang('View.invalidCellClass', [$class]));
}
public static function forTagSyntaxError(string $output)
{
return new static(lang('View.tagSyntaxError', [$output]));
}
}

244
system/View/Filters.php Normal file
View File

@@ -0,0 +1,244 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use Config\Services;
use NumberFormatter;
/**
* View filters
*/
class Filters
{
/**
* Returns $value as all lowercase with the first letter capitalized.
*/
public static function capitalize(string $value): string
{
return ucfirst(strtolower($value));
}
/**
* Formats a date into the given $format.
*
* @param mixed $value
*/
public static function date($value, string $format): string
{
if (is_string($value) && ! is_numeric($value)) {
$value = strtotime($value);
}
return date($format, $value);
}
/**
* Given a string or DateTime object, will return the date modified
* by the given value. Returns the value as a unix timestamp
*
* Example:
* my_date|date_modify(+1 day)
*
* @param string $value
*
* @return false|int
*/
public static function date_modify($value, string $adjustment)
{
$value = static::date($value, 'Y-m-d H:i:s');
return strtotime($adjustment, strtotime($value));
}
/**
* Returns the given default value if $value is empty or undefined.
*
* @param mixed $value
*/
public static function default($value, string $default): string
{
return empty($value)
? $default
: $value;
}
/**
* Escapes the given value with our `esc()` helper function.
*
* @param string $value
*/
public static function esc($value, string $context = 'html'): string
{
return esc($value, $context);
}
/**
* Returns an excerpt of the given string.
*/
public static function excerpt(string $value, string $phrase, int $radius = 100): string
{
helper('text');
return excerpt($value, $phrase, $radius);
}
/**
* Highlights a given phrase within the text using '<mark></mark>' tags.
*/
public static function highlight(string $value, string $phrase): string
{
helper('text');
return highlight_phrase($value, $phrase);
}
/**
* Highlights code samples with HTML/CSS.
*
* @param string $value
*/
public static function highlight_code($value): string
{
helper('text');
return highlight_code($value);
}
/**
* Limits the number of characters to $limit, and trails of with an ellipsis.
* Will break at word break so may be more or less than $limit.
*
* @param string $value
*/
public static function limit_chars($value, int $limit = 500): string
{
helper('text');
return character_limiter($value, $limit);
}
/**
* Limits the number of words to $limit, and trails of with an ellipsis.
*
* @param string $value
*/
public static function limit_words($value, int $limit = 100): string
{
helper('text');
return word_limiter($value, $limit);
}
/**
* Returns the $value displayed in a localized manner.
*
* @param float|int $value
*/
public static function local_number($value, string $type = 'decimal', int $precision = 4, ?string $locale = null): string
{
helper('number');
$types = [
'decimal' => NumberFormatter::DECIMAL,
'currency' => NumberFormatter::CURRENCY,
'percent' => NumberFormatter::PERCENT,
'scientific' => NumberFormatter::SCIENTIFIC,
'spellout' => NumberFormatter::SPELLOUT,
'ordinal' => NumberFormatter::ORDINAL,
'duration' => NumberFormatter::DURATION,
];
return format_number($value, $precision, $locale, ['type' => $types[$type]]);
}
/**
* Returns the $value displayed as a currency string.
*
* @param float|int $value
* @param int $fraction
*/
public static function local_currency($value, string $currency, ?string $locale = null, $fraction = null): string
{
helper('number');
$options = [
'type' => NumberFormatter::CURRENCY,
'currency' => $currency,
'fraction' => $fraction,
];
return format_number($value, 2, $locale, $options);
}
/**
* Returns a string with all instances of newline character (\n)
* converted to an HTML <br/> tag.
*/
public static function nl2br(string $value): string
{
$typography = Services::typography();
return $typography->nl2brExceptPre($value);
}
/**
* Takes a body of text and uses the auto_typography() method to
* turn it into prettier, easier-to-read, prose.
*/
public static function prose(string $value): string
{
$typography = Services::typography();
return $typography->autoTypography($value);
}
/**
* Rounds a given $value in one of 3 ways;
*
* - common Normal rounding
* - ceil always rounds up
* - floor always rounds down
*
* @param mixed $precision
*
* @return float|string
*/
public static function round(string $value, $precision = 2, string $type = 'common')
{
if (! is_numeric($precision)) {
$type = $precision;
$precision = 2;
}
switch ($type) {
case 'common':
return round((float) $value, $precision);
case 'ceil':
return ceil((float) $value);
case 'floor':
return floor((float) $value);
}
// Still here, just return the value.
return $value;
}
/**
* Returns a "title case" version of the string.
*/
public static function title(string $value): string
{
return ucwords(strtolower($value));
}
}

684
system/View/Parser.php Normal file
View File

@@ -0,0 +1,684 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\View\Exceptions\ViewException;
use Config\View as ViewConfig;
use ParseError;
use Psr\Log\LoggerInterface;
/**
* Class for parsing pseudo-vars
*/
class Parser extends View
{
/**
* Left delimiter character for pseudo vars
*
* @var string
*/
public $leftDelimiter = '{';
/**
* Right delimiter character for pseudo vars
*
* @var string
*/
public $rightDelimiter = '}';
/**
* Stores extracted noparse blocks.
*
* @var array
*/
protected $noparseBlocks = [];
/**
* Stores any plugins registered at run-time.
*
* @var array
*/
protected $plugins = [];
/**
* Stores the context for each data element
* when set by `setData` so the context is respected.
*
* @var array
*/
protected $dataContexts = [];
/**
* Constructor
*
* @param string $viewPath
* @param mixed $loader
* @param bool $debug
* @param LoggerInterface $logger
*/
public function __construct(ViewConfig $config, ?string $viewPath = null, $loader = null, ?bool $debug = null, ?LoggerInterface $logger = null)
{
// Ensure user plugins override core plugins.
$this->plugins = $config->plugins ?? [];
parent::__construct($config, $viewPath, $loader, $debug, $logger);
}
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template view,
* replacing them with any data that has already been set.
*
* @param array $options
* @param bool $saveData
*/
public function render(string $view, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
if ($saveData === null) {
$saveData = $this->config->saveData;
}
$fileExt = pathinfo($view, PATHINFO_EXTENSION);
$view = empty($fileExt) ? $view . '.php' : $view; // allow Views as .html, .tpl, etc (from CI3)
$cacheName = $options['cache_name'] ?? str_replace('.php', '', $view);
// Was it cached?
if (isset($options['cache']) && ($output = cache($cacheName))) {
$this->logPerformance($start, microtime(true), $view);
return $output;
}
$file = $this->viewPath . $view;
if (! is_file($file)) {
$fileOrig = $file;
$file = $this->loader->locateFile($view, 'Views');
// locateFile will return an empty string if the file cannot be found.
if (empty($file)) {
throw ViewException::forInvalidFile($fileOrig);
}
}
if ($this->tempData === null) {
$this->tempData = $this->data;
}
$template = file_get_contents($file);
$output = $this->parse($template, $this->tempData, $options);
$this->logPerformance($start, microtime(true), $view);
if ($saveData) {
$this->data = $this->tempData;
}
// Should we cache?
if (isset($options['cache'])) {
cache()->save($cacheName, $output, (int) $options['cache']);
}
$this->tempData = null;
return $output;
}
/**
* Parse a String
*
* Parses pseudo-variables contained in the specified string,
* replacing them with any data that has already been set.
*
* @param array $options
* @param bool $saveData
*/
public function renderString(string $template, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
if ($saveData === null) {
$saveData = $this->config->saveData;
}
if ($this->tempData === null) {
$this->tempData = $this->data;
}
$output = $this->parse($template, $this->tempData, $options);
$this->logPerformance($start, microtime(true), $this->excerpt($template));
if ($saveData) {
$this->data = $this->tempData;
}
$this->tempData = null;
return $output;
}
/**
* Sets several pieces of view data at once.
* In the Parser, we need to store the context here
* so that the variable is correctly handled within the
* parsing itself, and contexts (including raw) are respected.
*
* @param string $context The context to escape it for: html, css, js, url, raw
* If 'raw', no escaping will happen
*/
public function setData(array $data = [], ?string $context = null): RendererInterface
{
if (! empty($context)) {
foreach ($data as $key => &$value) {
if (is_array($value)) {
foreach ($value as &$obj) {
$obj = $this->objectToArray($obj);
}
} else {
$value = $this->objectToArray($value);
}
$this->dataContexts[$key] = $context;
}
}
$this->tempData = $this->tempData ?? $this->data;
$this->tempData = array_merge($this->tempData, $data);
return $this;
}
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* @param array $options Future options
*/
protected function parse(string $template, array $data = [], ?array $options = null): string
{
if ($template === '') {
return '';
}
// Remove any possible PHP tags since we don't support it
// and parseConditionals needs it clean anyway...
$template = str_replace(['<?', '?>'], ['&lt;?', '?&gt;'], $template);
$template = $this->parseComments($template);
$template = $this->extractNoparse($template);
// Replace any conditional code here so we don't have to parse as much
$template = $this->parseConditionals($template);
// Handle any plugins before normal data, so that
// it can potentially modify any template between its tags.
$template = $this->parsePlugins($template);
// loop over the data variables, replacing
// the content as we go.
foreach ($data as $key => $val) {
$escape = true;
if (is_array($val)) {
$escape = false;
$replace = $this->parsePair($key, $val, $template);
} else {
$replace = $this->parseSingle($key, (string) $val);
}
foreach ($replace as $pattern => $content) {
$template = $this->replaceSingle($pattern, $content, $template, $escape);
}
}
return $this->insertNoparse($template);
}
/**
* Parse a single key/value, extracting it
*/
protected function parseSingle(string $key, string $val): array
{
$pattern = '#' . $this->leftDelimiter . '!?\s*' . preg_quote($key, '#') . '(?(?=\s*\|\s*)(\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*))(\s*)!?' . $this->rightDelimiter . '#ms';
return [$pattern => $val];
}
/**
* Parse a tag pair
*
* Parses tag pairs: {some_tag} string... {/some_tag}
*/
protected function parsePair(string $variable, array $data, string $template): array
{
// Holds the replacement patterns and contents
// that will be used within a preg_replace in parse()
$replace = [];
// Find all matches of space-flexible versions of {tag}{/tag} so we
// have something to loop over.
preg_match_all(
'#' . $this->leftDelimiter . '\s*' . preg_quote($variable, '#') . '\s*' . $this->rightDelimiter . '(.+?)' .
$this->leftDelimiter . '\s*' . '/' . preg_quote($variable, '#') . '\s*' . $this->rightDelimiter . '#s',
$template,
$matches,
PREG_SET_ORDER
);
/*
* Each match looks like:
*
* $match[0] {tag}...{/tag}
* $match[1] Contents inside the tag
*/
foreach ($matches as $match) {
// Loop over each piece of $data, replacing
// it's contents so that we know what to replace in parse()
$str = ''; // holds the new contents for this tag pair.
foreach ($data as $row) {
// Objects that have a `toArray()` method should be
// converted with that method (i.e. Entities)
if (is_object($row) && method_exists($row, 'toArray')) {
$row = $row->toArray();
}
// Otherwise, cast as an array and it will grab public properties.
elseif (is_object($row)) {
$row = (array) $row;
}
$temp = [];
$pairs = [];
$out = $match[1];
foreach ($row as $key => $val) {
// For nested data, send us back through this method...
if (is_array($val)) {
$pair = $this->parsePair($key, $val, $match[1]);
if (! empty($pair)) {
$pairs[array_keys($pair)[0]] = true;
$temp = array_merge($temp, $pair);
}
continue;
}
if (is_object($val)) {
$val = 'Class: ' . get_class($val);
} elseif (is_resource($val)) {
$val = 'Resource';
}
$temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key, '#') . '(?(?=\s*\|\s*)(\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*))(\s*)!?' . $this->rightDelimiter . '#s'] = $val;
}
// Now replace our placeholders with the new content.
foreach ($temp as $pattern => $content) {
$out = $this->replaceSingle($pattern, $content, $out, ! isset($pairs[$pattern]));
}
$str .= $out;
}
// Escape | character from filters as it's handled as OR in regex
$escapedMatch = preg_replace('/(?<!\\\\)\\|/', '\\|', $match[0]);
$replace['#' . $escapedMatch . '#s'] = $str;
}
return $replace;
}
/**
* Removes any comments from the file. Comments are wrapped in {# #} symbols:
*
* {# This is a comment #}
*/
protected function parseComments(string $template): string
{
return preg_replace('/\{#.*?#\}/s', '', $template);
}
/**
* Extracts noparse blocks, inserting a hash in its place so that
* those blocks of the page are not touched by parsing.
*/
protected function extractNoparse(string $template): string
{
$pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ms';
/*
* $matches[][0] is the raw match
* $matches[][1] is the contents
*/
if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
// Create a hash of the contents to insert in its place.
$hash = md5($match[1]);
$this->noparseBlocks[$hash] = $match[1];
$template = str_replace($match[0], "noparse_{$hash}", $template);
}
}
return $template;
}
/**
* Re-inserts the noparsed contents back into the template.
*/
public function insertNoparse(string $template): string
{
foreach ($this->noparseBlocks as $hash => $replace) {
$template = str_replace("noparse_{$hash}", $replace, $template);
unset($this->noparseBlocks[$hash]);
}
return $template;
}
/**
* Parses any conditionals in the code, removing blocks that don't
* pass so we don't try to parse it later.
*
* Valid conditionals:
* - if
* - elseif
* - else
*/
protected function parseConditionals(string $template): string
{
$pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms';
/*
* For each match:
* [0] = raw match `{if var}`
* [1] = conditional `if`
* [2] = condition `do === true`
* [3] = same as [2]
*/
preg_match_all($pattern, $template, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
// Build the string to replace the `if` statement with.
$condition = $match[2];
$statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>';
$template = str_replace($match[0], $statement, $template);
}
$template = preg_replace('/\{\s*else\s*\}/ms', '<?php else: ?>', $template);
$template = preg_replace('/\{\s*endif\s*\}/ms', '<?php endif; ?>', $template);
// Parse the PHP itself, or insert an error so they can debug
ob_start();
if ($this->tempData === null) {
$this->tempData = $this->data;
}
extract($this->tempData);
try {
eval('?>' . $template . '<?php ');
} catch (ParseError $e) {
ob_end_clean();
throw ViewException::forTagSyntaxError(str_replace(['?>', '<?php '], '', $template));
}
return ob_get_clean();
}
/**
* Over-ride the substitution field delimiters.
*
* @param string $leftDelimiter
* @param string $rightDelimiter
*/
public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface
{
$this->leftDelimiter = $leftDelimiter;
$this->rightDelimiter = $rightDelimiter;
return $this;
}
/**
* Handles replacing a pseudo-variable with the actual content. Will double-check
* for escaping brackets.
*
* @param mixed $pattern
* @param string $content
* @param string $template
*/
protected function replaceSingle($pattern, $content, $template, bool $escape = false): string
{
// Any dollar signs in the pattern will be misinterpreted, so slash them
$pattern = addcslashes($pattern, '$');
$content = (string) $content;
// Flesh out the main pattern from the delimiters and escape the hash
// See https://regex101.com/r/IKdUlk/1
if (preg_match('/^(#)(.+)(#(m?s)?)$/s', $pattern, $parts)) {
$pattern = $parts[1] . addcslashes($parts[2], '#') . $parts[3];
}
// Replace the content in the template
return preg_replace_callback($pattern, function ($matches) use ($content, $escape) {
// Check for {! !} syntax to not escape this one.
if (strpos($matches[0], '{!') === 0 && substr($matches[0], -2) === '!}') {
$escape = false;
}
return $this->prepareReplacement($matches, $content, $escape);
}, (string) $template);
}
/**
* Callback used during parse() to apply any filters to the value.
*/
protected function prepareReplacement(array $matches, string $replace, bool $escape = true): string
{
$orig = array_shift($matches);
// Our regex earlier will leave all chained values on a single line
// so we need to break them apart so we can apply them all.
$filters = ! empty($matches[1]) ? explode('|', $matches[1]) : [];
if ($escape && empty($filters) && ($context = $this->shouldAddEscaping($orig))) {
$filters[] = "esc({$context})";
}
return $this->applyFilters($replace, $filters);
}
/**
* Checks the placeholder the view provided to see if we need to provide any autoescaping.
*
* @return false|string
*/
public function shouldAddEscaping(string $key)
{
$escape = false;
$key = trim(str_replace(['{', '}'], '', $key));
// If the key has a context stored (from setData)
// we need to respect that.
if (array_key_exists($key, $this->dataContexts)) {
if ($this->dataContexts[$key] !== 'raw') {
return $this->dataContexts[$key];
}
}
// No pipes, then we know we need to escape
elseif (strpos($key, '|') === false) {
$escape = 'html';
}
// If there's a `noescape` then we're definitely false.
elseif (strpos($key, 'noescape') !== false) {
$escape = false;
}
// If no `esc` filter is found, then we'll need to add one.
elseif (! preg_match('/\s+esc/', $key)) {
$escape = 'html';
}
return $escape;
}
/**
* Given a set of filters, will apply each of the filters in turn
* to $replace, and return the modified string.
*/
protected function applyFilters(string $replace, array $filters): string
{
// Determine the requested filters
foreach ($filters as $filter) {
// Grab any parameter we might need to send
preg_match('/\([\w<>=\/\\\,:.\-\s\+]+\)/', $filter, $param);
// Remove the () and spaces to we have just the parameter left
$param = ! empty($param) ? trim($param[0], '() ') : null;
// Params can be separated by commas to allow multiple parameters for the filter
if (! empty($param)) {
$param = explode(',', $param);
// Clean it up
foreach ($param as &$p) {
$p = trim($p, ' "');
}
} else {
$param = [];
}
// Get our filter name
$filter = ! empty($param) ? trim(strtolower(substr($filter, 0, strpos($filter, '(')))) : trim($filter);
if (! array_key_exists($filter, $this->config->filters)) {
continue;
}
// Filter it....
$replace = $this->config->filters[$filter]($replace, ...$param);
}
return $replace;
}
// Plugins
/**
* Scans the template for any parser plugins, and attempts to execute them.
* Plugins are delimited by {+ ... +}
*
* @return string
*/
protected function parsePlugins(string $template)
{
foreach ($this->plugins as $plugin => $callable) {
// Paired tags are enclosed in an array in the config array.
$isPair = is_array($callable);
$callable = $isPair ? array_shift($callable) : $callable;
// See https://regex101.com/r/BCBBKB/1
$pattern = $isPair
? '#\{\+\s*' . $plugin . '([\w=\-_:\+\s\(\)/"@.]*)?\s*\+\}(.+?)\{\+\s*/' . $plugin . '\s*\+\}#ims'
: '#\{\+\s*' . $plugin . '([\w=\-_:\+\s\(\)/"@.]*)?\s*\+\}#ims';
/**
* Match tag pairs
*
* Each match is an array:
* $matches[0] = entire matched string
* $matches[1] = all parameters string in opening tag
* $matches[2] = content between the tags to send to the plugin.
*/
if (! preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) {
continue;
}
foreach ($matches as $match) {
$params = [];
preg_match_all('/([\w-]+=\"[^"]+\")|([\w-]+=[^\"\s=]+)|(\"[^"]+\")|(\S+)/', trim($match[1]), $matchesParams);
foreach ($matchesParams[0] as $item) {
$keyVal = explode('=', $item);
if (count($keyVal) === 2) {
$params[$keyVal[0]] = str_replace('"', '', $keyVal[1]);
} else {
$params[] = str_replace('"', '', $item);
}
}
$template = $isPair
? str_replace($match[0], $callable($match[2], $params), $template)
: str_replace($match[0], $callable($params), $template);
}
}
return $template;
}
/**
* Makes a new plugin available during the parsing of the template.
*
* @return $this
*/
public function addPlugin(string $alias, callable $callback, bool $isPair = false)
{
$this->plugins[$alias] = $isPair ? [$callback] : $callback;
return $this;
}
/**
* Removes a plugin from the available plugins.
*
* @return $this
*/
public function removePlugin(string $alias)
{
unset($this->plugins[$alias]);
return $this;
}
/**
* Converts an object to an array, respecting any
* toArray() methods on an object.
*
* @param mixed $value
*
* @return mixed
*/
protected function objectToArray($value)
{
// Objects that have a `toArray()` method should be
// converted with that method (i.e. Entities)
if (is_object($value) && method_exists($value, 'toArray')) {
$value = $value->toArray();
}
// Otherwise, cast as an array and it will grab public properties.
elseif (is_object($value)) {
$value = (array) $value;
}
return $value;
}
}

106
system/View/Plugins.php Normal file
View File

@@ -0,0 +1,106 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\HTTP\URI;
use Config\Services;
/**
* View plugins
*/
class Plugins
{
/**
* Wrap helper function to use as view plugin.
*
* @return string|URI
*/
public static function currentURL()
{
return current_url();
}
/**
* Wrap helper function to use as view plugin.
*
* @return mixed|string|URI
*/
public static function previousURL()
{
return previous_url();
}
/**
* Wrap helper function to use as view plugin.
*/
public static function mailto(array $params = []): string
{
$email = $params['email'] ?? '';
$title = $params['title'] ?? '';
$attrs = $params['attributes'] ?? '';
return mailto($email, $title, $attrs);
}
/**
* Wrap helper function to use as view plugin.
*/
public static function safeMailto(array $params = []): string
{
$email = $params['email'] ?? '';
$title = $params['title'] ?? '';
$attrs = $params['attributes'] ?? '';
return safe_mailto($email, $title, $attrs);
}
/**
* Wrap helper function to use as view plugin.
*/
public static function lang(array $params = []): string
{
$line = array_shift($params);
return lang($line, $params);
}
/**
* Wrap helper function to use as view plugin.
*/
public static function ValidationErrors(array $params = []): string
{
$validator = Services::validation();
if (empty($params)) {
return $validator->listErrors();
}
return $validator->showError($params['field']);
}
/**
* Wrap helper function to use as view plugin.
*
* @return false|string
*/
public static function route(array $params = [])
{
return route_to(...$params);
}
/**
* Wrap helper function to use as view plugin.
*/
public static function siteURL(array $params = []): string
{
return site_url(...$params);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
/**
* Interface RendererInterface
*
* The interface used for displaying Views and/or theme files.
*/
interface RendererInterface
{
/**
* Builds the output based upon a file name and any
* data that has already been set.
*
* @param array $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool $saveData Whether to save data for subsequent calls
*/
public function render(string $view, ?array $options = null, bool $saveData = false): string;
/**
* Builds the output based upon a string and any
* data that has already been set.
*
* @param string $view The view contents
* @param array $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool $saveData Whether to save data for subsequent calls
*/
public function renderString(string $view, ?array $options = null, bool $saveData = false): string;
/**
* Sets several pieces of view data at once.
*
* @param string $context The context to escape it for: html, css, js, url
* If 'raw', no escaping will happen
*
* @return RendererInterface
*/
public function setData(array $data = [], ?string $context = null);
/**
* Sets a single piece of view data.
*
* @param mixed $value
* @param string $context The context to escape it for: html, css, js, url
* If 'raw' no escaping will happen
*
* @return RendererInterface
*/
public function setVar(string $name, $value = null, ?string $context = null);
/**
* Removes all of the view data from the system.
*
* @return RendererInterface
*/
public function resetData();
}

485
system/View/Table.php Normal file
View File

@@ -0,0 +1,485 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Database\BaseResult;
/**
* HTML Table Generating Class
*
* Lets you create tables manually or from database result objects, or arrays.
*/
class Table
{
/**
* Data for table rows
*
* @var array
*/
public $rows = [];
/**
* Data for table heading
*
* @var array
*/
public $heading = [];
/**
* Data for table footing
*
* @var array
*/
public $footing = [];
/**
* Whether or not to automatically create the table header
*
* @var bool
*/
public $autoHeading = true;
/**
* Table caption
*
* @var string|null
*/
public $caption;
/**
* Table layout template
*
* @var array
*/
public $template;
/**
* Newline setting
*
* @var string
*/
public $newline = "\n";
/**
* Contents of empty cells
*
* @var string
*/
public $emptyCells = '';
/**
* Callback for custom table layout
*
* @var callable|null
*/
public $function;
/**
* Set the template from the table config file if it exists
*
* @param array $config (default: array())
*/
public function __construct($config = [])
{
// initialize config
foreach ($config as $key => $val) {
$this->template[$key] = $val;
}
}
/**
* Set the template
*
* @param array $template
*
* @return bool
*/
public function setTemplate($template)
{
if (! is_array($template)) {
return false;
}
$this->template = $template;
return true;
}
/**
* Set the table heading
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function setHeading()
{
$this->heading = $this->_prepArgs(func_get_args());
return $this;
}
/**
* Set the table footing
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function setFooting()
{
$this->footing = $this->_prepArgs(func_get_args());
return $this;
}
/**
* Set columns. Takes a one-dimensional array as input and creates
* a multi-dimensional array with a depth equal to the number of
* columns. This allows a single array with many elements to be
* displayed in a table that has a fixed column count.
*
* @param array $array
* @param int $columnLimit
*
* @return array|false
*/
public function makeColumns($array = [], $columnLimit = 0)
{
if (! is_array($array) || $array === [] || ! is_int($columnLimit)) {
return false;
}
// Turn off the auto-heading feature since it's doubtful we
// will want headings from a one-dimensional array
$this->autoHeading = false;
if ($columnLimit === 0) {
return $array;
}
$new = [];
do {
$temp = array_splice($array, 0, $columnLimit);
if (count($temp) < $columnLimit) {
for ($i = count($temp); $i < $columnLimit; $i++) {
$temp[] = '&nbsp;';
}
}
$new[] = $temp;
} while ($array !== []);
return $new;
}
/**
* Set "empty" cells
*
* Can be passed as an array or discreet params
*
* @param mixed $value
*
* @return Table
*/
public function setEmpty($value)
{
$this->emptyCells = $value;
return $this;
}
/**
* Add a table row
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function addRow()
{
$this->rows[] = $this->_prepArgs(func_get_args());
return $this;
}
/**
* Prep Args
*
* Ensures a standard associative array format for all cell data
*
* @return array
*/
protected function _prepArgs(array $args)
{
// If there is no $args[0], skip this and treat as an associative array
// This can happen if there is only a single key, for example this is passed to table->generate
// array(array('foo'=>'bar'))
if (isset($args[0]) && count($args) === 1 && is_array($args[0]) && ! isset($args[0]['data'])) {
$args = $args[0];
}
foreach ($args as $key => $val) {
if (! is_array($val)) {
$args[$key] = ['data' => $val];
}
}
return $args;
}
/**
* Add a table caption
*
* @param string $caption
*
* @return Table
*/
public function setCaption($caption)
{
$this->caption = $caption;
return $this;
}
/**
* Generate the table
*
* @param mixed $tableData
*
* @return string
*/
public function generate($tableData = null)
{
// The table data can optionally be passed to this function
// either as a database result object or an array
if (! empty($tableData)) {
if ($tableData instanceof BaseResult) {
$this->_setFromDBResult($tableData);
} elseif (is_array($tableData)) {
$this->_setFromArray($tableData);
}
}
// Is there anything to display? No? Smite them!
if (empty($this->heading) && empty($this->rows)) {
return 'Undefined table data';
}
// Compile and validate the template date
$this->_compileTemplate();
// Validate a possibly existing custom cell manipulation function
if (isset($this->function) && ! is_callable($this->function)) {
$this->function = null;
}
// Build the table!
$out = $this->template['table_open'] . $this->newline;
// Add any caption here
if ($this->caption) {
$out .= '<caption>' . $this->caption . '</caption>' . $this->newline;
}
// Is there a table heading to display?
if (! empty($this->heading)) {
$out .= $this->template['thead_open'] . $this->newline . $this->template['heading_row_start'] . $this->newline;
foreach ($this->heading as $heading) {
$temp = $this->template['heading_cell_start'];
foreach ($heading as $key => $val) {
if ($key !== 'data') {
$temp = str_replace('<th', '<th ' . $key . '="' . $val . '"', $temp);
}
}
$out .= $temp . ($heading['data'] ?? '') . $this->template['heading_cell_end'];
}
$out .= $this->template['heading_row_end'] . $this->newline . $this->template['thead_close'] . $this->newline;
}
// Build the table rows
if (! empty($this->rows)) {
$out .= $this->template['tbody_open'] . $this->newline;
$i = 1;
foreach ($this->rows as $row) {
// We use modulus to alternate the row colors
$name = fmod($i++, 2) ? '' : 'alt_';
$out .= $this->template['row_' . $name . 'start'] . $this->newline;
foreach ($row as $cell) {
$temp = $this->template['cell_' . $name . 'start'];
foreach ($cell as $key => $val) {
if ($key !== 'data') {
$temp = str_replace('<td', '<td ' . $key . '="' . $val . '"', $temp);
}
}
$cell = $cell['data'] ?? '';
$out .= $temp;
if ($cell === '' || $cell === null) {
$out .= $this->emptyCells;
} elseif (isset($this->function)) {
$out .= ($this->function)($cell);
} else {
$out .= $cell;
}
$out .= $this->template['cell_' . $name . 'end'];
}
$out .= $this->template['row_' . $name . 'end'] . $this->newline;
}
$out .= $this->template['tbody_close'] . $this->newline;
}
// Any table footing to display?
if (! empty($this->footing)) {
$out .= $this->template['tfoot_open'] . $this->newline . $this->template['footing_row_start'] . $this->newline;
foreach ($this->footing as $footing) {
$temp = $this->template['footing_cell_start'];
foreach ($footing as $key => $val) {
if ($key !== 'data') {
$temp = str_replace('<th', '<th ' . $key . '="' . $val . '"', $temp);
}
}
$out .= $temp . ($footing['data'] ?? '') . $this->template['footing_cell_end'];
}
$out .= $this->template['footing_row_end'] . $this->newline . $this->template['tfoot_close'] . $this->newline;
}
// And finally, close off the table
$out .= $this->template['table_close'];
// Clear table class properties before generating the table
$this->clear();
return $out;
}
/**
* Clears the table arrays. Useful if multiple tables are being generated
*
* @return Table
*/
public function clear()
{
$this->rows = [];
$this->heading = [];
$this->footing = [];
$this->autoHeading = true;
$this->caption = null;
return $this;
}
/**
* Set table data from a database result object
*
* @param BaseResult $object Database result object
*/
protected function _setFromDBResult($object)
{
// First generate the headings from the table column names
if ($this->autoHeading && empty($this->heading)) {
$this->heading = $this->_prepArgs($object->getFieldNames());
}
foreach ($object->getResultArray() as $row) {
$this->rows[] = $this->_prepArgs($row);
}
}
/**
* Set table data from an array
*
* @param array $data
*/
protected function _setFromArray($data)
{
if ($this->autoHeading && empty($this->heading)) {
$this->heading = $this->_prepArgs(array_shift($data));
}
foreach ($data as &$row) {
$this->rows[] = $this->_prepArgs($row);
}
}
/**
* Compile Template
*/
protected function _compileTemplate()
{
if ($this->template === null) {
$this->template = $this->_defaultTemplate();
return;
}
foreach ($this->_defaultTemplate() as $field => $template) {
if (! isset($this->template[$field])) {
$this->template[$field] = $template;
}
}
}
/**
* Default Template
*
* @return array
*/
protected function _defaultTemplate()
{
return [
'table_open' => '<table border="0" cellpadding="4" cellspacing="0">',
'thead_open' => '<thead>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tfoot_open' => '<tfoot>',
'tfoot_close' => '</tfoot>',
'footing_row_start' => '<tr>',
'footing_row_end' => '</tr>',
'footing_cell_start' => '<td>',
'footing_cell_end' => '</td>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>',
];
}
}

458
system/View/View.php Normal file
View File

@@ -0,0 +1,458 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Autoloader\FileLocator;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
use CodeIgniter\View\Exceptions\ViewException;
use Config\Services;
use Config\Toolbar;
use Config\View as ViewConfig;
use Psr\Log\LoggerInterface;
use RuntimeException;
/**
* Class View
*/
class View implements RendererInterface
{
/**
* Data that is made available to the Views.
*
* @var array
*/
protected $data = [];
/**
* Merge savedData and userData
*/
protected $tempData;
/**
* The base directory to look in for our Views.
*
* @var string
*/
protected $viewPath;
/**
* The render variables
*
* @var array
*/
protected $renderVars = [];
/**
* Instance of FileLocator for when
* we need to attempt to find a view
* that's not in standard place.
*
* @var FileLocator
*/
protected $loader;
/**
* Logger instance.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Should we store performance info?
*
* @var bool
*/
protected $debug = false;
/**
* Cache stats about our performance here,
* when CI_DEBUG = true
*
* @var array
*/
protected $performanceData = [];
/**
* @var ViewConfig
*/
protected $config;
/**
* Whether data should be saved between renders.
*
* @var bool
*/
protected $saveData;
/**
* Number of loaded views
*
* @var int
*/
protected $viewsCount = 0;
/**
* The name of the layout being used, if any.
* Set by the `extend` method used within views.
*
* @var string|null
*/
protected $layout;
/**
* Holds the sections and their data.
*
* @var array
*/
protected $sections = [];
/**
* The name of the current section being rendered,
* if any.
*
* @var string|null
*
* @deprecated
*/
protected $currentSection;
/**
* The name of the current section being rendered,
* if any.
*
* @var array<string>
*/
protected $sectionStack = [];
public function __construct(ViewConfig $config, ?string $viewPath = null, ?FileLocator $loader = null, ?bool $debug = null, ?LoggerInterface $logger = null)
{
$this->config = $config;
$this->viewPath = rtrim($viewPath, '\\/ ') . DIRECTORY_SEPARATOR;
$this->loader = $loader ?? Services::locator();
$this->logger = $logger ?? Services::logger();
$this->debug = $debug ?? CI_DEBUG;
$this->saveData = (bool) $config->saveData;
}
/**
* Builds the output based upon a file name and any
* data that has already been set.
*
* Valid $options:
* - cache Number of seconds to cache for
* - cache_name Name to use for cache
*
* @param string $view File name of the view source
* @param array|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool|null $saveData If true, saves data for subsequent calls,
* if false, cleans the data after displaying,
* if null, uses the config setting.
*/
public function render(string $view, ?array $options = null, ?bool $saveData = null): string
{
$this->renderVars['start'] = microtime(true);
// Store the results here so even if
// multiple views are called in a view, it won't
// clean it unless we mean it to.
$saveData = $saveData ?? $this->saveData;
$fileExt = pathinfo($view, PATHINFO_EXTENSION);
$realPath = empty($fileExt) ? $view . '.php' : $view; // allow Views as .html, .tpl, etc (from CI3)
$this->renderVars['view'] = $realPath;
$this->renderVars['options'] = $options ?? [];
// Was it cached?
if (isset($this->renderVars['options']['cache'])) {
$cacheName = $this->renderVars['options']['cache_name'] ?? str_replace('.php', '', $this->renderVars['view']);
$cacheName = str_replace(['\\', '/'], '', $cacheName);
$this->renderVars['cacheName'] = $cacheName;
if ($output = cache($this->renderVars['cacheName'])) {
$this->logPerformance($this->renderVars['start'], microtime(true), $this->renderVars['view']);
return $output;
}
}
$this->renderVars['file'] = $this->viewPath . $this->renderVars['view'];
if (! is_file($this->renderVars['file'])) {
$this->renderVars['file'] = $this->loader->locateFile($this->renderVars['view'], 'Views', empty($fileExt) ? 'php' : $fileExt);
}
// locateFile will return an empty string if the file cannot be found.
if (empty($this->renderVars['file'])) {
throw ViewException::forInvalidFile($this->renderVars['view']);
}
// Make our view data available to the view.
$this->prepareTemplateData($saveData);
// Save current vars
$renderVars = $this->renderVars;
$output = (function (): string {
extract($this->tempData);
ob_start();
include $this->renderVars['file'];
return ob_get_clean() ?: '';
})();
// Get back current vars
$this->renderVars = $renderVars;
// When using layouts, the data has already been stored
// in $this->sections, and no other valid output
// is allowed in $output so we'll overwrite it.
if ($this->layout !== null && $this->sectionStack === []) {
$layoutView = $this->layout;
$this->layout = null;
// Save current vars
$renderVars = $this->renderVars;
$output = $this->render($layoutView, $options, $saveData);
// Get back current vars
$this->renderVars = $renderVars;
}
$this->logPerformance($this->renderVars['start'], microtime(true), $this->renderVars['view']);
if (($this->debug && (! isset($options['debug']) || $options['debug'] === true))
&& in_array('CodeIgniter\Filters\DebugToolbar', service('filters')->getFiltersClass()['after'], true)
) {
$toolbarCollectors = config(Toolbar::class)->collectors;
if (in_array(Views::class, $toolbarCollectors, true)) {
// Clean up our path names to make them a little cleaner
$this->renderVars['file'] = clean_path($this->renderVars['file']);
$this->renderVars['file'] = ++$this->viewsCount . ' ' . $this->renderVars['file'];
$output = '<!-- DEBUG-VIEW START ' . $this->renderVars['file'] . ' -->' . PHP_EOL
. $output . PHP_EOL
. '<!-- DEBUG-VIEW ENDED ' . $this->renderVars['file'] . ' -->' . PHP_EOL;
}
}
// Should we cache?
if (isset($this->renderVars['options']['cache'])) {
cache()->save($this->renderVars['cacheName'], $output, (int) $this->renderVars['options']['cache']);
}
$this->tempData = null;
return $output;
}
/**
* Builds the output based upon a string and any
* data that has already been set.
* Cache does not apply, because there is no "key".
*
* @param string $view The view contents
* @param array|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool|null $saveData If true, saves data for subsequent calls,
* if false, cleans the data after displaying,
* if null, uses the config setting.
*/
public function renderString(string $view, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
$saveData = $saveData ?? $this->saveData;
$this->prepareTemplateData($saveData);
$output = (function (string $view): string {
extract($this->tempData);
ob_start();
eval('?>' . $view);
return ob_get_clean() ?: '';
})($view);
$this->logPerformance($start, microtime(true), $this->excerpt($view));
$this->tempData = null;
return $output;
}
/**
* Extract first bit of a long string and add ellipsis
*/
public function excerpt(string $string, int $length = 20): string
{
return (strlen($string) > $length) ? substr($string, 0, $length - 3) . '...' : $string;
}
/**
* Sets several pieces of view data at once.
*
* @param string $context The context to escape it for: html, css, js, url
* If null, no escaping will happen
*/
public function setData(array $data = [], ?string $context = null): RendererInterface
{
if ($context) {
$data = \esc($data, $context);
}
$this->tempData = $this->tempData ?? $this->data;
$this->tempData = array_merge($this->tempData, $data);
return $this;
}
/**
* Sets a single piece of view data.
*
* @param mixed $value
* @param string|null $context The context to escape it for: html, css, js, url
* If null, no escaping will happen
*/
public function setVar(string $name, $value = null, ?string $context = null): RendererInterface
{
if ($context) {
$value = esc($value, $context);
}
$this->tempData = $this->tempData ?? $this->data;
$this->tempData[$name] = $value;
return $this;
}
/**
* Removes all of the view data from the system.
*/
public function resetData(): RendererInterface
{
$this->data = [];
return $this;
}
/**
* Returns the current data that will be displayed in the view.
*/
public function getData(): array
{
return $this->tempData ?? $this->data;
}
/**
* Specifies that the current view should extend an existing layout.
*/
public function extend(string $layout)
{
$this->layout = $layout;
}
/**
* Starts holds content for a section within the layout.
*
* @param string $name Section name
*/
public function section(string $name)
{
// Saved to prevent BC.
$this->currentSection = $name;
$this->sectionStack[] = $name;
ob_start();
}
/**
* Captures the last section
*
* @throws RuntimeException
*/
public function endSection()
{
$contents = ob_get_clean();
if ($this->sectionStack === []) {
throw new RuntimeException('View themes, no current section.');
}
$section = array_pop($this->sectionStack);
// Ensure an array exists so we can store multiple entries for this.
if (! array_key_exists($section, $this->sections)) {
$this->sections[$section] = [];
}
$this->sections[$section][] = $contents;
}
/**
* Renders a section's contents.
*/
public function renderSection(string $sectionName)
{
if (! isset($this->sections[$sectionName])) {
echo '';
return;
}
foreach ($this->sections[$sectionName] as $key => $contents) {
echo $contents;
unset($this->sections[$sectionName][$key]);
}
}
/**
* Used within layout views to include additional views.
*
* @param bool $saveData
*/
public function include(string $view, ?array $options = null, $saveData = true): string
{
return $this->render($view, $options, $saveData);
}
/**
* Returns the performance data that might have been collected
* during the execution. Used primarily in the Debug Toolbar.
*/
public function getPerformanceData(): array
{
return $this->performanceData;
}
/**
* Logs performance data for rendering a view.
*/
protected function logPerformance(float $start, float $end, string $view)
{
if ($this->debug) {
$this->performanceData[] = [
'start' => $start,
'end' => $end,
'view' => $view,
];
}
}
protected function prepareTemplateData(bool $saveData): void
{
$this->tempData = $this->tempData ?? $this->data;
if ($saveData) {
$this->data = $this->tempData;
}
}
}