diff --git a/library/Icinga/Web/Widget/AbstractWidget.php b/library/Icinga/Web/Widget/AbstractWidget.php new file mode 100644 index 000000000..bd8e7a8df --- /dev/null +++ b/library/Icinga/Web/Widget/AbstractWidget.php @@ -0,0 +1,133 @@ + + * @author Icinga-Web Team + * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License + */ +abstract class AbstractWidget implements Widget +{ + /** + * If you are going to access the current view with the view() function, + * it's instance is stored here for performance reasons. + * + * @var Zend_View_Abstract + */ + protected static $view; + + abstract public function render(Zend_View_Abstract $view); + + /** + * Getter for widget properties + * + * @param string $key The option you're interested in + * + * @throws ProgrammingError for unknown property name + * + * @return mixed + */ + public function __get($key) + { + if (array_key_exists($key, $this->properties)) { + return $this->properties[$key]; + } + + throw new ProgrammingError( + sprintf( + 'Trying to get invalid "%s" property for %s', + $key, + get_class($this) + ) + ); + } + + /** + * Setter for widget properties + * + * @param string $key The option you want to set + * @param string $val The new value going to be assigned to this option + * + * @throws ProgrammingError for unknown property name + * + * @return mixed + */ + public function __set($key, $val) + { + if (array_key_exists($key, $this->properties)) { + $this->properties[$key] = $val; + return; + } + + throw new ProgrammingError( + sprintf( + 'Trying to set invalid "%s" property in %s. Allowed are: %s', + $key, + get_class($this), + empty($this->properties) + ? 'none' + : implode(', ', array_keys($this->properties)) + ) + ); + } + + /** + * Access the current view + * + * Will instantiate a new one if none exists + * // TODO: App->getView + * + * @return Zend_View_Abstract + */ + protected function view() + { + if (self::$view === null) { + + $renderer = ZfActionHelper::getStaticHelper( + 'viewRenderer' + ); + + if (null === $renderer->view) { + $renderer->initView(); + } + + self::$view = $renderer->view; + } + + return self::$view; + } + + /** + * Cast this widget to a string. Will call your render() function + * + * @return string + */ + public function __toString() + { + try { + $html = $this->render($this->view()); + } catch (Exception $e) { + return htmlspecialchars($e->getMessage()); + } + return $html; + } +}