Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-12-16 11:06:45 +13:00
parent a09795b3a2
commit 93fced94f1
4 changed files with 796 additions and 705 deletions

View File

@ -29,318 +29,351 @@
* *
* @package reports * @package reports
*/ */
class SS_Report extends ViewableData { class SS_Report extends ViewableData
/** {
* This is the title of the report, /**
* used by the ReportAdmin templates. * This is the title of the report,
* * used by the ReportAdmin templates.
* @var string *
*/ * @var string
protected $title = ''; */
protected $title = '';
/** /**
* This is a description about what this * This is a description about what this
* report does. Used by the ReportAdmin * report does. Used by the ReportAdmin
* templates. * templates.
* *
* @var string * @var string
*/ */
protected $description = ''; protected $description = '';
/** /**
* The class of object being managed by this report. * The class of object being managed by this report.
* Set by overriding in your subclass. * Set by overriding in your subclass.
*/ */
protected $dataClass = 'SiteTree'; protected $dataClass = 'SiteTree';
/** /**
* A field that specifies the sort order of this report * A field that specifies the sort order of this report
* @var int * @var int
*/ */
protected $sort = 0; protected $sort = 0;
/** /**
* Reports which should not be collected and returned in get_reports * Reports which should not be collected and returned in get_reports
* @var array * @var array
*/ */
public static $excluded_reports = array( public static $excluded_reports = array(
'SS_Report', 'SS_Report',
'SS_ReportWrapper', 'SS_ReportWrapper',
'SideReportWrapper' 'SideReportWrapper'
); );
/** /**
* Return the title of this report. * Return the title of this report.
* *
* You have two ways of specifying the description: * You have two ways of specifying the description:
* - overriding description(), which lets you support i18n * - overriding description(), which lets you support i18n
* - defining the $description property * - defining the $description property
*/ */
public function title() { public function title()
return $this->title; {
} return $this->title;
}
/**
* Allows access to title as a property /**
* * Allows access to title as a property
* @return string *
*/ * @return string
public function getTitle() { */
return $this->title(); public function getTitle()
} {
return $this->title();
/** }
* Return the description of this report.
* /**
* You have two ways of specifying the description: * Return the description of this report.
* - overriding description(), which lets you support i18n *
* - defining the $description property * You have two ways of specifying the description:
*/ * - overriding description(), which lets you support i18n
public function description() { * - defining the $description property
return $this->description; */
} public function description()
{
/** return $this->description;
* Return the {@link SQLQuery} that provides your report data. }
*/
public function sourceQuery($params) { /**
if($this->hasMethod('sourceRecords')) { * Return the {@link SQLQuery} that provides your report data.
return $this->sourceRecords()->dataQuery(); */
} else { public function sourceQuery($params)
user_error("Please override sourceQuery()/sourceRecords() and columns() or, if necessary, override getReportField()", E_USER_ERROR); {
} if ($this->hasMethod('sourceRecords')) {
} return $this->sourceRecords()->dataQuery();
} else {
/** user_error("Please override sourceQuery()/sourceRecords() and columns() or, if necessary, override getReportField()", E_USER_ERROR);
* Return a SS_List records for this report. }
*/ }
public function records($params) {
if($this->hasMethod('sourceRecords')) { /**
return $this->sourceRecords($params, null, null); * Return a SS_List records for this report.
} else { */
$query = $this->sourceQuery(); public function records($params)
$results = new ArrayList(); {
foreach($query->execute() as $data) { if ($this->hasMethod('sourceRecords')) {
$class = $this->dataClass(); return $this->sourceRecords($params, null, null);
$result = new $class($data); } else {
$results->push($result); $query = $this->sourceQuery();
} $results = new ArrayList();
return $results; foreach ($query->execute() as $data) {
} $class = $this->dataClass();
} $result = new $class($data);
$results->push($result);
}
return $results;
}
}
/** /**
* Return the data class for this report * Return the data class for this report
*/ */
public function dataClass() { public function dataClass()
return $this->dataClass; {
} return $this->dataClass;
}
public function getLink($action = null) { public function getLink($action = null)
return Controller::join_links( {
'admin/reports/', return Controller::join_links(
"$this->class", 'admin/reports/',
'/', // trailing slash needed if $action is null! "$this->class",
"$action" '/', // trailing slash needed if $action is null!
); "$action"
} );
}
/** /**
* counts the number of objects returned * counts the number of objects returned
* @param Array $params - any parameters for the sourceRecords * @param Array $params - any parameters for the sourceRecords
* @return Int * @return Int
*/ */
public function getCount($params = array()){ public function getCount($params = array())
$sourceRecords = $this->sourceRecords($params, null, null); {
if(!$sourceRecords instanceOf SS_List){ $sourceRecords = $this->sourceRecords($params, null, null);
user_error($this->class."::sourceRecords does not return an SS_List", E_USER_NOTICE); if (!$sourceRecords instanceof SS_List) {
return "-1"; user_error($this->class."::sourceRecords does not return an SS_List", E_USER_NOTICE);
} return "-1";
return $sourceRecords->count(); }
} return $sourceRecords->count();
}
/** /**
* Exclude certain reports classes from the list of Reports in the CMS * Exclude certain reports classes from the list of Reports in the CMS
* @param $reportClass Can be either a string with the report classname or an array of reports classnames * @param $reportClass Can be either a string with the report classname or an array of reports classnames
*/ */
static public function add_excluded_reports($reportClass) { public static function add_excluded_reports($reportClass)
if (is_array($reportClass)) { {
self::$excluded_reports = array_merge(self::$excluded_reports, $reportClass); if (is_array($reportClass)) {
} else { self::$excluded_reports = array_merge(self::$excluded_reports, $reportClass);
if (is_string($reportClass)) { } else {
//add to the excluded reports, so this report doesn't get used if (is_string($reportClass)) {
self::$excluded_reports[] = $reportClass; //add to the excluded reports, so this report doesn't get used
} self::$excluded_reports[] = $reportClass;
} }
} }
}
/** /**
* Return an array of excluded reports. That is, reports that will not be included in * Return an array of excluded reports. That is, reports that will not be included in
* the list of reports in report admin in the CMS. * the list of reports in report admin in the CMS.
* @return array * @return array
*/ */
static public function get_excluded_reports() { public static function get_excluded_reports()
return self::$excluded_reports; {
} return self::$excluded_reports;
}
/** /**
* Return the SS_Report objects making up the given list. * Return the SS_Report objects making up the given list.
* @return Array of SS_Report objects * @return Array of SS_Report objects
*/ */
static public function get_reports() { public static function get_reports()
$reports = ClassInfo::subclassesFor(get_called_class()); {
$reports = ClassInfo::subclassesFor(get_called_class());
$reportsArray = array(); $reportsArray = array();
if ($reports && count($reports) > 0) { if ($reports && count($reports) > 0) {
//collect reports into array with an attribute for 'sort' //collect reports into array with an attribute for 'sort'
foreach($reports as $report) { foreach ($reports as $report) {
if (in_array($report, self::$excluded_reports)) continue; //don't use the SS_Report superclass if (in_array($report, self::$excluded_reports)) {
$reflectionClass = new ReflectionClass($report); continue;
if ($reflectionClass->isAbstract()) continue; //don't use abstract classes } //don't use the SS_Report superclass
$reflectionClass = new ReflectionClass($report);
if ($reflectionClass->isAbstract()) {
continue;
} //don't use abstract classes
$reportObj = new $report; $reportObj = new $report;
if (method_exists($reportObj,'sort')) $reportObj->sort = $reportObj->sort(); //use the sort method to specify the sort field if (method_exists($reportObj, 'sort')) {
$reportsArray[$report] = $reportObj; $reportObj->sort = $reportObj->sort();
} } //use the sort method to specify the sort field
} $reportsArray[$report] = $reportObj;
}
}
uasort($reportsArray, function($a, $b) { uasort($reportsArray, function ($a, $b) {
if($a->sort == $b->sort) return 0; if ($a->sort == $b->sort) {
else return ($a->sort < $b->sort) ? -1 : 1; return 0;
}); } else {
return ($a->sort < $b->sort) ? -1 : 1;
}
});
return $reportsArray; return $reportsArray;
} }
/////////////////////// UI METHODS /////////////////////// /////////////////////// UI METHODS ///////////////////////
/** /**
* Returns a FieldList with which to create the CMS editing form. * Returns a FieldList with which to create the CMS editing form.
* You can use the extend() method of FieldList to create customised forms for your other * You can use the extend() method of FieldList to create customised forms for your other
* data objects. * data objects.
* *
* @uses getReportField() to render a table, or similar field for the report. This * @uses getReportField() to render a table, or similar field for the report. This
* method should be defined on the SS_Report subclasses. * method should be defined on the SS_Report subclasses.
* *
* @return FieldList * @return FieldList
*/ */
public function getCMSFields() { public function getCMSFields()
$fields = new FieldList(); {
$fields = new FieldList();
if($title = $this->title()) { if ($title = $this->title()) {
$fields->push(new LiteralField('ReportTitle', "<h3>{$title}</h3>")); $fields->push(new LiteralField('ReportTitle', "<h3>{$title}</h3>"));
} }
if($description = $this->description()) { if ($description = $this->description()) {
$fields->push(new LiteralField('ReportDescription', "<p>" . $description . "</p>")); $fields->push(new LiteralField('ReportDescription', "<p>" . $description . "</p>"));
} }
// Add search fields is available // Add search fields is available
if($this->hasMethod('parameterFields') && $parameterFields = $this->parameterFields()) { if ($this->hasMethod('parameterFields') && $parameterFields = $this->parameterFields()) {
foreach($parameterFields as $field) { foreach ($parameterFields as $field) {
// Namespace fields for easier handling in form submissions // Namespace fields for easier handling in form submissions
$field->setName(sprintf('filters[%s]', $field->getName())); $field->setName(sprintf('filters[%s]', $field->getName()));
$field->addExtraClass('no-change-track'); // ignore in changetracker $field->addExtraClass('no-change-track'); // ignore in changetracker
$fields->push($field); $fields->push($field);
} }
// Add a search button // Add a search button
$fields->push(new FormAction('updatereport', _t('GridField.Filter'))); $fields->push(new FormAction('updatereport', _t('GridField.Filter')));
} }
$fields->push($this->getReportField()); $fields->push($this->getReportField());
$this->extend('updateCMSFields', $fields); $this->extend('updateCMSFields', $fields);
return $fields; return $fields;
} }
public function getCMSActions() { public function getCMSActions()
// getCMSActions() can be extended with updateCMSActions() on a extension {
$actions = new FieldList(); // getCMSActions() can be extended with updateCMSActions() on a extension
$this->extend('updateCMSActions', $actions); $actions = new FieldList();
return $actions; $this->extend('updateCMSActions', $actions);
} return $actions;
}
/**
* Return a field, such as a {@link GridField} that is /**
* used to show and manipulate data relating to this report. * Return a field, such as a {@link GridField} that is
* * used to show and manipulate data relating to this report.
* Generally, you should override {@link columns()} and {@link records()} to make your report, *
* but if they aren't sufficiently flexible, then you can override this method. * Generally, you should override {@link columns()} and {@link records()} to make your report,
* * but if they aren't sufficiently flexible, then you can override this method.
* @return FormField subclass *
*/ * @return FormField subclass
public function getReportField() { */
// TODO Remove coupling with global state public function getReportField()
$params = isset($_REQUEST['filters']) ? $_REQUEST['filters'] : array(); {
$items = $this->sourceRecords($params, null, null); // TODO Remove coupling with global state
$params = isset($_REQUEST['filters']) ? $_REQUEST['filters'] : array();
$items = $this->sourceRecords($params, null, null);
$gridFieldConfig = GridFieldConfig::create()->addComponents( $gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(), new GridFieldToolbarHeader(),
new GridFieldSortableHeader(), new GridFieldSortableHeader(),
new GridFieldDataColumns(), new GridFieldDataColumns(),
new GridFieldPaginator(), new GridFieldPaginator(),
new GridFieldButtonRow('after'), new GridFieldButtonRow('after'),
new GridFieldPrintButton('buttons-after-left'), new GridFieldPrintButton('buttons-after-left'),
new GridFieldExportButton('buttons-after-left') new GridFieldExportButton('buttons-after-left')
); );
$gridField = new GridField('Report',$this->title(), $items, $gridFieldConfig); $gridField = new GridField('Report', $this->title(), $items, $gridFieldConfig);
$columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns'); $columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
$displayFields = array(); $displayFields = array();
$fieldCasting = array(); $fieldCasting = array();
$fieldFormatting = array(); $fieldFormatting = array();
// Parse the column information // Parse the column information
foreach($this->columns() as $source => $info) { foreach ($this->columns() as $source => $info) {
if(is_string($info)) $info = array('title' => $info); if (is_string($info)) {
$info = array('title' => $info);
if(isset($info['formatting'])) $fieldFormatting[$source] = $info['formatting']; }
if(isset($info['csvFormatting'])) $csvFieldFormatting[$source] = $info['csvFormatting'];
if(isset($info['casting'])) $fieldCasting[$source] = $info['casting']; if (isset($info['formatting'])) {
$fieldFormatting[$source] = $info['formatting'];
}
if (isset($info['csvFormatting'])) {
$csvFieldFormatting[$source] = $info['csvFormatting'];
}
if (isset($info['casting'])) {
$fieldCasting[$source] = $info['casting'];
}
if(isset($info['link']) && $info['link']) { if (isset($info['link']) && $info['link']) {
$link = singleton('CMSPageEditController')->Link('show'); $link = singleton('CMSPageEditController')->Link('show');
$fieldFormatting[$source] = '<a href=\"' . $link . '/$ID\">$value</a>'; $fieldFormatting[$source] = '<a href=\"' . $link . '/$ID\">$value</a>';
} }
$displayFields[$source] = isset($info['title']) ? $info['title'] : $source; $displayFields[$source] = isset($info['title']) ? $info['title'] : $source;
} }
$columns->setDisplayFields($displayFields); $columns->setDisplayFields($displayFields);
$columns->setFieldCasting($fieldCasting); $columns->setFieldCasting($fieldCasting);
$columns->setFieldFormatting($fieldFormatting); $columns->setFieldFormatting($fieldFormatting);
return $gridField; return $gridField;
} }
/** /**
* @param Member $member * @param Member $member
* @return boolean * @return boolean
*/ */
public function canView($member = null) { public function canView($member = null)
if(!$member && $member !== FALSE) { {
$member = Member::currentUser(); if (!$member && $member !== false) {
} $member = Member::currentUser();
}
return true;
} return true;
}
/**
* Return the name of this report, which
* is used by the templates to render the
* name of the report in the report tree,
* the left hand pane inside ReportAdmin.
*
* @return string
*/
public function TreeTitle() {
return $this->title();
}
/**
* Return the name of this report, which
* is used by the templates to render the
* name of the report in the report tree,
* the left hand pane inside ReportAdmin.
*
* @return string
*/
public function TreeTitle()
{
return $this->title();
}
} }
/** /**
@ -358,92 +391,104 @@ class SS_Report extends ViewableData {
* *
* @package reports * @package reports
*/ */
abstract class SS_ReportWrapper extends SS_Report { abstract class SS_ReportWrapper extends SS_Report
protected $baseReport; {
protected $baseReport;
public function __construct($baseReport) { public function __construct($baseReport)
$this->baseReport = is_string($baseReport) ? new $baseReport : $baseReport; {
$this->dataClass = $this->baseReport->dataClass(); $this->baseReport = is_string($baseReport) ? new $baseReport : $baseReport;
parent::__construct(); $this->dataClass = $this->baseReport->dataClass();
} parent::__construct();
}
public function ID() { public function ID()
return get_class($this->baseReport) . '_' . get_class($this); {
} return get_class($this->baseReport) . '_' . get_class($this);
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Filtering // Filtering
public function parameterFields() { public function parameterFields()
return $this->baseReport->parameterFields(); {
} return $this->baseReport->parameterFields();
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Columns // Columns
public function columns() { public function columns()
return $this->baseReport->columns(); {
} return $this->baseReport->columns();
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Querying // Querying
/** /**
* Override this method to perform some actions prior to querying. * Override this method to perform some actions prior to querying.
*/ */
public function beforeQuery($params) { public function beforeQuery($params)
} {
}
/** /**
* Override this method to perform some actions after querying. * Override this method to perform some actions after querying.
*/ */
public function afterQuery() {} public function afterQuery()
{
}
public function sourceQuery($params) { public function sourceQuery($params)
if($this->baseReport->hasMethod('sourceRecords')) { {
// The default implementation will create a fake query from our sourceRecords() method if ($this->baseReport->hasMethod('sourceRecords')) {
return parent::sourceQuery($params); // The default implementation will create a fake query from our sourceRecords() method
return parent::sourceQuery($params);
} elseif ($this->baseReport->hasMethod('sourceQuery')) {
$this->beforeQuery($params);
$query = $this->baseReport->sourceQuery($params);
$this->afterQuery();
return $query;
} else {
user_error("Please override sourceQuery()/sourceRecords() and columns() in your base report", E_USER_ERROR);
}
}
} else if($this->baseReport->hasMethod('sourceQuery')) { public function sourceRecords($params = array(), $sort = null, $limit = null)
$this->beforeQuery($params); {
$query = $this->baseReport->sourceQuery($params); $this->beforeQuery($params);
$this->afterQuery(); $records = $this->baseReport->sourceRecords($params, $sort, $limit);
return $query; $this->afterQuery();
return $records;
} else { }
user_error("Please override sourceQuery()/sourceRecords() and columns() in your base report", E_USER_ERROR);
}
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
$this->beforeQuery($params);
$records = $this->baseReport->sourceRecords($params, $sort, $limit);
$this->afterQuery();
return $records;
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Pass-through // Pass-through
public function title() { public function title()
return $this->baseReport->title(); {
} return $this->baseReport->title();
}
public function group() {
return $this->baseReport->hasMethod('group') ? $this->baseReport->group() : 'Group'; public function group()
} {
return $this->baseReport->hasMethod('group') ? $this->baseReport->group() : 'Group';
public function sort() { }
return $this->baseReport->hasMethod('sort') ? $this->baseReport->sort() : 0;
} public function sort()
{
return $this->baseReport->hasMethod('sort') ? $this->baseReport->sort() : 0;
}
public function description() { public function description()
return $this->baseReport->description(); {
} return $this->baseReport->description();
}
public function canView($member = null) { public function canView($member = null)
return $this->baseReport->canView($member); {
} return $this->baseReport->canView($member);
}
} }

View File

@ -10,180 +10,197 @@
* *
* @package reports * @package reports
*/ */
class ReportAdmin extends LeftAndMain implements PermissionProvider { class ReportAdmin extends LeftAndMain implements PermissionProvider
{
private static $url_segment = 'reports';
private static $url_segment = 'reports';
private static $url_rule = '/$ReportClass/$Action';
private static $url_rule = '/$ReportClass/$Action';
private static $menu_title = 'Reports';
private static $menu_title = 'Reports';
private static $template_path = null; // defaults to (project)/templates/email
private static $template_path = null; // defaults to (project)/templates/email
private static $tree_class = 'SS_Report';
private static $url_handlers = array( private static $tree_class = 'SS_Report';
'$ReportClass/$Action' => 'handleAction'
);
/** private static $url_handlers = array(
* Variable that describes which report we are currently viewing based on '$ReportClass/$Action' => 'handleAction'
* the URL (gets set in init method). );
*
* @var string
*/
protected $reportClass;
protected $reportObject; /**
* Variable that describes which report we are currently viewing based on
public function init() { * the URL (gets set in init method).
parent::init(); *
* @var string
*/
protected $reportClass;
//set the report we are currently viewing from the URL protected $reportObject;
$this->reportClass = (isset($this->urlParams['ReportClass']) && $this->urlParams['ReportClass'] !== 'index')
? $this->urlParams['ReportClass'] public function init()
: null; {
$allReports = SS_Report::get_reports(); parent::init();
$this->reportObject = (isset($allReports[$this->reportClass])) ? $allReports[$this->reportClass] : null;
// Set custom options for TinyMCE specific to ReportAdmin //set the report we are currently viewing from the URL
HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css'); $this->reportClass = (isset($this->urlParams['ReportClass']) && $this->urlParams['ReportClass'] !== 'index')
HtmlEditorConfig::get('cms')->setOption('Lang', i18n::get_tinymce_lang()); ? $this->urlParams['ReportClass']
: null;
$allReports = SS_Report::get_reports();
$this->reportObject = (isset($allReports[$this->reportClass])) ? $allReports[$this->reportClass] : null;
// Always block the HtmlEditorField.js otherwise it will be sent with an ajax request // Set custom options for TinyMCE specific to ReportAdmin
Requirements::block(FRAMEWORK_DIR . '/javascript/HtmlEditorField.js'); HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css');
Requirements::javascript(REPORTS_DIR . '/javascript/ReportAdmin.js'); HtmlEditorConfig::get('cms')->setOption('Lang', i18n::get_tinymce_lang());
}
/** // Always block the HtmlEditorField.js otherwise it will be sent with an ajax request
* Does the parent permission checks, but also Requirements::block(FRAMEWORK_DIR . '/javascript/HtmlEditorField.js');
* makes sure that instantiatable subclasses of Requirements::javascript(REPORTS_DIR . '/javascript/ReportAdmin.js');
* {@link Report} exist. By default, the CMS doesn't }
* include any Reports, so there's no point in showing
*
* @param Member $member
* @return boolean
*/
public function canView($member = null) {
if(!$member && $member !== FALSE) $member = Member::currentUser();
if(!parent::canView($member)) return false; /**
* Does the parent permission checks, but also
* makes sure that instantiatable subclasses of
* {@link Report} exist. By default, the CMS doesn't
* include any Reports, so there's no point in showing
*
* @param Member $member
* @return boolean
*/
public function canView($member = null)
{
if (!$member && $member !== false) {
$member = Member::currentUser();
}
$hasViewableSubclasses = false; if (!parent::canView($member)) {
foreach($this->Reports() as $report) { return false;
if($report->canView($member)) return true; }
}
return false; $hasViewableSubclasses = false;
} foreach ($this->Reports() as $report) {
if ($report->canView($member)) {
return true;
}
}
/** return false;
* Return a SS_List of SS_Report subclasses }
* that are available for use.
*
* @return SS_List
*/
public function Reports() {
$output = new ArrayList();
foreach(SS_Report::get_reports() as $report) {
if($report->canView()) $output->push($report);
}
return $output;
}
/** /**
* Determine if we have reports and need * Return a SS_List of SS_Report subclasses
* to display the "Reports" main menu item * that are available for use.
* in the CMS. *
* * @return SS_List
* The test for an existance of a report */
* is done by checking for a subclass of public function Reports()
* "SS_Report" that exists. {
* $output = new ArrayList();
* @return boolean foreach (SS_Report::get_reports() as $report) {
*/ if ($report->canView()) {
public static function has_reports() { $output->push($report);
return sizeof(SS_Report::get_reports()) > 0; }
} }
return $output;
}
/** /**
* Returns the Breadcrumbs for the ReportAdmin * Determine if we have reports and need
* @return ArrayList * to display the "Reports" main menu item
*/ * in the CMS.
public function Breadcrumbs($unlinked = false) { *
$items = parent::Breadcrumbs($unlinked); * The test for an existance of a report
* is done by checking for a subclass of
// The root element should explicitly point to the root node. * "SS_Report" that exists.
// Uses session state for current record otherwise. *
$items[0]->Link = singleton('ReportAdmin')->Link(); * @return boolean
*/
public static function has_reports()
{
return sizeof(SS_Report::get_reports()) > 0;
}
if ($this->reportObject) { /**
//build breadcrumb trail to the current report * Returns the Breadcrumbs for the ReportAdmin
$items->push(new ArrayData(array( * @return ArrayList
'Title' => $this->reportObject->title(), */
'Link' => Controller::join_links($this->Link(), '?' . http_build_query(array('q' => $this->request->requestVar('q')))) public function Breadcrumbs($unlinked = false)
))); {
} $items = parent::Breadcrumbs($unlinked);
// The root element should explicitly point to the root node.
// Uses session state for current record otherwise.
$items[0]->Link = singleton('ReportAdmin')->Link();
return $items; if ($this->reportObject) {
} //build breadcrumb trail to the current report
$items->push(new ArrayData(array(
'Title' => $this->reportObject->title(),
'Link' => Controller::join_links($this->Link(), '?' . http_build_query(array('q' => $this->request->requestVar('q'))))
)));
}
/** return $items;
* Returns the link to the report admin section, or the specific report that is currently displayed }
* @return String
*/
public function Link($action = null) {
if ($this->reportObject) {
$link = $this->reportObject->getLink($action);
} else {
$link = self::join_links(parent::Link('index'), $action);
}
return $link;
}
public function providePermissions() { /**
$title = _t("ReportAdmin.MENUTITLE", LeftAndMain::menu_title_for_class($this->class)); * Returns the link to the report admin section, or the specific report that is currently displayed
return array( * @return String
"CMS_ACCESS_ReportAdmin" => array( */
'name' => _t('CMSMain.ACCESS', "Access to '{title}' section", array('title' => $title)), public function Link($action = null)
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access') {
) if ($this->reportObject) {
); $link = $this->reportObject->getLink($action);
} } else {
$link = self::join_links(parent::Link('index'), $action);
}
return $link;
}
public function getEditForm($id = null, $fields = null) { public function providePermissions()
$report = $this->reportObject; {
if($report) { $title = _t("ReportAdmin.MENUTITLE", LeftAndMain::menu_title_for_class($this->class));
$fields = $report->getCMSFields(); return array(
} else { "CMS_ACCESS_ReportAdmin" => array(
// List all reports 'name' => _t('CMSMain.ACCESS', "Access to '{title}' section", array('title' => $title)),
$fields = new FieldList(); 'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access')
$gridFieldConfig = GridFieldConfig::create()->addComponents( )
new GridFieldToolbarHeader(), );
new GridFieldSortableHeader(), }
new GridFieldDataColumns(),
new GridFieldFooter()
);
$gridField = new GridField('Reports',false, $this->Reports(), $gridFieldConfig);
$columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
$columns->setDisplayFields(array(
'title' => _t('ReportAdmin.ReportTitle', 'Title'),
));
$columns->setFieldFormatting(array( public function getEditForm($id = null, $fields = null)
'title' => '<a href=\"$Link\" class=\"cms-panel-link\">$value ($Count)</a>' {
)); $report = $this->reportObject;
$gridField->addExtraClass('all-reports-gridfield'); if ($report) {
$fields->push($gridField); $fields = $report->getCMSFields();
} } else {
// List all reports
$fields = new FieldList();
$gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldFooter()
);
$gridField = new GridField('Reports', false, $this->Reports(), $gridFieldConfig);
$columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
$columns->setDisplayFields(array(
'title' => _t('ReportAdmin.ReportTitle', 'Title'),
));
$actions = new FieldList(); $columns->setFieldFormatting(array(
$form = new Form($this, "EditForm", $fields, $actions); 'title' => '<a href=\"$Link\" class=\"cms-panel-link\">$value ($Count)</a>'
$form->addExtraClass('cms-edit-form cms-panel-padded center ' . $this->BaseCSSClasses()); ));
$form->loadDataFrom($this->request->getVars()); $gridField->addExtraClass('all-reports-gridfield');
$fields->push($gridField);
}
$this->extend('updateEditForm', $form); $actions = new FieldList();
$form = new Form($this, "EditForm", $fields, $actions);
$form->addExtraClass('cms-edit-form cms-panel-padded center ' . $this->BaseCSSClasses());
$form->loadDataFrom($this->request->getVars());
return $form; $this->extend('updateEditForm', $form);
}
return $form;
}
} }

