Remove AbstractWidget and make Widget an interface

As Widget's already denote an abstract concept, the name
'AbstractWidget' is redundant. Also this class didn't do anything except
fetching a view via a singleton (which is now injected into the render method)
and bypassing the PHP class properties by creating a 'properties' array which is
filled with magic getters and setters (which now are simply php class properties)

Further changes:
- toString is removed, as this incorporated a lot of
   application logic which would cause unrecoverable
   errors when throwing exceptions
- renderToHtml is now just render and the view dependency must be
   passed, as a widget shouldn't be responsible for getting
   view instance (this means that <?= $this->tabs ?> is now
   <?= $this->tabs->render($this); ?> in the templates
- Controllers don't have $this->widget anymore as Widgets are
   directly instanciated with their class, allowing better code completion
   and avoiding hidden dependencies, also Widget::create is now removed
   in favor of direct instanciation.

refs #4192
This commit is contained in:
Jannis Moßhammer 2013-08-06 18:00:33 +02:00
parent 4149328216
commit b3e0d5e8ce
26 changed files with 168 additions and 474 deletions

View File

@ -28,7 +28,7 @@
use Icinga\Application\Benchmark;
use Icinga\Authentication\Manager;
use Icinga\Web\ActionController;
use Icinga\Web\Hook\Configuration\ConfigurationTab;
use Icinga\Web\Widget\Tabs;
use Icinga\Web\Hook\Configuration\ConfigurationTabBuilder;
/**
@ -48,7 +48,7 @@ class ConfigurationController extends ActionController
public function indexAction()
{
$tabBuilder = new ConfigurationTabBuilder(
$this->widget('tabs')
new Tabs()
);
$tabBuilder->build();

View File

@ -33,8 +33,7 @@
use Icinga\Web\ActionController;
use Icinga\Application\Icinga;
use Icinga\Web\Hook\Configuration\ConfigurationTabBuilder;
use Icinga\Application\Modules\Manager as ModuleManager;
use Zend_Controller_Action as ZfActionController;
use Icinga\Web\Widget\Tabs;
/**
* Handle module depending frontend actions
@ -60,9 +59,7 @@ class ModulesController extends ActionController
*/
public function indexAction()
{
$tabBuilder = new ConfigurationTabBuilder(
$this->widget('tabs')
);
$tabBuilder = new ConfigurationTabBuilder(new Tabs());
$tabBuilder->build();

View File

@ -1,4 +1,5 @@
<?= $this->tabs; ?>
<?= $this->tabs->render($this); ?>
<h3>Configuration</h3>
<p>

View File

@ -3,7 +3,7 @@ $this->modules->limit(10);
$modules = $this->modules->paginate();
?>
<?= $this->tabs; ?>
<?= $this->tabs->render($this); ?>
<h3>Installed Modules</h3>
<?= $this->paginationControl($modules, null, null, array(
'preserve' => $this->preserve

View File

@ -153,19 +153,6 @@ class ActionController extends ZfController
return t($string);
}
/**
* Helper function creating a new widget
*
* @param string $name The widget name
* @param string $properties Optional widget properties
*
* @return Widget\AbstractWidget
*/
public function widget($name, $properties = array())
{
return Widget::create($name, $properties);
}
/**
* Whether the current user has the given permission
*

View File

@ -1,73 +0,0 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* Icinga 2 Web - Head for multiple monitoring frontends
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web;
use Icinga\Exception\ProgrammingError;
/**
* Web widgets make things easier for you!
*
* This class provides nothing but a static factory method for widget creation.
* Usually it will not be used directly as there are widget()-helpers available
* in your action controllers and view scripts.
*
* Usage example:
* <code>
* $tabs = Widget::create('tabs');
* </code>
*
* @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org>
* @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/
class Widget
{
/**
* Create a new widget
*
* @param string $name Widget name
* @param array $options Widget constructor options
*
* @return Icinga\Web\Widget\AbstractWidget
*/
public static function create($name, $options = array(), $module_name = null)
{
$class = 'Icinga\\Web\\Widget\\' . ucfirst($name);
if (! class_exists($class)) {
throw new ProgrammingError(
sprintf(
'There is no such widget: %s',
$name
)
);
}
$widget = new $class($options, $module_name);
return $widget;
}
}

View File

@ -1,167 +0,0 @@
<?php
/**
* Web Widget abstract class
*/
namespace Icinga\Web\Widget;
use Icinga\Exception\ProgrammingError;
use Zend_Controller_Action_HelperBroker as ZfActionHelper;
/**
* Web widgets MUST extend this class
*
* AbstractWidget implements getters and setters for widget options stored in
* the protected options array. If you want to allow options for your own
* widget, you have to set a default value (may be null) for each single option
* in this array.
*
* Please have a look at the available widgets in this folder to get a better
* idea on what they should look like.
*
* @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org>
* @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/
abstract class AbstractWidget
{
/**
* 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;
protected $module_name;
/**
* Fill $properties with default values for all your valid widget properties
*
* @var array
*/
protected $properties = array();
/**
* You MUST extend this function. This is where all your HTML voodoo happens
*
* @return string
*/
abstract public function renderAsHtml();
/**
* You are not allowed to override the constructor, but you can put
* initialization stuff in your init() function
*
* @return void
*/
protected function init()
{
}
/**
* We are not allowing you to override the constructor unless someone
* presents a very good reason for doing so
*
* @param array $properties An optional properties array
*/
final public function __construct($properties = array(), $module_name = null)
{
if ($module_name !== null) {
$this->module_name = $module_name;
}
foreach ($properties as $key => $val) {
$this->$key = $val;
}
$this->init();
}
/**
* 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 renderAsHtml() function
*
* @return string
*/
public function __toString()
{
return $this->renderAsHtml();
}
}

View File

@ -4,13 +4,16 @@ namespace Icinga\Web\Widget;
use Icinga\Application\Icinga;
use Icinga\Config\Config;
use Icinga\Web\Widget;
use Icinga\Web\Widget\Widget;
use Icinga\Web\Widget\Dashboard\Pane;
use Icinga\Web\Url;
use Zend_Config as ZfConfig;
class Dashboard extends AbstractWidget
class Dashboard implements Widget
{
/**
* @var Config
*/
protected $config;
protected $configfile;
protected $panes = array();
@ -24,7 +27,7 @@ class Dashboard extends AbstractWidget
protected function init()
{
if ($this->url === null) {
$this->url = Url::fromRequest()->without($this->tabParam);
$this->url = Url::fromRequest()->getUrlWithout($this->tabParam);
}
}
@ -36,7 +39,7 @@ class Dashboard extends AbstractWidget
public function tabs()
{
if ($this->tabs === null) {
$this->tabs = Widget::create('tabs');
$this->tabs = new Tabs();
foreach ($this->panes as $key => $pane) {
$this->tabs->add($key, array(
'title' => $pane->getTitle(),
@ -65,8 +68,7 @@ class Dashboard extends AbstractWidget
public function readConfig(ZfConfig $config)
{
$this->configfile = Config::getInstance()->getConfigDir()
. '/dashboard.ini';
$this->configfile = Icinga::app('dashboard')->getApplicationDir("dashboard");
$this->config = $config;
$this->panes = array();
$this->loadConfigPanes();
@ -128,7 +130,7 @@ class Dashboard extends AbstractWidget
return $this->panes[$name];
}
public function renderAsHtml()
public function render(\Zend_View_Abstract $view)
{
if (empty($this->panes)) {
return '';
@ -164,7 +166,7 @@ class Dashboard extends AbstractWidget
protected function loadConfigPanes()
{
$items = $this->config->dashboard->toArray();
$items = $this->config->keys();
$app = Icinga::app();
foreach ($items as $key => $item) {
if (false === strstr($key, '.')) {

View File

@ -1,21 +1,18 @@
<?php
/**
* Form
*/
namespace Icinga\Web\Widget;
use Icinga\Exception\ProgrammingError;
use Icinga\Application\Icinga;
/**
* A form loader...
* A form loader
*
* @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org>
* @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/
class Form extends AbstractWidget
class Form
{
protected $form;
protected $properties = array(
@ -74,7 +71,7 @@ class Form extends AbstractWidget
$this->form = new $class($this->options);
}
public function renderAsHtml()
public function render()
{
return (string) $this->form;
}

View File

@ -1,8 +1,5 @@
<?php
/**
* Single tab
*/
namespace Icinga\Web\Widget;
use Icinga\Exception\ProgrammingError;
@ -24,27 +21,102 @@ use Icinga\Exception\ProgrammingError;
* @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/
class Tab extends AbstractWidget
class Tab implements Widget
{
/**
* Whether this tab is currently active
*
* @var bool
*/
protected $active = false;
private $active = false;
/**
* Default values for widget properties
*
* @var array
*/
protected $properties = array(
'name' => null,
'title' => '',
'url' => null,
'urlParams' => array(),
'icon' => null,
);
private $name = null;
private $title = '';
private $url = null;
private $urlParams = array();
private $icon = null;
/**
* @param mixed $icon
*/
public function setIcon($icon)
{
$this->icon = $icon;
}
/**
* @return mixed
*/
public function getIcon()
{
return $this->icon;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @return mixed
*/
public function getUrl()
{
return $this->url;
}
public function __construct(array $properties = array())
{
foreach ($properties as $name=>$value) {
$setter = 'set'.ucfirst($name);
if (method_exists($this, $setter)) {
$this->$setter($value);
}
}
}
/**
* Health check at initialization time
@ -56,9 +128,7 @@ class Tab extends AbstractWidget
protected function init()
{
if ($this->name === null) {
throw new ProgrammingError(
'Cannot create a nameless tab'
);
throw new ProgrammingError('Cannot create a nameless tab');
}
}
@ -93,16 +163,15 @@ class Tab extends AbstractWidget
*
* @return string
*/
public function renderAsHtml()
public function render(\Zend_View_Abstract $view)
{
$view = $this->view();
$class = $this->isActive() ? ' class="active"' : '';
$caption = $this->title;
if ($this->icon !== null) {
$caption = $view->img($this->icon, array(
'width' => 16,
'height' => 16
)) . ' ' . $caption;
'width' => 16,
'height' => 16
)) . ' ' . $caption;
}
if ($this->url !== null) {
$tab = $view->qlink(
@ -114,6 +183,8 @@ class Tab extends AbstractWidget
} else {
$tab = $caption;
}
return "<li $class>$tab</li>\n";
}
}

View File

@ -1,12 +1,10 @@
<?php
/**
* Navigation tabs
*/
namespace Icinga\Web\Widget;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Url;
use Zend_Controller_Action_HelperBroker as ZfActionHelper;
use Countable;
@ -19,30 +17,30 @@ use Countable;
* @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/
class Tabs extends AbstractWidget implements Countable
class Tabs implements Countable, Widget
{
/**
* This is where single tabs added to this container will be stored
*
* @var array
*/
protected $tabs = array();
private $tabs = array();
/**
* The name of the currently activated tab
*
* @var string
*/
protected $active;
private $active;
/**
* Class name(s) going to be assigned to the &lt;ul&gt; element
*
* @var string
*/
protected $tab_class = 'nav-tabs';
private $tab_class = 'nav-tabs';
protected $specialActions = false;
private $specialActions = false;
/**
* Activate the tab with the given name
@ -188,48 +186,46 @@ class Tabs extends AbstractWidget implements Countable
*
* @return string
*/
public function renderAsHtml()
public function render(\Zend_View_Abstract $view)
{
$view = $this->view();
if (empty($this->tabs)) {
return '';
}
$html = '<ul class="nav ' . $this->tab_class . '">' . "\n";
foreach ($this->tabs as $tab) {
$html .= $tab;
$html .= $tab->render($view);
}
$special = array();
$special[] = $this->view()->qlink(
$this->view()->img('img/classic/application-pdf.png') . ' PDF',
$special[] = $view->qlink(
$view->img('img/classic/application-pdf.png') . ' PDF',
Url::fromRequest(),
array('filetype' => 'pdf'),
array('target' => '_blank', 'quote' => false)
);
$special[] = $this->view()->qlink(
$this->view()->img('img/classic/application-csv.png') . ' CSV',
$special[] = $view->qlink(
$view->img('img/classic/application-csv.png') . ' CSV',
Url::fromRequest(),
array('format' => 'csv'),
array('target' => '_blank', 'quote' => false)
);
$special[] = $this->view()->qlink(
$this->view()->img('img/classic/application-json.png') . ' JSON',
$special[] = $view->qlink(
$view->img('img/classic/application-json.png') . ' JSON',
Url::fromRequest(),
array('format' => 'json', 'quote' => false),
array('target' => '_blank', 'quote' => false)
);
$special[] = $this->view()->qlink(
$this->view()->img('img/classic/basket.png') . ' URL Basket',
$special[] = $view->qlink(
$view->img('img/classic/basket.png') . ' URL Basket',
Url::fromPath('basket/add'),
array('url' => Url::fromRequest()->getRelativeUrl()),
array('quote' => false)
);
$special[] = $this->view()->qlink(
$this->view()->img('img/classic/dashboard.png') . ' Dashboard',
$special[] = $view->qlink(
$view->img('img/classic/dashboard.png') . ' Dashboard',
Url::fromPath('dashboard/addurl'),
array('url' => Url::fromRequest()->getRelativeUrl()),
array('quote' => false)
@ -255,6 +251,7 @@ class Tabs extends AbstractWidget implements Countable
return $html;
}
public function count()
{
return count($this->tabs);

View File

@ -0,0 +1,18 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: moja
* Date: 8/5/13
* Time: 11:58 AM
* To change this template use File | Settings | File Templates.
*/
namespace Icinga\Web\Widget;
use Icinga\Web\View;
interface Widget {
public function render(\Zend_View_Abstract $view);
}

View File

@ -5,6 +5,7 @@ use Icinga\Web\Hook;
use Icinga\File\Csv;
use Monitoring\Backend;
use Icinga\Application\Benchmark;
use Icinga\Web\Widget\Tabs;
class Monitoring_ListController extends ModuleActionController
{
@ -213,7 +214,7 @@ class Monitoring_ListController extends ModuleActionController
protected function getTabs()
{
$tabs = $this->widget('tabs');
$tabs = new Tabs();
$tabs->add('services', array(
'title' => 'All services',
'icon' => 'img/classic/service.png',

View File

@ -33,6 +33,7 @@ use Icinga\Web\Hook;
use Monitoring\Object\Host;
use Monitoring\Object\Service;
use Icinga\Application\Benchmark;
use Icinga\Web\Widget\Tabs;
/**
* Class Monitoring_ShowController
*
@ -425,7 +426,7 @@ class Monitoring_ShowController extends ModuleActionController
protected function createTabs()
{
$object = $this->view->object;
$tabs = $this->widget('tabs');
$tabs = new Tabs();
if (!$this->view->host) {
return $tabs;
}

View File

@ -2,6 +2,7 @@
use Icinga\Web\ModuleActionController;
use Icinga\Backend;
use Icinga\Web\Widget\Tabs;
class Monitoring_SummaryController extends ModuleActionController
{
@ -18,7 +19,7 @@ class Monitoring_SummaryController extends ModuleActionController
protected function getTabs()
{
$tabs = $this->widget('tabs');
$tabs = new Tabs();
$tabs->add('hostgroup', array(
'title' => 'Hostgroups',
'url' => 'monitoring/summary/group',

View File

@ -1,4 +1,5 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<pre>
<?= $this->escape(print_r($this->contactgroups->fetchAll(), 1)) ?>
</pre>

View File

@ -1,4 +1,5 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<pre>
<?= $this->escape(print_r($this->contacts->fetchAll(), 1)) ?>
</pre>

View File

@ -1,4 +1,4 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<?php
/**

View File

@ -1,4 +1,5 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<pre>
<?= $this->escape(print_r($this->hostgroups->fetchAll(), 1)) ?>
</pre>

View File

@ -1,4 +1,4 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<?php
$hosts = $this->hosts->paginate();

View File

@ -1,4 +1,5 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<pre>
<?= $this->escape(print_r($this->servicegroups->fetchAll(), 1)) ?>
</pre>

View File

@ -1,4 +1,4 @@
<?= $this->tabs ?>
<?= $this->tabs->render($this); ?>
<?php
$paginator = $services->paginate();

View File

@ -13,7 +13,8 @@ if ($this->tabs->getActiveName() === 'history') {
}
if (!$this->compact) {
echo $this->tabs;
echo $this->tabs->render($this);
}
?>
<div class="information-container">

View File

@ -6,7 +6,7 @@ require_once '../../library/Icinga/Web/Hook/Configuration/ConfigurationTabInterf
require_once '../../library/Icinga/Web/Hook/Configuration/ConfigurationTab.php';
require_once '../../library/Icinga/Web/Hook/Configuration/ConfigurationTabBuilder.php';
require_once '../../library/Icinga/Web/Hook.php';
require_once '../../library/Icinga/Web/Widget/AbstractWidget.php';
require_once '../../library/Icinga/Web/Widget/Widget.php';
require_once '../../library/Icinga/Web/Widget/Tabs.php';
require_once '../../library/Icinga/Web/Widget/Tab.php';
require_once '../../library/Icinga/Exception/ProgrammingError.php';

View File

@ -1,113 +0,0 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: mhein
* Date: 6/10/13
* Time: 1:31 PM
* To change this template use File | Settings | File Templates.
*/
namespace Tests\Icinga\Web\Widget;
require_once '../../library/Icinga/Exception/ProgrammingError.php';
require_once '../../library/Icinga/Web/Widget.php';
require_once '../../library/Icinga/Web/Widget/AbstractWidget.php';
require_once 'Zend/View.php';
require_once 'Zend/Controller/Action/HelperBroker.php';
use Icinga\Web\Widget\AbstractWidget;
/**
* Class TestWidget
* @package Tests\Icinga\Web\Widget
* @property boolean $test1
* @property boolean $test2
*/
class TestWidget extends AbstractWidget
{
protected $properties = array(
'test1' => true,
'test2' => false
);
public function renderAsHtml()
{
return "ok123123";
}
}
class TestWidget2 extends AbstractWidget
{
protected function init()
{
$this->view();
}
public function getView()
{
return $this->view();
}
public function renderAsHtml()
{
return "ok123123";
}
}
class AbstractWidgetTest extends \PHPUnit_Framework_TestCase
{
public function testAbstractImplementation1()
{
$widget = new TestWidget(
array(
'test1' => false,
'test2' => true
)
);
$this->assertTrue($widget->test2);
$this->assertFalse($widget->test1);
$this->assertEquals('ok123123', (string)$widget);
$this->assertEquals('ok123123', $widget->renderAsHtml());
}
/**
* @expectedException Icinga\Exception\ProgrammingError
* @expectedExceptionMessage Trying to set invalid "test3" property in Tests\Icinga\Web\Widget\TestWidget. Allowed are: test1, test2
*/
public function testSetFail1()
{
$widget = new TestWidget();
$widget->test3 = true;
}
/**
* @expectedException Icinga\Exception\ProgrammingError
* @expectedExceptionMessage Trying to set invalid "unknown" property in Tests\Icinga\Web\Widget\TestWidget2. Allowed are: none
*/
public function testSetFail2()
{
$widget = new TestWidget2();
$widget->unknown = true;
}
/**
* @expectedException Icinga\Exception\ProgrammingError
* @expectedExceptionMessage Trying to get invalid "test3" property for Tests\Icinga\Web\Widget\TestWidget
*/
public function testGetFail()
{
$widget = new TestWidget();
$target = $widget->test3;
}
public function testView1()
{
$widget = new TestWidget2();
$view = $widget->getView();
$this->assertInstanceOf('Zend_View', $view);
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace Tests\Icinga\Web;
use Icinga\Web\Widget;
require_once '../../library/Icinga/Web/Widget.php';
require_once '../../library/Icinga/Web/Widget/AbstractWidget.php';
require_once '../../library/Icinga/Web/Widget/Tab.php';
require_once '../../library/Icinga/Exception/ProgrammingError.php';
class WidgetTest extends \PHPUnit_Framework_TestCase
{
public function testCreate1()
{
$widgetCreator = new Widget();
$widget = $widgetCreator->create('tab', array('name' => 'TEST'));
$this->assertInstanceOf('Icinga\Web\Widget\Tab', $widget);
}
/**
* @expectedException Icinga\Exception\ProgrammingError
* @expectedExceptionMessage There is no such widget: DOES_NOT_EXIST
*/
public function testFail1()
{
$widgetCreator = new Widget();
$widget = $widgetCreator->create('DOES_NOT_EXIST');
}
}