silverstripe-framework/src/View/SSViewer_FromString.php

93 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\View;
use SilverStripe\Core\Config\Config;
/**
* Special SSViewer that will process a template passed as a string, rather than a filename.
*/
class SSViewer_FromString extends SSViewer
{
2016-11-29 00:31:16 +01:00
/**
* The global template caching behaviour if no instance override is specified
2017-09-19 18:23:53 +02:00
*
2016-11-29 00:31:16 +01:00
* @config
* @var bool
*/
private static $cache_template = true;
/**
* The template to use
2017-09-19 18:23:53 +02:00
*
2016-11-29 00:31:16 +01:00
* @var string
*/
protected $content;
/**
* Indicates whether templates should be cached
*
* @var bool
*/
protected $cacheTemplate;
2017-09-19 18:23:53 +02:00
/**
* @param string $content
* @param TemplateParser $parser
*/
2016-11-29 00:31:16 +01:00
public function __construct($content, TemplateParser $parser = null)
{
if ($parser) {
$this->setParser($parser);
}
$this->content = $content;
}
2017-09-19 18:23:53 +02:00
/**
* {@inheritdoc}
*/
2016-11-29 00:31:16 +01:00
public function process($item, $arguments = null, $scope = null)
{
2022-04-14 03:12:59 +02:00
$hash = sha1($this->content ?? '');
2017-10-09 01:41:34 +02:00
$cacheFile = TEMP_PATH . DIRECTORY_SEPARATOR . ".cache.$hash";
2016-11-29 00:31:16 +01:00
2022-04-14 03:12:59 +02:00
if (!file_exists($cacheFile ?? '') || isset($_GET['flush'])) {
2016-11-29 00:31:16 +01:00
$content = $this->parseTemplateContent($this->content, "string sha1=$hash");
2022-04-14 03:12:59 +02:00
$fh = fopen($cacheFile ?? '', 'w');
fwrite($fh, $content ?? '');
2016-11-29 00:31:16 +01:00
fclose($fh);
}
$val = $this->includeGeneratedTemplate($cacheFile, $item, $arguments, null, $scope);
if ($this->cacheTemplate !== null) {
$cacheTemplate = $this->cacheTemplate;
} else {
$cacheTemplate = static::config()->get('cache_template');
2016-11-29 00:31:16 +01:00
}
if (!$cacheTemplate) {
2022-04-14 03:12:59 +02:00
unlink($cacheFile ?? '');
2016-11-29 00:31:16 +01:00
}
return $val;
}
/**
* @param boolean $cacheTemplate
*/
public function setCacheTemplate($cacheTemplate)
{
$this->cacheTemplate = (bool)$cacheTemplate;
}
/**
* @return boolean
*/
public function getCacheTemplate()
{
return $this->cacheTemplate;
}
}