viewPath)) {
if (defined('VIEWS_DIR')) {
$this->viewPath = rtrim(VIEWS_DIR, '/') . '/';
} else {
$this->viewPath = ROOT_CORE . '/Views/';
}
} else {
$this->viewPath = rtrim($this->viewPath, '/') . '/';
}
}
/**
* Loads the component from a file.
*
* @param string $component
*
* @return static
*/
public function load(string $component): static
{
$componentRealName = trim(str_replace(':', '/', $component), ' :');
if (file_exists($this->viewPath . $componentRealName . $this->extension)) {
ob_start();
include($this->viewPath . $componentRealName . $this->extension);
$this->content = ob_get_clean();
$this->parse();
} else {
throw new \Exception(
'"' . $component . '" component not exists.'
);
}
return $this;
}
/**
* Component tag token grammar. Matches an opening tag `` or a
* closing tag `` where Name is an optional leading-colon namespace
* followed by an uppercase letter and at least one word/digit/colon char
* (so plain lowercase HTML and single-letter tags are never treated as
* components). Mirrors the discovery grammar the previous regex used.
*/
private const TAG_RE = '/<(\/)?((?::+)?[A-Z][\w1-9:]+)([^>]*)>/';
/**
* Parses and processes the content in search of more components.
*
* Uses a single left-to-right pass over all component tags with an
* explicit stack, so it correctly resolves balanced, same-type nested
* components at any depth (which the previous per-name lazy regex could
* not) and costs one pass regardless of how many distinct component
* types the document uses.
*
* @return void
*/
protected function parse(): void
{
$this->content = $this->parseComponents($this->content, $this->properties);
}
/**
* Resolves every component tag found in $content, rendering each with the
* properties inherited from its ancestors merged with its own, and returns
* the fully rendered string. Nested components are rendered bottom-up (the
* stack assembles each frame's inner content before the frame is rendered).
*
* @param string $content Content that may contain component tags.
* @param array $inherited Properties inherited from ancestor components.
*
* @return string
*/
private function parseComponents(string $content, array $inherited): string
{
preg_match_all(self::TAG_RE, $content, $tokens, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
if (!$tokens) {
return $content;
}
$segments = [];
$cursor = 0;
/** @var array, rawStart: int}> $stack */
$stack = [];
$top = -1;
$length = strlen($content);
foreach ($tokens as $token) {
$offset = $token[0][1];
$raw = $token[0][0];
if ($offset > $cursor) {
$literal = substr($content, $cursor, $offset - $cursor);
if ($top >= 0) {
$stack[$top]['seg'][] = $literal;
} else {
$segments[] = $literal;
}
}
$cursor = $offset + strlen($raw);
$isClose = $token[1][0] === '/';
$name = $token[2][0];
if (!$isClose) {
$parentProperties = $top >= 0 ? $stack[$top]['props'] : $inherited;
$ownProperties = static::parseProperties($token[3][0]);
$stack[] = [
'name' => $name,
'props' => array_merge($parentProperties, $ownProperties),
'seg' => [],
'rawStart' => $offset,
];
$top++;
continue;
}
if ($top >= 0 && $stack[$top]['name'] === $name) {
$frame = array_pop($stack);
$top--;
$inner = implode('', $frame['seg']);
$rendered = $this->renderComponent($name, $frame['props'], $inner);
if ($top >= 0) {
$stack[$top]['seg'][] = $rendered;
} else {
$segments[] = $rendered;
}
} else {
// stray or mis-nested closing tag: keep it verbatim (malformed
// markup is left unparsed rather than crashing).
if ($top >= 0) {
$stack[$top]['seg'][] = $raw;
} else {
$segments[] = $raw;
}
}
}
if ($top >= 0) {
// unbalanced opening tags: emit the remainder verbatim from the
// first unclosed component onward.
$segments[] = substr($content, $stack[0]['rawStart']);
} elseif ($cursor < $length) {
$segments[] = substr($content, $cursor);
}
return implode('', $segments);
}
/**
* Renders a single component with the given (already inherited+merged)
* properties and inner content. The inner content is fully resolved before
* it reaches here; load() re-parses the view's own output so components
* declared inside a view file keep working.
*
* @param string $component
* @param array $properties
* @param string $inner
*
* @return string
*/
private function renderComponent(string $component, array $properties, string $inner): string
{
$instance = new static($properties);
$instance->content = $inner;
$instance->load($component);
return $instance->getContent();
}
/**
* Converts a string in "key='value' key2='value2'" format into an array.
*
* @param string $propertiesString
*
* @return array
*/
protected static function parseProperties(string $propertiesString): array
{
preg_match_all('/([\w]+)=[\'"](.+)?[\'"]/sU', $propertiesString, $matches, PREG_PATTERN_ORDER);
$result = [];
foreach ($matches[1] as $index => $property) {
$result[$property] = $matches[2][$index];
}
preg_match_all('/([\w]+) /si', $propertiesString . ' ', $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $property) {
$result[$property] = $property;
}
return $result;
}
/**
* Prints the component.
*
* @return void
*/
public function print(): void
{
echo $this->content;
}
/**
* Renders a component.
*
* @param string $component
* @param array $properties
*
* @return void
*/
public static function render(string $component, array $properties = []): void
{
$instance = new static($properties);
$instance->load($component);
$instance->print();
}
/**
* Returns the component as a string.
*
* @return string
*/
public function getContent(): string
{
return $this->content;
}
/**
* Returns the value of a property.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function property(string $key, mixed $default = null): mixed
{
return $this->properties[$key] ?? $default;
}
/**
* Returns the value of a property escaped with htmlspecialchars.
*
* @param string $key
* @param string $default
*
* @return string
*/
public function escapedProperty(string $key, string $default = ''): string
{
if (isset($this->properties[$key])) {
return SanitizerProxy::apply($this->properties[$key] ?? null);
} else {
return htmlspecialchars($default);
}
}
/**
* Alias function for the property method.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function p(string $key, mixed $default = null): mixed
{
return $this->property($key, $default);
}
/**
* Alias function for the escapedProperty method.
*
* @param string $key
* @param string $default
*
* @return string
*/
public function e(string $key, string $default = ''): string
{
return $this->escapedProperty($key, $default);
}
/**
* Based on the received array of property names, it returns them
* with their values as an associative array.
* If no properties are received as arguments, all existing ones are returned.
*
* @param array $properties
*
* @return array
*/
public function propsToArray(...$properties): array
{
if (empty($properties)) {
return $this->properties;
}
$result = [];
foreach ($properties as $property) {
$result[$property] = $this->properties[$property] ?? null;
}
return $result;
}
/**
* Based on the received array of property names, it returns them
* as HTML attributes in property="value" format.
*
* @param array $properties
*
* @return string
*/
public function propsToAtts(...$properties): string
{
$attributes = [];
foreach ($properties as $property) {
$attributes[] = $property . '="' .
htmlspecialchars($this->property($property, '')) . '"';
}
return ' ' . implode(' ', $attributes);
}
/**
* Based on the received array of property names, it returns them
* as unary HTML attributes such as checked, required, etc.
*
* @param array $properties
*
* @return string
*/
public function propsToUnary(...$properties): string
{
$result = ' ';
foreach ($properties as $property) {
if (isset($this->properties[$property])) {
$result .= $property . ' ';
}
}
return $result;
}
/**
* Treats a property as a definition of a unary HTML property.
*
* @param string $property Unary property to look for.
* @param mixed $result Value to return if the property is defined. If null, returns $property.
*
* @return mixed
*/
public function unary(string $property, mixed $result = null): mixed
{
if (isset($this->properties[$property])) {
if (isset($result)) {
return $result;
} else {
return $property;
}
}
return null;
}
/**
* Adds a new property/attribute.
* If a property already exists, it replaces it.
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function addProperty(string $key, mixed $value): void
{
$this->properties = array_merge($this->properties, [$key => $value]);
}
/**
* Adds new properties in bulk.
* If a property already exists, it replaces it.
*
* @param array $properties
*
* @return void
*/
public function addProperties(array $properties): void
{
$this->properties = array_merge($this->properties, $properties);
}
/**
* Attempts to return the absolute URL from a relative path.
*
* @param string $path
*
* @return string
*/
public static function route(string $path = '/'): string
{
if (defined('SITE_URL') && !empty(SITE_URL)) {
return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
}
return $path;
}
/**
* Returns the request path.
*
* @return string
*/
public static function path(): string
{
return Router::currentPath();
}
/**
* __get
*
* @param string $index
* @return mixed
*/
public function __get(string $index): mixed
{
return SanitizerProxy::apply($this->property($index));
}
/**
* __isset
*
* @param string $key
*
* @return bool
*/
public function __isset(string $key): bool
{
return isset($this->properties[$key]);
}
}