Skip to content

Internals Blade Integration

Stefan Crkvenjakov edited this page Oct 7, 2026 · 1 revision

AWT Blade integration

Rendering internals · Developer guide

Source: adapted BladeOne

BladeOne 4.17.1 retains its upstream MIT attribution. This page describes AWT-specific integration and modified code paths; upstream properties, directives and utility APIs are third-party and excluded from the exhaustive ownership inventory.

State and constraints

AWT uses packageName (protected string, default empty), assetDict (protected array, default empty), csrf_token (public string, default empty) and constructor-promoted readonly csrfTokens/requests/httpMethods collaborators. View supplies the template root, COMPILED path, MODE_AUTO, extension, package name and asset dictionary slot 0. A cache salt csrf-instance-v1 separates compiled templates using the instance-backed CSRF directive. @data still builds a legacy media URL. Resource URLs require PublicResource permission at HTTP serving time even after internal resolution.

__construct

public function __construct($templatePath = null, $compiledPath = null, $mode = 0, $commentMode = 0,
        private readonly \router\interface\ICsrfTokenManager $csrfTokens = new \router\security\Csrf(),
        private readonly \router\interface\IRequestProvider $requests = new \router\http\GlobalsRequestProvider(),
        private readonly \router\interface\IMethodPolicy $httpMethods = new \router\http\HttpMethod())

State writes: $this->templatePath, $this->compiledPath, self::$instance, $this->authCallBack, $this->authAnyCallBack, $this->errorCallBack.

Return expressions (including local callbacks): \in_array($action, $this->currentPermission, true); true; false.

Adapted implementation and ordering
//</editor-fold>
    //<editor-fold desc="constructor">
    /**
     * It creates an instance of BladeOne. The folder at $compiledPath is created in case it doesn't exist.<br>
     * **Example**
     * ```
     * $blade=new BladeOne("pathtemplate","pathcompile",BladeOne::MODE_AUTO,2);
     * ```
     *
     * @param string|null $templatePath If null then it uses (caller_folder)/views
     * @param string|null $compiledPath If null then it uses (caller_folder)/compiles
     * @param int         $mode         =[BladeOne::MODE_AUTO,BladeOne::MODE_DEBUG,BladeOne::MODE_FAST,BladeOne::MODE_SLOW][$i]<br>
     *                                  **BladeOne::MODE_AUTO** (default mode)<br>
     *                                  **BladeOne::MODE_DEBUG** errors will be more verbose, and it will compile code
     *                                  every time<br>
     *                                  **BladeOne::MODE_FAST** it will not check if the compiled file exists<br>
     *                                  **BladeOne::MODE_SLOW** it will compile the code everytime<br>
     * @param int         $commentMode  =[0,1,2][$i] <br>
     *                                  **0** comments are generated as php code.<br>
     *                                  **1** comments are generated as html code<br>
     *                                  **2** comments are ignored (no code is generated)<br>
     */
    public function __construct($templatePath = null, $compiledPath = null, $mode = 0, $commentMode = 0,
        private readonly \router\interface\ICsrfTokenManager $csrfTokens = new \router\security\Csrf(),
        private readonly \router\interface\IRequestProvider $requests = new \router\http\GlobalsRequestProvider(),
        private readonly \router\interface\IMethodPolicy $httpMethods = new \router\http\HttpMethod())
    {
        if ($templatePath === null) {
            $templatePath = \getcwd() . '/views';
        }
        if ($compiledPath === null) {
            $compiledPath = \getcwd() . '/compiles';
        }
        $this->templatePath = (is_array($templatePath)) ? $templatePath : [$templatePath];
        $this->compiledPath = $compiledPath;
        $this->setMode($mode);
        $this->setCommentMode($commentMode);
        self::$instance = $this;
        $this->authCallBack = function(
            $action = null,
            /** @noinspection PhpUnusedParameterInspection */
            $subject = null
        ) {
            return \in_array($action, $this->currentPermission, true);
        };
        $this->authAnyCallBack = function($array = []) {
            foreach ($array as $permission) {
                if (\in_array($permission, $this->currentPermission ?? [], true)) {
                    return true;
                }
            }
            return false;
        };
        $this->errorCallBack = static function(
            /** @noinspection PhpUnusedParameterInspection */
            $key = null
        ) {
            return false;
        };
        // If the "traits" has "Constructors", then we call them.
        // Requisites.
        // 1- the method must be public or protected
        // 2- it must don't have arguments
        // 3- It must have the name of the trait. i.e. trait=MyTrait, method=MyTrait()
        $traits = get_declared_traits();
        $currentTraits = (array)class_uses($this);
        foreach ($traits as $trait) {
            $r = explode('\\', $trait);
            $name = end($r);
            if (!in_array($trait, $currentTraits, true)) {
                continue;
            }
            if (is_callable([$this, $name]) && method_exists($this, $name)) {
                $this->{$name}();
            }
        }
    }