View File

@ -5,96 +5,105 @@
* *
* @package reports * @package reports
*/ */
class SideReportView extends ViewableData { class SideReportView extends ViewableData
{
protected $controller, $report; protected $controller, $report;
protected $parameters; protected $parameters;
public function __construct($controller, $report) { public function __construct($controller, $report)
$this->controller = $controller; {
$this->report = $report; $this->controller = $controller;
parent::__construct(); $this->report = $report;
} parent::__construct();
}
public function group() {
return _t('SideReport.OtherGroupTitle', "Other"); public function group()
} {
return _t('SideReport.OtherGroupTitle', "Other");
public function sort() { }
return 0;
} public function sort()
{
public function setParameters($parameters) { return 0;
$this->parameters = $parameters; }
}
public function setParameters($parameters)
public function forTemplate() { {
$records = $this->report->records($this->parameters); $this->parameters = $parameters;
$columns = $this->report->columns(); }
if($records && $records->Count()) { public function forTemplate()
$result = "<ul class=\"$this->class\">\n"; {
$records = $this->report->records($this->parameters);
foreach($records as $record) { $columns = $this->report->columns();
$result .= "<li>\n";
foreach($columns as $source => $info) { if ($records && $records->Count()) {
if(is_string($info)) $info = array('title' => $info); $result = "<ul class=\"$this->class\">\n";
$result .= $this->formatValue($record, $source, $info);
} foreach ($records as $record) {
$result .= "\n</li>\n"; $result .= "<li>\n";
} foreach ($columns as $source => $info) {
$result .= "</ul>\n"; if (is_string($info)) {
} else { $info = array('title' => $info);
$result = "<p class=\"message notice\">" . }
_t( $result .= $this->formatValue($record, $source, $info);
'SideReport.REPEMPTY', }
'The {title} report is empty.', $result .= "\n</li>\n";
array('title' => $this->report->title()) }
) $result .= "</ul>\n";
. "</p>"; } else {
} $result = "<p class=\"message notice\">" .
return $result; _t(
} 'SideReport.REPEMPTY',
'The {title} report is empty.',
protected function formatValue($record, $source, $info) { array('title' => $this->report->title())
// Field sources )
//if(is_string($source)) { . "</p>";
$val = Convert::raw2xml($record->$source); }
//} else { return $result;
// $val = $record->val($source[0], $source[1]); }
//}
protected function formatValue($record, $source, $info)
// Casting, a la TableListField. We're deep-calling a helper method on TableListField that {
// should probably be pushed elsewhere... // Field sources
if(!empty($info['casting'])) { //if(is_string($source)) {
$val = TableListField::getCastedValue($val, $info['casting']); $val = Convert::raw2xml($record->$source);
} //} else {
// $val = $record->val($source[0], $source[1]);
// Formatting, a la TableListField //}
if(!empty($info['formatting'])) {
$format = str_replace('$value', "__VAL__", $info['formatting']);
$format = preg_replace('/\$([A-Za-z0-9-_]+)/','$record->$1', $format);
$format = str_replace('__VAL__', '$val', $format);
$val = eval('return "' . $format . '";');
}
$prefix = empty($info['newline']) ? "" : "<br>"; // Casting, a la TableListField. We're deep-calling a helper method on TableListField that
// should probably be pushed elsewhere...
if (!empty($info['casting'])) {
$val = TableListField::getCastedValue($val, $info['casting']);
}
// Formatting, a la TableListField
if (!empty($info['formatting'])) {
$format = str_replace('$value', "__VAL__", $info['formatting']);
$format = preg_replace('/\$([A-Za-z0-9-_]+)/', '$record->$1', $format);
$format = str_replace('__VAL__', '$val', $format);
$val = eval('return "' . $format . '";');
}
$prefix = empty($info['newline']) ? "" : "<br>";
$classClause = "";
if(isset($info['title'])) {
$cssClass = preg_replace('/[^A-Za-z0-9]+/', '', $info['title']); $classClause = "";
$classClause = "class=\"$cssClass\""; if (isset($info['title'])) {
} $cssClass = preg_replace('/[^A-Za-z0-9]+/', '', $info['title']);
$classClause = "class=\"$cssClass\"";
if(isset($info['link']) && $info['link']) { }
$linkBase = singleton('CMSPageEditController')->Link('show') . '/';
$link = ($info['link'] === true) ? $linkBase . $record->ID : $info['link']; if (isset($info['link']) && $info['link']) {
return $prefix . "<a $classClause href=\"$link\">$val</a>"; $linkBase = singleton('CMSPageEditController')->Link('show') . '/';
} else { $link = ($info['link'] === true) ? $linkBase . $record->ID : $info['link'];
return $prefix . "<span $classClause>$val</span>"; return $prefix . "<a $classClause href=\"$link\">$val</a>";
} } else {
} return $prefix . "<span $classClause>$val</span>";
}
}
} }
/** /**
@ -104,12 +113,14 @@ class SideReportView extends ViewableData {
* *
* @package reports * @package reports
*/ */
class SideReportWrapper extends SS_ReportWrapper { class SideReportWrapper extends SS_ReportWrapper
public function columns() { {
if($this->baseReport->hasMethod('sideReportColumns')) { public function columns()
return $this->baseReport->sideReportColumns(); {
} else { if ($this->baseReport->hasMethod('sideReportColumns')) {
return parent::columns(); return $this->baseReport->sideReportColumns();
} } else {
} return parent::columns();
} }
}
}

View File

@ -4,131 +4,149 @@
* @package reports * @package reports
* @subpackage tests * @subpackage tests
*/ */
class ReportTest extends SapphireTest { class ReportTest extends SapphireTest
{
public function testGetReports() { public function testGetReports()
$reports = SS_Report::get_reports(); {
$this->assertNotNull($reports, "Reports returned"); $reports = SS_Report::get_reports();
$previousSort = 0; $this->assertNotNull($reports, "Reports returned");
foreach($reports as $report) { $previousSort = 0;
$this->assertGreaterThanOrEqual($previousSort, $report->sort, "Reports are in correct sort order"); foreach ($reports as $report) {
$previousSort = $report->sort; $this->assertGreaterThanOrEqual($previousSort, $report->sort, "Reports are in correct sort order");
} $previousSort = $report->sort;
} }
}
public function testExcludeReport() { public function testExcludeReport()
$reports = SS_Report::get_reports(); {
$reportNames = array(); $reports = SS_Report::get_reports();
foreach($reports as $report) { $reportNames = array();
$reportNames[] = $report->class; foreach ($reports as $report) {
} $reportNames[] = $report->class;
$this->assertContains('ReportTest_FakeTest',$reportNames,'ReportTest_FakeTest is in reports list'); }
$this->assertContains('ReportTest_FakeTest', $reportNames, 'ReportTest_FakeTest is in reports list');
//exclude one report //exclude one report
SS_Report::add_excluded_reports('ReportTest_FakeTest'); SS_Report::add_excluded_reports('ReportTest_FakeTest');
$reports = SS_Report::get_reports(); $reports = SS_Report::get_reports();
$reportNames = array(); $reportNames = array();
foreach($reports as $report) { foreach ($reports as $report) {
$reportNames[] = $report->class; $reportNames[] = $report->class;
} }
$this->assertNotContains('ReportTest_FakeTest',$reportNames,'ReportTest_FakeTest is NOT in reports list'); $this->assertNotContains('ReportTest_FakeTest', $reportNames, 'ReportTest_FakeTest is NOT in reports list');
//exclude two reports //exclude two reports
SS_Report::add_excluded_reports(array('ReportTest_FakeTest','ReportTest_FakeTest2')); SS_Report::add_excluded_reports(array('ReportTest_FakeTest', 'ReportTest_FakeTest2'));
$reports = SS_Report::get_reports(); $reports = SS_Report::get_reports();
$reportNames = array(); $reportNames = array();
foreach($reports as $report) { foreach ($reports as $report) {
$reportNames[] = $report->class; $reportNames[] = $report->class;
} }
$this->assertNotContains('ReportTest_FakeTest',$reportNames,'ReportTest_FakeTest is NOT in reports list'); $this->assertNotContains('ReportTest_FakeTest', $reportNames, 'ReportTest_FakeTest is NOT in reports list');
$this->assertNotContains('ReportTest_FakeTest2',$reportNames,'ReportTest_FakeTest2 is NOT in reports list'); $this->assertNotContains('ReportTest_FakeTest2', $reportNames, 'ReportTest_FakeTest2 is NOT in reports list');
} }
public function testAbstractClassesAreExcluded() { public function testAbstractClassesAreExcluded()
$reports = SS_Report::get_reports(); {
$reportNames = array(); $reports = SS_Report::get_reports();
foreach($reports as $report) { $reportNames = array();
$reportNames[] = $report->class; foreach ($reports as $report) {
} $reportNames[] = $report->class;
$this->assertNotContains('ReportTest_FakeTest_Abstract', }
$reportNames, $this->assertNotContains('ReportTest_FakeTest_Abstract',
'ReportTest_FakeTest_Abstract is NOT in reports list as it is abstract'); $reportNames,
} 'ReportTest_FakeTest_Abstract is NOT in reports list as it is abstract');
}
} }
/** /**
* @package reports * @package reports
* @subpackage tests * @subpackage tests
*/ */
class ReportTest_FakeTest extends SS_Report implements TestOnly { class ReportTest_FakeTest extends SS_Report implements TestOnly
public function title() { {
return 'Report title'; public function title()
} {
public function columns() { return 'Report title';
return array( }
"Title" => array( public function columns()
"title" => "Page Title" {
) return array(
); "Title" => array(
} "title" => "Page Title"
public function sourceRecords($params, $sort, $limit) { )
return new ArrayList(); );
} }
public function sourceRecords($params, $sort, $limit)
{
return new ArrayList();
}
public function sort() { public function sort()
return 100; {
} return 100;
}
} }
/** /**
* @package reports * @package reports
* @subpackage tests * @subpackage tests
*/ */
class ReportTest_FakeTest2 extends SS_Report implements TestOnly { class ReportTest_FakeTest2 extends SS_Report implements TestOnly
public function title() { {
return 'Report title 2'; public function title()
} {
public function columns() { return 'Report title 2';
return array( }
"Title" => array( public function columns()
"title" => "Page Title 2" {
) return array(
); "Title" => array(
} "title" => "Page Title 2"
public function sourceRecords($params, $sort, $limit) { )
return new ArrayList(); );
} }
public function sourceRecords($params, $sort, $limit)
{
return new ArrayList();
}
public function sort() { public function sort()
return 98; {
} return 98;
}
} }
/** /**
* @package reports * @package reports
* @subpackage tests * @subpackage tests
*/ */
abstract class ReportTest_FakeTest_Abstract extends SS_Report implements TestOnly { abstract class ReportTest_FakeTest_Abstract extends SS_Report implements TestOnly
{
public function title() {
return 'Report title Abstract'; public function title()
} {
return 'Report title Abstract';
}
public function columns() { public function columns()
return array( {
"Title" => array( return array(
"title" => "Page Title Abstract" "Title" => array(
) "title" => "Page Title Abstract"
); )
} );
public function sourceRecords($params, $sort, $limit) { }
return new ArrayList(); public function sourceRecords($params, $sort, $limit)
} {
return new ArrayList();
}
public function sort() { public function sort()
return 5; {
} return 5;
}
} }