winter/modules/cms/classes/CmsCompoundObject.php

475 lines
14 KiB
PHP
Raw Normal View History

2014-05-14 23:24:20 +10:00
<?php namespace Cms\Classes;
use Validator;
use Cms\Classes\CodeBase;
use System\Classes\SystemException;
use Cms\Classes\FileHelper;
use October\Rain\Support\ValidationException;
2014-08-28 19:03:47 +11:00
use Cms\Classes\ViewBag;
use Cache;
use Config;
2014-10-05 22:21:03 -07:00
use Twig_Environment;
use System\Twig\Extension as SystemTwigExtension;
use Cms\Twig\Extension as CmsTwigExtension;
use Cms\Twig\Loader as TwigLoader;
2014-05-14 23:24:20 +10:00
/**
* This is a base class for CMS objects that have multiple sections - pages, partials and layouts.
* The class implements functionality for the compound object file parsing. It also provides a way
* to access parameters defined in the INI settings section as the object properties.
*
* @package october\cms
* @author Alexey Bobkov, Samuel Georges
*/
class CmsCompoundObject extends CmsObject
{
/**
* @var array Initialized components defined in the template file.
*/
public $components = [];
/**
* @var array INI settings defined in the template file.
*/
public $settings = [];
/**
* @var string PHP code section of the template file.
*/
public $code;
/**
* @var string Twig markup section of the template file.
*/
public $markup;
protected static $fillable = [
'markup',
'settings',
'code',
'fileName'
];
protected $settingsValidationRules = [];
protected $settingsValidationMessages = [];
2014-08-28 19:03:47 +11:00
protected $viewBagValidationRules = [];
protected $viewBagValidationMessages = [];
protected $viewBagCache = false;
protected $originalData = [];
protected static $objectComponentPropertyMap = null;
2014-05-14 23:24:20 +10:00
/**
* Loads the object from a file.
2014-05-17 18:08:01 +02:00
* @param \Cms\Classes\Theme $theme Specifies the theme the object belongs to.
2014-05-14 23:24:20 +10:00
* @param string $fileName Specifies the file name, with the extension.
* The file name can contain only alphanumeric symbols, dashes and dots.
* @return boolean Returns true if the object was successfully loaded. Otherwise returns false.
*/
public static function load($theme, $fileName)
{
2014-10-11 01:22:03 +02:00
if (($obj = parent::load($theme, $fileName)) === null) {
2014-05-14 23:24:20 +10:00
return null;
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
CmsException::mask($obj, 200);
$parsedData = SectionParser::parse($obj->content);
CmsException::unmask();
2014-05-14 23:24:20 +10:00
$obj->settings = $parsedData['settings'];
$obj->code = $parsedData['code'];
$obj->markup = $parsedData['markup'];
$obj->originalData['settings'] = $obj->settings;
$obj->originalData['code'] = $obj->code;
$obj->originalData['markup'] = $obj->markup;
2014-05-14 23:24:20 +10:00
$obj->parseComponentSettings();
$obj->parseSettings();
return $obj;
}
/**
* Implements getter functionality for properties defined in the settings section.
*/
public function __get($name)
{
2014-10-11 01:22:03 +02:00
if (is_array($this->settings) && array_key_exists($name, $this->settings)) {
2014-05-14 23:24:20 +10:00
return $this->settings[$name];
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
return parent::__get($name);
}
/**
* Determine if an attribute exists on the object.
*
* @param string $key
* @return void
*/
public function __isset($key)
{
2014-10-11 01:22:03 +02:00
if (parent::__isset($key) === true) {
2014-05-14 23:24:20 +10:00
return true;
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
return isset($this->settings[$key]);
}
/**
* Returns the Twig content string
*/
public function getTwigContent()
{
return $this->markup;
}
/**
* Runs components defined in the settings
* Process halts if a component returns a value
*/
public function runComponents()
{
foreach ($this->components as $component) {
2014-10-11 01:22:03 +02:00
if ($result = $component->onRun()) {
2014-05-14 23:24:20 +10:00
return $result;
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
}
}
/**
* Parse component sections.
* Replace the multiple component sections with a single "components"
* element in the $settings property.
*/
public function parseComponentSettings()
{
$manager = ComponentManager::instance();
$components = [];
foreach ($this->settings as $setting => $value) {
2014-10-11 01:22:03 +02:00
if (!is_array($value)) {
2014-05-14 23:24:20 +10:00
continue;
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
$settingParts = explode(' ', $setting);
$settingName = $settingParts[0];
2014-10-11 01:22:03 +02:00
// if (!$manager->hasComponent($settingName)) {
// continue;
2014-10-11 01:22:03 +02:00
// }
2014-05-14 23:24:20 +10:00
$components[$setting] = $value;
unset($this->settings[$setting]);
}
$this->settings['components'] = $components;
}
/**
* Returns name of a PHP class to us a parent for the PHP class created for the object's PHP section.
* @return mixed Returns the class name or null.
*/
public function getCodeClassParent()
{
return null;
}
/**
2014-05-17 18:08:01 +02:00
* Sets the PHP code content string.
2014-05-14 23:24:20 +10:00
* @param string $value Specifies the PHP code string.
* @return \Cms\Classes\CmsCompoundObject Returns the object instance.
*/
public function setCode($value)
{
$value = trim($value);
$this->code = $value;
}
/**
* Saves the object to the disk.
*/
public function save()
{
$this->code = trim($this->code);
$this->markup = trim($this->markup);
2014-10-11 01:22:03 +02:00
$trim = function (&$values) use (&$trim) {
2014-05-14 23:24:20 +10:00
foreach ($values as &$value) {
2014-10-11 01:22:03 +02:00
if (!is_array($value)) {
2014-05-14 23:24:20 +10:00
$value = trim($value);
2014-10-11 01:22:03 +02:00
} else {
$trim($value);
}
2014-05-14 23:24:20 +10:00
}
};
$trim($this->settings);
2014-10-11 01:22:03 +02:00
if (array_key_exists('components', $this->settings) && count($this->settings['components']) == 0) {
unset($this->settings['components']);
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
$this->validate();
$content = [];
2014-10-11 01:22:03 +02:00
if ($this->settings) {
2014-05-14 23:24:20 +10:00
$content[] = FileHelper::formatIniString($this->settings);
2014-10-11 01:22:03 +02:00
}
2014-05-14 23:24:20 +10:00
if ($this->code) {
if ($this->wrapCodeToPhpTags() && $this->originalData['code'] != $this->code) {
$code = preg_replace('/^\<\?php/', '', $this->code);
$code = preg_replace('/^\<\?/', '', $code);
$code = preg_replace('/\?>$/', '', $code);
$content[] = '<?php'.PHP_EOL.$this->code.PHP_EOL.'?>';
} else {
$content[] = $this->code;
2014-05-14 23:24:20 +10:00
}
$content[] = $this->markup;
$this->content = trim(implode(PHP_EOL.'=='.PHP_EOL, $content));
parent::save();
}
/**
* Returns the configured view bag component.
* This method is used only in the back-end and for internal system needs when
* the standard way to access components is not an option.
* @return \Cms\Classes\ViewBag Returns the view bag component instance.
*/
public function getViewBag()
{
2014-10-11 01:22:03 +02:00
if ($this->viewBagCache !== false) {
return $this->viewBagCache;
2014-10-11 01:22:03 +02:00
}
$componentName = 'viewBag';
2014-08-28 19:03:47 +11:00
if (!isset($this->settings['components'][$componentName])) {
$viewBag = new ViewBag(null, []);
$viewBag->name = $componentName;
return $this->viewBagCache = $viewBag;
}
return $this->viewBagCache = $this->getComponent($componentName);
}
/**
* Returns a component by its name.
* This method is used only in the back-end and for internal system needs when
* the standard way to access components is not an option.
* @param string $componentName Specifies the component name.
* @return \Cms\Classes\ComponentBase Returns the component instance or null.
*/
public function getComponent($componentName)
{
2014-10-11 14:33:40 +02:00
if (!($componentSection = $this->hasComponent($componentName))) {
return null;
2014-10-11 01:22:03 +02:00
}
return ComponentManager::instance()->makeComponent(
2014-10-11 01:22:03 +02:00
$componentName,
null,
$this->settings['components'][$componentSection]
2014-10-11 01:22:03 +02:00
);
}
/**
* Checks if the object has a component with the specified name.
* @param string $componentName Specifies the component name.
* @return mixed Return false or the full component name used on the page (it could include the alias).
*/
public function hasComponent($componentName)
{
2014-10-11 14:33:40 +02:00
foreach ($this->settings['components'] as $sectionName => $values) {
if ($sectionName == $componentName) {
return $componentName;
}
$parts = explode(' ', $sectionName);
if (count($parts) < 2) {
continue;
}
if (trim($parts[0]) == $componentName) {
return $sectionName;
}
}
return false;
}
/**
* Returns component property names and values.
* This method implements caching and can be used in the run-time on the front-end.
* @param string $componentName Specifies the component name.
* @return array Returns an associative array with property names in the keys and property values in the values.
*/
public function getComponentProperties($componentName)
{
$key = crc32($this->theme->getPath()).'component-properties';
if (self::$objectComponentPropertyMap !== null) {
$objectComponentMap = self::$objectComponentPropertyMap;
} else {
$cached = Cache::get($key, false);
$unserialized = $cached ? @unserialize($cached) : false;
$objectComponentMap = $unserialized ? $unserialized : [];
2014-10-11 01:22:03 +02:00
if ($objectComponentMap) {
self::$objectComponentPropertyMap = $objectComponentMap;
2014-10-11 01:22:03 +02:00
}
}
$objectCode = $this->getBaseFileName();
if (array_key_exists($objectCode, $objectComponentMap)) {
2014-10-11 01:22:03 +02:00
if (array_key_exists($componentName, $objectComponentMap[$objectCode])) {
return $objectComponentMap[$objectCode][$componentName];
2014-10-11 01:22:03 +02:00
}
return [];
}
2014-10-11 01:22:03 +02:00
if (!isset($this->settings['components'])) {
$objectComponentMap[$objectCode] = [];
2014-10-11 01:22:03 +02:00
} else {
foreach ($this->settings['components'] as $componentName => $componentSettings) {
$nameParts = explode(' ', $componentName);
if (count($nameParts > 1)) {
$componentName = trim($nameParts[0]);
}
$component = $this->getComponent($componentName);
2014-10-11 01:22:03 +02:00
if (!$component) {
continue;
2014-10-11 01:22:03 +02:00
}
$componentProperties = [];
$propertyDefinitions = $component->defineProperties();
2014-10-11 01:22:03 +02:00
foreach ($propertyDefinitions as $propertyName => $propertyInfo) {
$componentProperties[$propertyName] = $component->property($propertyName);
2014-10-11 01:22:03 +02:00
}
$objectComponentMap[$objectCode][$componentName] = $componentProperties;
}
}
self::$objectComponentPropertyMap = $objectComponentMap;
Cache::put($key, serialize($objectComponentMap), Config::get('cms.parsedPageCacheTTL', 10));
2014-10-11 01:22:03 +02:00
if (array_key_exists($componentName, $objectComponentMap[$objectCode])) {
return $objectComponentMap[$objectCode][$componentName];
2014-10-11 01:22:03 +02:00
}
return [];
}
/**
* Clears the object cache.
*/
public static function clearCache($theme)
{
$key = crc32($theme->getPath()).'component-properties';
Cache::forget($key);
}
2014-10-05 22:21:03 -07:00
/**
* Returns Twig node tree generated from the object's markup.
* This method is used by the system internally and shouldn't
* participate in the front-end request processing.
* @link http://twig.sensiolabs.org/doc/internals.html Twig internals
* @param mixed $markup Specifies the markup content.
* Use FALSE to load the content from the markup section.
2014-10-05 22:21:03 -07:00
* @return Twig_Node_Module A node tree
*/
public function getTwigNodeTree($markup = false)
2014-10-05 22:21:03 -07:00
{
$loader = new TwigLoader();
$twig = new Twig_Environment($loader, []);
$twig->addExtension(new CmsTwigExtension());
$twig->addExtension(new SystemTwigExtension);
$stream = $twig->tokenize($markup === false ? $this->markup : $markup, 'getTwigNodeTree');
2014-10-05 22:21:03 -07:00
return $twig->parse($stream);
}
2014-05-14 23:24:20 +10:00
/**
* Parses the settings array.
* Child classes can override this method in order to update
* the content of the $settings property after the object
* is loaded from a file.
*/
2014-10-11 01:22:03 +02:00
protected function parseSettings()
{
}
2014-05-14 23:24:20 +10:00
/**
* Initializes the object properties from the cached data.
* @param array $cached The cached data array.
*/
protected function initFromCache($cached)
{
$this->settings = $cached['settings'];
$this->code = $cached['code'];
$this->markup = $cached['markup'];
}
/**
* Initializes a cache item.
* @param array &$item The cached item array.
*/
protected function initCacheItem(&$item)
{
$item['settings'] = $this->settings;
$item['code'] = $this->code;
$item['markup'] = $this->markup;
}
/**
* Validates the object properties.
* Throws a ValidationException in case of an error.
*/
protected function validate()
{
2014-10-11 01:22:03 +02:00
$validation = Validator::make(
$this->settings,
$this->settingsValidationRules,
$this->settingsValidationMessages
);
if ($validation->fails()) {
2014-05-14 23:24:20 +10:00
throw new ValidationException($validation);
2014-10-11 01:22:03 +02:00
}
2014-08-28 19:03:47 +11:00
if ($this->viewBagValidationRules && isset($this->settings['viewBag'])) {
2014-10-11 01:22:03 +02:00
$validation = Validator::make(
$this->settings['viewBag'],
$this->viewBagValidationRules,
$this->viewBagValidationMessages
);
if ($validation->fails()) {
2014-08-28 19:03:47 +11:00
throw new ValidationException($validation);
2014-10-11 01:22:03 +02:00
}
2014-08-28 19:03:47 +11:00
}
2014-05-14 23:24:20 +10:00
}
/**
* Determines if the content of the code section should be wrapped to PHP tags.
* @return boolean
*/
protected function wrapCodeToPhpTags()
{
return true;
}
2014-10-11 01:22:03 +02:00
}