setPackageName

public function setPackageName(string $packageName): BladeOne

State writes: $this->packageName.

Return expressions (including local callbacks): $this.

Adapted implementation and ordering
public function setPackageName(string $packageName): BladeOne
    {
        $this->packageName = $packageName;
        return $this;
    }

addAssetDict

public function addAssetDict($name, $url = ''): void

State writes: $this->assetDict, $this->assetDict[$name].

Adapted implementation and ordering
/**
     * It adds an alias to the link of the resources.<br>
     * addAssetDict('name','url/res.jpg')<br>
     * addAssetDict(['name'=>'url/res.jpg','name2'=>'url/res2.jpg']);
     *
     * @param string|array $name example 'css/style.css', you could also add an array
     * @param string       $url  example https://www.web.com/style.css'
     */
    public function addAssetDict($name, $url = ''): void
    {
        if (\is_array($name)) {
            $this->assetDict = \array_merge($this->assetDict, $name);
        } else {
            $this->assetDict[$name] = $url;
        }
    }

getCompiledFile

public function getCompiledFile($templateName = ''): string

Return expressions (including local callbacks): $this->compiledPath . '/' . basename($templateName) . '_' . $hash . $this->compileExtension.

Explicit exceptions: \RuntimeException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Adapted implementation and ordering
/**
     * Get the full path of the compiled file.
     *
     * @param string $templateName
     * @return string
     */
    public function getCompiledFile($templateName = ''): string
    {
        $templateName = (empty($templateName)) ? $this->fileName : $templateName;
        $fullPath = $this->getTemplateFile($templateName);
        if ($fullPath == '') {
            throw new \RuntimeException('Template not found: ' . ($this->mode == self::MODE_DEBUG ? $this->templatePath[0] . '/' . $templateName : $templateName));
        }
        $style = $this->compileTypeFileName;
        if ($style === 'auto') {
            $style = 'sha1';
        }
        // Recompile templates that previously called the static CSRF helper.
        $cacheKey = $fullPath . '|csrf-instance-v1';
        $hash = $style === 'md5' ? \md5($cacheKey) : \sha1($cacheKey);
        return $this->compiledPath . '/' . basename($templateName) . '_' . $hash . $this->compileExtension;
    }

getCsrfToken

public function getCsrfToken($fullToken = false, $tokenId = '_token'): string

State writes: $this->csrf_token.

Return expressions (including local callbacks): $fullToken ? $this->csrf_token . '|' . $this->ipClient() : $this->csrf_token.

Adapted implementation and ordering
/**
     * Returns the current token. if there is not a token then it generates a new one.
     * It could require an open session.
     *
     * @param bool   $fullToken It returns a token with the current ip.
     * @param string $tokenId   [optional] Name of the token.
     *
     * @return string
     */
    public function getCsrfToken($fullToken = false, $tokenId = '_token'): string
    {
        $this->csrf_token = $this->csrfTokens->token($tokenId);
        return $fullToken ? $this->csrf_token . '|' . $this->ipClient() : $this->csrf_token;
    }

regenerateToken

public function regenerateToken($tokenId = '_token'): void

State writes: $this->csrf_token.

Adapted implementation and ordering
/** Regenerate the shared session token explicitly (invalidates existing forms). */
    public function regenerateToken($tokenId = '_token'): void
    {
        $this->csrf_token = $this->csrfTokens->regenerate($tokenId);
    }

csrfIsValid

public function csrfIsValid($alwaysRegenerate = false, $tokenId = '_token'): bool

Return expressions (including local callbacks): false; true.

Adapted implementation and ordering
/** Validate unsafe requests before optionally rotating the shared token. */
    public function csrfIsValid($alwaysRegenerate = false, $tokenId = '_token'): bool
    {
        $request = $this->requests->current();
        if (!$this->httpMethods->isSafe($request->method())
            && !$this->csrfTokens->validateToken($request->csrfToken($tokenId), $tokenId)) {
            return false;
        }
        if ($alwaysRegenerate) {
            $this->regenerateToken($tokenId);
        } else {
            $this->getCsrfToken(false, $tokenId);
        }
        return true;
    }

compilecsrf

protected function compilecsrf($expression = null): string

Return expressions (including local callbacks): "<input type='hidden' name='<?= htmlspecialchars($expression, ENT_QUOTES, 'UTF-8') ?>' value='<?= htmlspecialchars(\$this->getCsrfToken(false, $expression), ENT_QUOTES, 'UTF-8') ?>'/>".

Adapted implementation and ordering
protected function compilecsrf($expression = null): string
    {
        $expression = empty($expression) ? "'_token'" : $this->stripParentheses($expression);
        return "<input type='hidden' name='<?= htmlspecialchars($expression, ENT_QUOTES, 'UTF-8') ?>' value='<?= htmlspecialchars(\$this->getCsrfToken(false, $expression), ENT_QUOTES, 'UTF-8') ?>'/>";
    }

compileAsset

protected function compileAsset($expression): string

Return expressions (including local callbacks): $this->phpTagEcho . "'$url'.

Adapted implementation and ordering
protected function compileAsset($expression): string
    {
        $expression = str_replace("('", "", $expression);
        $expression = str_replace("')", "", $expression);

        $url = HOSTNAME . $this->assetDict[0] . "/". $expression;
        return $this->phpTagEcho . "'$url'; ?>";
    }

compileData

protected function compileData($expression): string

Return expressions (including local callbacks): $this->phpTagEcho . "'$path'.

Adapted implementation and ordering
protected function compileData($expression): string
    {
        $expression = str_replace("('", "", $expression);
        $expression = str_replace("')", "", $expression);
        $expression = str_replace("'", "", $expression);

        $args = explode(',', $expression);

        $file = $args[0];
        $type = $args[1];

        $path = HOSTNAME . "/awt_data/media/packages/$type/" . $this->packageName . "/$file";

        return $this->phpTagEcho . "'$path'; ?>";
    }

compileResource

protected function compileResource($expression): string

Return expressions (including local callbacks): $this->phpTagEcho . '$this->resourceUrl' . $expression . '.

Adapted implementation and ordering
protected function compileResource($expression): string
    {
        return $this->phpTagEcho . '$this->resourceUrl' . $expression . '; ?>';
    }

resourceUrl

public function resourceUrl(string $alias, bool $must = false): string

Return expressions (including local callbacks): ''; self::e($url).

Explicit exceptions: \vfs\resource\exceptions\ResourceException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Adapted implementation and ordering
/** Resolve a Resource alias at render time using this template's package context. */
    public function resourceUrl(string $alias, bool $must = false): string
    {
        $context = $this->packageName;
        if (str_contains($alias, ':')) $context = explode(':', $alias, 2)[0];
        $resource = new \vfs\resource\Resource($context);
        $path = $resource->get($alias, $must);
        if ($path === null) return '';

        $root = rtrim(PACKAGES, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        if (!str_starts_with($path, $root)) {
            throw new \vfs\resource\exceptions\ResourceException('Resource is outside the package root.');
        }
        $relative = substr($path, strlen($root));
        $segments = explode(DIRECTORY_SEPARATOR, $relative);
        $url = rtrim(HOSTNAME, '/') . '/awt_packages/' . implode('/', array_map('rawurlencode', $segments));
        return self::e($url);
    }

compileUrl

protected function compileUrl($expression): string

Return expressions (including local callbacks): $this->phpTagEcho . "'$path'.

Adapted implementation and ordering
protected function compileUrl($expression): string {

        $expression = str_replace("('", "", $expression);
        $expression = str_replace("')", "", $expression);

        $path = HOSTNAME . "/$expression";
        return $this->phpTagEcho . "'$path'; ?>";
    }

Clone this wiki locally