MDL-82183 core: Coding style fixes for core\output

This commit is contained in:
Andrew Nicols
2024-06-26 23:00:33 +08:00
parent ff0fd2764a
commit 9043dc75bf
95 changed files with 2181 additions and 1759 deletions
+12 -11
View File
@@ -30,7 +30,7 @@ namespace core_block\output;
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
* @package core
* @package core_block
* @category output
*/
class block_contents {
@@ -51,7 +51,7 @@ class block_contents {
/**
* @var int All the blocks (or things that look like blocks) printed on
* a page are given a unique number that can be used to construct id="" attributes.
* This is set automatically be the {@link prepare()} method.
* This is set automatically be the {@see prepare()} method.
* Do not try to set it manually.
*/
public $skipid;
@@ -71,7 +71,7 @@ class block_contents {
/**
* @var array An array of attribute => value pairs that are put on the outer div of this
* block. {@link $id} and {@link $classes} attributes should be set separately.
* block. {@see $id} and {@see $classes} attributes should be set separately.
*/
public $attributes;
@@ -122,23 +122,24 @@ class block_contents {
* this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
* $icon is the icon name. Fed to $OUTPUT->image_url.
*/
public $controls = array();
public $controls = [];
/**
* Create new instance of block content
* @param array $attributes
* Create new instance of block content.
*
* @param null|array $attributes
*/
public function __construct(array $attributes = null) {
public function __construct(?array $attributes = null) {
$this->skipid = self::$idcounter;
self::$idcounter += 1;
if ($attributes) {
// standard block
// Standard block.
$this->attributes = $attributes;
} else {
// simple "fake" blocks used in some modules and "Add new block" block
$this->attributes = array('class'=>'block');
// Simple "fake" blocks used in some modules and "Add new block" block.
$this->attributes = ['class' => 'block'];
}
}
@@ -148,7 +149,7 @@ class block_contents {
* @param string $class
*/
public function add_class($class) {
$this->attributes['class'] .= ' '.$class;
$this->attributes['class'] .= ' ' . $class;
}
/**
+1 -1
View File
@@ -28,7 +28,7 @@ use moodle_url;
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
* @package core
* @package core_block
* @category output
*/
class block_move_target {
+12 -10
View File
@@ -59,15 +59,17 @@ class action_link implements renderable {
* Constructor
* @param moodle_url $url
* @param string $text HTML fragment
* @param component_action $action
* @param array $attributes associative array of html link attributes + disabled
* @param pix_icon $icon optional pix_icon to render with the link text
* @param null|component_action $action
* @param null|array $attributes associative array of html link attributes + disabled
* @param null|pix_icon $icon optional pix_icon to render with the link text
*/
public function __construct(moodle_url $url,
public function __construct(
moodle_url $url,
$text,
component_action $action=null,
array $attributes=null,
pix_icon $icon=null) {
?component_action $action = null,
?array $attributes = null,
?pix_icon $icon = null
) {
$this->url = clone($url);
$this->text = $text;
if (empty($attributes['id'])) {
@@ -144,14 +146,14 @@ class action_link implements renderable {
$data->classes = isset($attributes['class']) ? $attributes['class'] : '';
unset($attributes['class']);
$data->attributes = array_map(function($key, $value) {
$data->attributes = array_map(function ($key, $value) {
return [
'name' => $key,
'value' => $value
'value' => $value,
];
}, array_keys($attributes), $attributes);
$data->actions = array_map(function($action) use ($output) {
$data->actions = array_map(function ($action) use ($output) {
return $action->export_for_template($output);
}, !empty($this->actions) ? $this->actions : []);
$data->hasactions = !empty($this->actions);
+42 -39
View File
@@ -64,35 +64,35 @@ class action_menu implements renderable, templatable {
protected $instance = 0;
/**
* An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
* An array of primary actions. Please use {@see action_menu::add_primary_action()} to add actions.
* @var array
*/
protected $primaryactions = array();
protected $primaryactions = [];
/**
* An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
* An array of secondary actions. Please use {@see action_menu::add_secondary_action()} to add actions.
* @var array
*/
protected $secondaryactions = array();
protected $secondaryactions = [];
/**
* An array of attributes added to the container of the action menu.
* Initialised with defaults during construction.
* @var array
*/
public $attributes = array();
public $attributes = [];
/**
* An array of attributes added to the container of the primary actions.
* Initialised with defaults during construction.
* @var array
*/
public $attributesprimary = array();
public $attributesprimary = [];
/**
* An array of attributes added to the container of the secondary actions.
* Initialised with defaults during construction.
* @var array
*/
public $attributessecondary = array();
public $attributessecondary = [];
/**
* The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
@@ -147,27 +147,27 @@ class action_menu implements renderable, templatable {
*
* @param array $actions An array of actions (action_menu_link|pix_icon|string).
*/
public function __construct(array $actions = array()) {
public function __construct(array $actions = []) {
static $initialised = 0;
$this->instance = $initialised;
$initialised++;
$this->attributes = array(
'id' => 'action-menu-'.$this->instance,
$this->attributes = [
'id' => 'action-menu-' . $this->instance,
'class' => 'moodle-actionmenu',
'data-enhance' => 'moodle-core-actionmenu'
);
$this->attributesprimary = array(
'id' => 'action-menu-'.$this->instance.'-menubar',
'data-enhance' => 'moodle-core-actionmenu',
];
$this->attributesprimary = [
'id' => 'action-menu-' . $this->instance . '-menubar',
'class' => 'menubar',
);
$this->attributessecondary = array(
'id' => 'action-menu-'.$this->instance.'-menu',
];
$this->attributessecondary = [
'id' => 'action-menu-' . $this->instance . '-menu',
'class' => 'menu',
'data-rel' => 'menu-content',
'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
'role' => 'menu'
);
'aria-labelledby' => 'action-menu-toggle-' . $this->instance,
'role' => 'menu',
];
$this->dropdownalignment = 'dropdown-menu-right';
foreach ($actions as $action) {
$this->add($action);
@@ -207,8 +207,11 @@ class action_menu implements renderable, templatable {
* @param string|null $extraclasses extra classes for the trigger {@see self::set_menu_trigger()}
* @throws coding_exception
*/
public function set_kebab_trigger(?string $triggername = null, ?core_renderer $output = null,
?string $extraclasses = '') {
public function set_kebab_trigger(
?string $triggername = null,
?core_renderer $output = null,
?string $extraclasses = ''
) {
global $OUTPUT;
if (empty($output)) {
$output = $OUTPUT;
@@ -307,16 +310,16 @@ class action_menu implements renderable, templatable {
/**
* Returns the primary actions ready to be rendered.
*
* @param core_renderer $output The renderer to use for getting icons.
* @param null|core_renderer $output The renderer to use for getting icons.
* @return array
*/
public function get_primary_actions(core_renderer $output = null) {
public function get_primary_actions(?core_renderer $output = null) {
global $OUTPUT;
if ($output === null) {
$output = $OUTPUT;
}
$pixicon = $this->actionicon;
$linkclasses = array('toggle-display');
$linkclasses = ['toggle-display'];
$title = '';
if (!empty($this->menutrigger)) {
@@ -328,7 +331,7 @@ class action_menu implements renderable, templatable {
't/edit_menu',
'',
'moodle',
array('class' => 'iconsmall actionmenu', 'title' => '')
['class' => 'iconsmall actionmenu', 'title' => '']
);
$pixicon = $this->actionicon;
}
@@ -349,14 +352,14 @@ class action_menu implements renderable, templatable {
$label = $title;
}
$actions = $this->primaryactions;
$attributes = array(
$attributes = [
'class' => implode(' ', $linkclasses),
'title' => $title,
'aria-label' => $label,
'id' => 'action-menu-toggle-'.$this->instance,
'id' => 'action-menu-toggle-' . $this->instance,
'role' => 'menuitem',
'tabindex' => '-1',
);
];
$link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
if ($this->prioritise) {
array_unshift($actions, $link);
@@ -395,12 +398,12 @@ class action_menu implements renderable, templatable {
if (isset($this->attributessecondary['data-align'])) {
// We've already got one set, lets remove the old class so as to avoid troubles.
$class = $this->attributessecondary['class'];
$search = 'align-'.$this->attributessecondary['data-align'];
$search = 'align-' . $this->attributessecondary['data-align'];
$this->attributessecondary['class'] = str_replace($search, '', $class);
}
$align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
$this->attributessecondary['data-align'] = $align;
$this->attributessecondary['class'] .= ' align-'.$align;
$this->attributessecondary['class'] .= ' align-' . $align;
}
/**
@@ -411,15 +414,15 @@ class action_menu implements renderable, templatable {
*/
protected function get_align_string($align) {
switch ($align) {
case self::TL :
case self::TL:
return 'tl';
case self::TR :
case self::TR:
return 'tr';
case self::BL :
case self::BL:
return 'bl';
case self::BR :
case self::BR:
return 'br';
default :
default:
return 'tl';
}
}
@@ -502,7 +505,7 @@ class action_menu implements renderable, templatable {
$pos = strpos($this->attributes['class'], $class);
if ($value === true && $pos === false) {
// The value is true and the class has not been set yet. Add it.
$this->attributes['class'] .= ' '.$class;
$this->attributes['class'] .= ' ' . $class;
} else if ($value === false && $pos !== false) {
// The value is false and the class has been set. Remove it.
$this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
@@ -520,7 +523,7 @@ class action_menu implements renderable, templatable {
*/
public function set_additional_classes(string $class = '') {
if (!empty($this->attributes['class'])) {
$this->attributes['class'] .= " ".$class;
$this->attributes['class'] .= " " . $class;
} else {
$this->attributes['class'] = $class;
}
@@ -547,7 +550,7 @@ class action_menu implements renderable, templatable {
$data->classes = isset($attributes['class']) ? $attributes['class'] : '';
unset($attributes['class']);
$data->attributes = array_map(function($key, $value) {
$data->attributes = array_map(function ($key, $value) {
return [ 'name' => $key, 'value' => $value ];
}, array_keys($attributes), $attributes);
+4 -5
View File
@@ -33,7 +33,6 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class link extends action_link implements renderable {
/**
* True if this is a primary action. False if not.
* @var bool
@@ -49,8 +48,8 @@ class link extends action_link implements renderable {
/**
* The number of instances of this action menu link (and its subclasses).
*
* @deprecated since Moodle 4.4.
* @var int
* @deprecated since Moodle 4.4.
*/
protected static $instance = 1;
@@ -63,7 +62,7 @@ class link extends action_link implements renderable {
* @param bool $primary Whether this is a primary action or not.
* @param array $attributes Any attribtues associated with the action.
*/
public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = []) {
parent::__construct($url, $text, null, $attributes, $icon);
$this->primary = (bool)$primary;
$this->add_class('menu-action');
@@ -104,10 +103,10 @@ class link extends action_link implements renderable {
$data->disabled = !empty($attributes['disabled']);
unset($attributes['disabled']);
$data->attributes = array_map(function($key, $value) {
$data->attributes = array_map(function ($key, $value) {
return [
'name' => $key,
'value' => $value
'value' => $value,
];
}, array_keys($attributes), $attributes);
@@ -36,7 +36,7 @@ class link_primary extends link {
* @param string $text
* @param array $attributes
*/
public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = []) {
parent::__construct($url, $icon, $text, true, $attributes);
}
}
@@ -36,7 +36,7 @@ class link_secondary extends link {
* @param string $text
* @param array $attributes
*/
public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = []) {
parent::__construct($url, $icon, $text, false, $attributes);
}
}
@@ -31,7 +31,6 @@ use stdClass;
* @category output
*/
class component_action implements templatable {
/**
* @var string $event The DOM event that will trigger this action when caught
*/
@@ -48,7 +47,7 @@ class component_action implements templatable {
/**
* @var array An array of arguments to pass to the JS function
*/
public $jsfunctionargs = array();
public $jsfunctionargs = [];
/**
* Constructor
@@ -56,7 +55,7 @@ class component_action implements templatable {
* @param string $jsfunction An optional JS function. Required if jsfunctionargs is given
* @param array $jsfunctionargs An array of arguments to pass to the jsfunction
*/
public function __construct($event, $jsfunction, $jsfunctionargs=array()) {
public function __construct($event, $jsfunction, $jsfunctionargs = []) {
$this->event = $event;
$this->jsfunction = $jsfunction;
@@ -37,14 +37,18 @@ class confirm_action extends component_action {
*/
public function __construct($message, $callback = null, $continuelabel = null, $cancellabel = null) {
if ($callback !== null) {
debugging('The callback argument to new confirm_action() has been deprecated.' .
debugging(
'The callback argument to new confirm_action() has been deprecated.' .
' If you need to use a callback, please write Javascript to use moodle-core-notification-confirmation ' .
'and attach to the provided events.',
DEBUG_DEVELOPER);
DEBUG_DEVELOPER,
);
}
parent::__construct('click', 'M.util.show_confirm_dialog', array(
'message' => $message,
'continuelabel' => $continuelabel, 'cancellabel' => $cancellabel));
parent::__construct('click', 'M.util.show_confirm_dialog', [
'message' => $message,
'continuelabel' => $continuelabel,
'cancellabel' => $cancellabel,
]);
}
}
+22 -21
View File
@@ -37,20 +37,21 @@ class popup_action extends component_action {
/**
* @var array An array of parameters that will be passed to the openpopup JS function
*/
public $params = array(
'height' => 400,
'width' => 500,
'top' => 0,
'left' => 0,
'menubar' => false,
'location' => false,
'scrollbars' => true,
'resizable' => true,
'toolbar' => true,
'status' => true,
'directories' => false,
'fullscreen' => false,
'dependent' => true);
public $params = [
'height' => 400,
'width' => 500,
'top' => 0,
'left' => 0,
'menubar' => false,
'location' => false,
'scrollbars' => true,
'resizable' => true,
'toolbar' => true,
'status' => true,
'directories' => false,
'fullscreen' => false,
'dependent' => true,
];
/**
* Constructor
@@ -60,18 +61,18 @@ class popup_action extends component_action {
* @param string $name The JS function to call for the popup (default 'popup')
* @param array $params An array of popup parameters
*/
public function __construct($event, $url, $name='popup', $params=array()) {
public function __construct($event, $url, $name = 'popup', $params = []) {
global $CFG;
$url = new moodle_url($url);
if ($name) {
$_name = $name;
if (($_name = preg_replace("/\s/", '_', $_name)) != $name) {
$checkname = $name;
if (($checkname = preg_replace("/\s/", '_', $checkname)) != $name) {
throw new coding_exception(
'The $name of a popup window shouldn\'t contain spaces - string modified. ' . $name . ' changed to ' . $_name,
"The {$name} of a popup window shouldn't contain spaces - string modified. {$name} changed to {$checkname}",
);
$name = $_name;
$name = $checkname;
}
} else {
$name = 'popup';
@@ -83,7 +84,7 @@ class popup_action extends component_action {
}
}
$attributes = array('url' => $url->out(false), 'name' => $name, 'options' => $this->get_js_options($params));
$attributes = ['url' => $url->out(false), 'name' => $name, 'options' => $this->get_js_options($params)];
if (!empty($params['fullscreen'])) {
$attributes['fullscreen'] = 1;
}
@@ -102,7 +103,7 @@ class popup_action extends component_action {
foreach ($this->params as $var => $val) {
if (is_string($val) || is_int($val)) {
$jsoptions .= "$var=$val,";
} elseif (is_bool($val)) {
} else if (is_bool($val)) {
$jsoptions .= ($val) ? "$var," : "$var=0,";
}
}
+4 -2
View File
@@ -64,8 +64,10 @@ class activity_header implements renderable, templatable {
$this->title = format_string($page->activityrecord->name);
}
if (empty($layoutoptions['nodescription']) && !empty($page->activityrecord->intro) &&
trim($page->activityrecord->intro)) {
if (
empty($layoutoptions['nodescription']) && !empty($page->activityrecord->intro) &&
trim($page->activityrecord->intro)
) {
$this->description = format_module_intro($this->page->activityname, $page->activityrecord, $page->cm->id);
}
}
+3 -3
View File
@@ -97,13 +97,13 @@ class choicelist implements named_templatable, renderable {
* @return \stdClass[]
*/
public function get_selectable_options(): array {
$selectableOptions = [];
$selectableoptions = [];
foreach ($this->options as $option) {
if ($option['value'] !== $this->selected && !$option['disabled']) {
$selectableOptions[] = (object) $option;
$selectableoptions[] = (object) $option;
}
}
return $selectableOptions;
return $selectableoptions;
}
/**
+2 -4
View File
@@ -36,7 +36,6 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class chooser implements renderable, templatable {
/** @var moodle_url The form action URL. */
public $actionurl;
/** @var lang_string The instructions to display. */
@@ -81,7 +80,7 @@ class chooser implements renderable, templatable {
$this->params[] = [
'name' => $name,
'value' => $value,
'id' => $id
'id' => $id,
];
}
@@ -120,11 +119,10 @@ class chooser implements renderable, templatable {
$data->sesskey = sesskey();
$data->title = (string) $this->title;
$data->sections = array_map(function($section) use ($output) {
$data->sections = array_map(function ($section) use ($output) {
return $section->export_for_template($output);
}, $this->sections);
return $data;
}
}
+9 -4
View File
@@ -36,7 +36,6 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class chooser_item implements renderable, templatable {
/** @var string An identifier for the item. */
public $id;
/** @var string The label of this item. */
@@ -89,11 +88,17 @@ class chooser_item implements renderable, templatable {
$data->description = '';
if (!empty($this->description)) {
list($data->description) = \core_external\util::format_text((string) $this->description, FORMAT_MARKDOWN,
$this->context->id, null, null, null, $options);
[$data->description] = \core_external\util::format_text(
(string) $this->description,
FORMAT_MARKDOWN,
$this->context->id,
null,
null,
null,
$options
);
}
return $data;
}
}
+1 -3
View File
@@ -35,7 +35,6 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class chooser_section implements renderable, templatable {
/** @var string $id An identifier for the section. */
public $id;
/** @var lang_string $label The label of the section. */
@@ -66,10 +65,9 @@ class chooser_section implements renderable, templatable {
$data = new stdClass();
$data->id = $this->id;
$data->label = (string) $this->label;
$data->items = array_map(function($item) use ($output) {
$data->items = array_map(function ($item) use ($output) {
return $item->export_for_template($output);
}, array_values($this->items));
return $data;
}
}
+7 -7
View File
@@ -21,12 +21,11 @@ use core\exception\moodle_exception;
/**
* Renderable class for the comboboxsearch.
*
* @package core_output
* @package core
* @copyright 2022 Mathew May <Mathew.solutions>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class comboboxsearch implements renderable, templatable {
/** @var bool $renderlater Should the dropdown render straightaway? We sometimes need to output the component without all of the
* data and leave the rendering of any defaults and actual data to the caller. We will give you a basic placeholder that can
* then be easily replaced.*/
@@ -50,7 +49,7 @@ class comboboxsearch implements renderable, templatable {
/** @var null|string $buttonheader If the button item in the tertiary nav needs an extra top header for context. */
protected $buttonheader;
/** @var boolean $usesbutton Whether to provide a A11y button. */
/** @var bool $usesbutton Whether to provide a A11y button. */
protected $usesbutton;
/** @var null|string $label The label of the combobox. */
@@ -96,15 +95,16 @@ class comboboxsearch implements renderable, templatable {
throw new moodle_exception(
'incorrectdropdownvars',
'core',
'', null,
'',
null,
'Dropdown content must be set to render later.'
);
}
if ($usebutton && !$label) {
debugging(
'You have requested to use the button but have not provided a label for the combobox.',
DEBUG_DEVELOPER
'You have requested to use the button but have not provided a label for the combobox.',
DEBUG_DEVELOPER
);
}
@@ -137,7 +137,7 @@ class comboboxsearch implements renderable, templatable {
public function export_for_template(renderer_base $output): array {
return [
'renderlater' => $this->renderlater,
'buttoncontent' => $this->buttoncontent ,
'buttoncontent' => $this->buttoncontent,
'dropdowncontent' => $this->dropdowncontent,
'parentclasses' => $this->parentclasses,
'buttonclasses' => $this->buttonclasses,
+12 -15
View File
@@ -26,18 +26,15 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class context_header implements renderable, templatable {
/**
* @var string $heading Main heading.
*/
/** @var string $heading Main heading */
public $heading;
/**
* @var int $headinglevel Main heading 'h' tag level.
*/
/** @var int $headinglevel Main heading 'h' tag level */
public $headinglevel;
/**
* @var string|null $imagedata HTML code for the picture in the page header.
*/
/** @var string|null $imagedata HTML code for the picture in the page header */
public $imagedata;
/**
* @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
* array elements - title => alternate text for the image, or if no image is available the button text.
@@ -47,9 +44,8 @@ class context_header implements renderable, templatable {
* page => page object. Don't include if the image is an external image.
*/
public $additionalbuttons;
/**
* @var string $prefix A string that is before the title.
*/
/** @var string $prefix A string that is before the title */
public $prefix;
/**
@@ -62,7 +58,6 @@ class context_header implements renderable, templatable {
* @param string $prefix Text that precedes the heading.
*/
public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
$this->heading = $heading;
$this->headinglevel = $headinglevel;
$this->imagedata = $imagedata;
@@ -101,8 +96,10 @@ class context_header implements renderable, templatable {
$class = 'btn';
}
// Add the bootstrap 'btn' class for formatting.
$this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
array('class' => $class));
$this->additionalbuttons[$buttontype]['linkattributes'] = array_merge(
$button['linkattributes'],
['class' => $class]
);
}
}
File diff suppressed because it is too large Load Diff
+15 -10
View File
@@ -40,21 +40,23 @@ class core_renderer_ajax extends core_renderer {
* @param string $moreinfourl URL where more info can be found about the error
* @param string $link Link for the Continue button
* @param array $backtrace The execution backtrace
* @param string $debuginfo Debugging information
* @param null|string $debuginfo Debugging information
* @param string $errorcode
* @return string A template fragment for a fatal error
*/
public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
global $CFG;
$this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
// Ugly hack - make sure page context is set to something, we do not want bogus warnings here.
$this->page->set_context(null);
$e = new stdClass();
$e->error = $message;
$e->errorcode = $errorcode;
$e->stacktrace = NULL;
$e->debuginfo = NULL;
$e->reproductionlink = NULL;
if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
$e->stacktrace = null;
$e->debuginfo = null;
$e->reproductionlink = null;
if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
$link = (string) $link;
if ($link) {
$e->reproductionlink = $link;
@@ -99,7 +101,8 @@ class core_renderer_ajax extends core_renderer {
$delay,
$debugdisableredirect,
$messagetype = notification::NOTIFY_INFO,
) {}
) {
}
/**
* Prepares the start of an AJAX output.
@@ -118,7 +121,7 @@ class core_renderer_ajax extends core_renderer {
@header('Content-type: application/json; charset=utf-8');
}
// Headers to make it not cacheable and json
// Headers to make it not cacheable and json.
@header('Cache-Control: no-store, no-cache, must-revalidate');
@header('Cache-Control: post-check=0, pre-check=0', false);
@header('Pragma: no-cache');
@@ -131,7 +134,8 @@ class core_renderer_ajax extends core_renderer {
* There is no footer for an AJAX request, however we must override the
* footer method to prevent the default footer.
*/
public function footer() {}
public function footer() {
}
/**
* No need for headers in an AJAX request... this should never happen.
@@ -140,7 +144,8 @@ class core_renderer_ajax extends core_renderer {
* @param string $classes
* @param string $id
*/
public function heading($text, $level = 2, $classes = 'main', $id = null) {}
public function heading($text, $level = 2, $classes = 'main', $id = null) {
}
}
// Alias this class to the old name.
+6 -6
View File
@@ -33,7 +33,6 @@ use core\check\result as check_result;
class core_renderer_cli extends core_renderer {
/**
* @var array $progressmaximums stores the largest percentage for a progress bar.
* @return string ascii fragment
*/
private $progressmaximums = [];
@@ -59,10 +58,10 @@ class core_renderer_cli extends core_renderer {
$status = $result->get_status();
$labels = [
check_result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
check_result::NA => ' ' . cli_ansi_format('<colour:darkGray>') . ' NA ',
check_result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
check_result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
check_result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
check_result::INFO => ' ' . cli_ansi_format('<colour:blue>') . ' INFO ',
check_result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>') . ' UNKNOWN ',
check_result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
check_result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
check_result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
@@ -96,7 +95,7 @@ class core_renderer_cli extends core_renderer {
$ascii = "\n";
if (stream_isatty(STDOUT)) {
require_once($CFG->libdir.'/clilib.php');
require_once($CFG->libdir . '/clilib.php');
$ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
return cli_ansi_format($ascii);
@@ -199,7 +198,8 @@ class core_renderer_cli extends core_renderer {
* @param string $moreinfourl URL where more info can be found about the error
* @param string $link Link for the Continue button
* @param array $backtrace The execution backtrace
* @param string $debuginfo Debugging information
* @param null|string $debuginfo Debugging information
* @param string $errorcode
* @return string A template fragment for a fatal error
*/
public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
@@ -70,7 +70,7 @@ class core_renderer_maintenance extends core_renderer {
* @param boolean $fakeblocksonly
* @return string
*/
public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
public function blocks($region, $classes = [], $tag = 'aside', $fakeblocksonly = false) {
return '';
}
@@ -158,11 +158,19 @@ class core_renderer_maintenance extends core_renderer {
if ($continue instanceof single_button) {
$continue->type = single_button::BUTTON_PRIMARY;
} else if (is_string($continue)) {
$continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
$displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
$continue = new single_button(
new moodle_url($continue),
get_string('continue'),
'post',
$displayoptions['type'] ?? single_button::BUTTON_PRIMARY
);
} else if ($continue instanceof moodle_url) {
$continue = new single_button($continue, get_string('continue'), 'post',
$displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
$continue = new single_button(
$continue,
get_string('continue'),
'post',
$displayoptions['type'] ?? single_button::BUTTON_PRIMARY
);
} else {
throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
' (string/moodle_url) or a single_button instance.');
@@ -228,10 +236,10 @@ class core_renderer_maintenance extends core_renderer {
* Does nothing. The maintenance renderer cannot produce user pictures.
*
* @param stdClass $user
* @param array $options
* @param null|array $options
* @return string
*/
public function user_picture(stdClass $user, array $options = null) {
public function user_picture(stdClass $user, ?array $options = null) {
return '';
}
}
+3 -3
View File
@@ -44,7 +44,7 @@ class custom_menu extends custom_menu_item {
/**
* Creates the custom menu
*
* @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
* @param string $definition the menu items definition in syntax required by {@see convert_text_to_menu_nodes()}
* @param string $currentlanguage the current language code, null disables multilang support
*/
public function __construct($definition = '', $currentlanguage = null) {
@@ -62,7 +62,7 @@ class custom_menu extends custom_menu_item {
* @param array $children
*/
public function override_children(array $children) {
$this->children = array();
$this->children = [];
foreach ($children as $child) {
if ($child instanceof custom_menu_item) {
$this->children[] = $child;
@@ -100,7 +100,7 @@ class custom_menu extends custom_menu_item {
$root = new custom_menu();
$lastitem = $root;
$lastdepth = 0;
$hiddenitems = array();
$hiddenitems = [];
$lines = explode("\n", $text);
foreach ($lines as $linenumber => $line) {
$line = trim($line);
+27 -27
View File
@@ -33,17 +33,11 @@ use stdClass;
* @category output
*/
class custom_menu_item implements renderable, templatable {
/**
* @var string The text to show for the item
*/
protected $text;
/**
* @var moodle_url The link to give the icon if it has no children
*/
protected $url;
/**
* @var string A title to apply to the item. By default the text
*/
@@ -55,60 +49,66 @@ class custom_menu_item implements renderable, templatable {
*/
protected $sort;
/**
* @var custom_menu_item A reference to the parent for this item or NULL if
* it is a top level item
*/
protected $parent;
/**
* @var array A array in which to store children this item has.
*/
protected $children = array();
protected $children = [];
/**
* @var int A reference to the sort var of the last child that was added
*/
protected $lastsort = 0;
/** @var array Array of other HTML attributes for the custom menu item. */
protected $attributes = [];
/**
* Constructs the new custom menu item
*
* @param string $text
* @param moodle_url $url A moodle url to apply as the link for this item [Optional]
* @param null|moodle_url $url A moodle url to apply as the link for this item [Optional]
* @param string $title A title to apply to this item [Optional]
* @param int $sort A sort or to use if we need to sort differently [Optional]
* @param custom_menu_item $parent A reference to the parent custom_menu_item this child
* @param null|custom_menu_item $parent A reference to the parent custom_menu_item this child
* belongs to, only if the child has a parent. [Optional]
* @param array $attributes Array of other HTML attributes for the custom menu item.
*/
public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
array $attributes = []) {
public function __construct(
$text,
/** @var moodle_url The link to give the icon if it has no children */
protected ?moodle_url $url = null,
$title = null,
$sort = null,
/**
* @var custom_menu_item A reference to the parent for this item or NULL if
* it is a top level item
*/
protected ?custom_menu_item $parent = null,
/** @var array Array of other HTML attributes for the custom menu item. */
protected array $attributes = [],
) {
// Use class setter method for text to ensure it's always a string type.
$this->set_text($text);
$this->url = $url;
$this->title = $title;
$this->sort = (int)$sort;
$this->parent = $parent;
$this->attributes = $attributes;
}
/**
* Adds a custom menu item as a child of this node given its properties.
*
* @param string $text
* @param moodle_url $url
* @param null|moodle_url $url
* @param string $title
* @param int $sort
* @param array $attributes Array of other HTML attributes for the custom menu item.
* @return custom_menu_item
*/
public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
public function add(
$text,
?moodle_url $url = null,
$title = null,
$sort = null,
$attributes = [],
) {
$key = count($this->children);
if (empty($sort)) {
$sort = $this->lastsort + 1;
@@ -195,7 +195,7 @@ class custom_menu_item implements renderable, templatable {
* Sorts the children this item has
*/
public function sort() {
usort($this->children, array('custom_menu','sort_custom_menu_items'));
usort($this->children, ['custom_menu', 'sort_custom_menu_items']);
}
/**
@@ -252,7 +252,7 @@ class custom_menu_item implements renderable, templatable {
if (!empty($this->attributes)) {
$context->attributes = $this->attributes;
}
$context->children = array();
$context->children = [];
if (preg_match("/^#+$/", $this->text)) {
$context->divider = true;
}
+1 -2
View File
@@ -28,7 +28,6 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class datafilter implements renderable, templatable {
/** @var int None of the following match */
public const JOINTYPE_NONE = 0;
@@ -108,7 +107,7 @@ abstract class datafilter implements renderable, templatable {
'values' => $values,
'filteroptions' => $filteroptions,
'required' => $required,
'joinlist' => json_encode($joinlist)
'joinlist' => json_encode($joinlist),
];
}
}
+1 -2
View File
@@ -28,7 +28,6 @@ use core\output\dynamic_tabs\base;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dynamic_tabs implements templatable {
/** @var base[] */
protected $tabs = [];
@@ -60,7 +59,7 @@ class dynamic_tabs implements templatable {
*/
public function export_for_template(renderer_base $output): array {
$data = [
'tabs' => []
'tabs' => [],
];
foreach ($this->tabs as $tab) {
-1
View File
@@ -29,7 +29,6 @@ use core\output\templatable;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class base implements templatable {
/** @var array */
protected $data;
+23 -20
View File
@@ -39,13 +39,12 @@ class external extends external_api {
* @return external_function_parameters
*/
public static function load_template_parameters() {
return new external_function_parameters(
array('component' => new external_value(PARAM_COMPONENT, 'component containing the template'),
'template' => new external_value(PARAM_SAFEPATH, 'name of the template'),
'themename' => new external_value(PARAM_ALPHANUMEXT, 'The current theme.'),
'includecomments' => new external_value(PARAM_BOOL, 'Include comments or not', VALUE_DEFAULT, false)
)
);
return new external_function_parameters([
'component' => new external_value(PARAM_COMPONENT, 'component containing the template'),
'template' => new external_value(PARAM_SAFEPATH, 'name of the template'),
'themename' => new external_value(PARAM_ALPHANUMEXT, 'The current theme.'),
'includecomments' => new external_value(PARAM_BOOL, 'Include comments or not', VALUE_DEFAULT, false),
]);
}
/**
@@ -60,11 +59,15 @@ class external extends external_api {
global $DB, $CFG, $PAGE;
$PAGE->set_context(context_system::instance());
$params = self::validate_parameters(self::load_template_parameters(),
array('component' => $component,
'template' => $template,
'themename' => $themename,
'includecomments' => $includecomments));
$params = self::validate_parameters(
self::load_template_parameters(),
[
'component' => $component,
'template' => $template,
'themename' => $themename,
'includecomments' => $includecomments,
],
);
$loader = new mustache_template_source_loader();
// Will throw exceptions if the template does not exist.
@@ -72,7 +75,7 @@ class external extends external_api {
$params['component'],
$params['template'],
$params['themename'],
$params['includecomments']
$params['includecomments'],
);
}
@@ -108,7 +111,7 @@ class external extends external_api {
* @param string $themename The name of the current theme.
* @param bool $includecomments Whether to strip comments from the template source.
* @param string $lang moodle translation language, null means use current.
* @return string the template
* @return array the template
*/
public static function load_template_with_dependencies(
string $component,
@@ -126,7 +129,7 @@ class external extends external_api {
'template' => $template,
'themename' => $themename,
'includecomments' => $includecomments,
'lang' => $lang
'lang' => $lang,
]
);
@@ -141,14 +144,14 @@ class external extends external_api {
[],
$params['lang']
);
$formatdependencies = function($dependency) {
$formatdependencies = function ($dependency) {
$results = [];
foreach ($dependency as $dependencycomponent => $dependencyvalues) {
foreach ($dependencyvalues as $dependencyname => $dependencyvalue) {
array_push($results, [
'component' => $dependencycomponent,
'name' => $dependencyname,
'value' => $dependencyvalue
'value' => $dependencyvalue,
]);
}
}
@@ -159,7 +162,7 @@ class external extends external_api {
// by external functions (because they don't support dynamic keys).
return [
'templates' => $formatdependencies($dependencies['templates']),
'strings' => $formatdependencies($dependencies['strings'])
'strings' => $formatdependencies($dependencies['strings']),
];
}
@@ -172,12 +175,12 @@ class external extends external_api {
$resourcestructure = new external_single_structure([
'component' => new external_value(PARAM_COMPONENT, 'component containing the resource'),
'name' => new external_value(PARAM_TEXT, 'name of the resource'),
'value' => new external_value(PARAM_RAW, 'resource value')
'value' => new external_value(PARAM_RAW, 'resource value'),
]);
return new external_single_structure([
'templates' => new external_multiple_structure($resourcestructure),
'strings' => new external_multiple_structure($resourcestructure)
'strings' => new external_multiple_structure($resourcestructure),
]);
}
+17 -13
View File
@@ -52,18 +52,18 @@ class file_picker implements renderable {
*/
public function __construct(stdClass $options) {
global $CFG, $USER, $PAGE;
require_once($CFG->dirroot. '/repository/lib.php');
$defaults = array(
'accepted_types'=>'*',
'return_types'=>FILE_INTERNAL,
require_once($CFG->dirroot . '/repository/lib.php');
$defaults = [
'accepted_types' => '*',
'return_types' => FILE_INTERNAL,
'env' => 'filepicker',
'client_id' => uniqid(),
'itemid' => 0,
'maxbytes'=>-1,
'maxfiles'=>1,
'buttonname'=>false
);
foreach ($defaults as $key=>$value) {
'maxbytes' => -1,
'maxfiles' => 1,
'buttonname' => false,
];
foreach ($defaults as $key => $value) {
if (empty($options->$key)) {
$options->$key = $value;
}
@@ -81,15 +81,19 @@ class file_picker implements renderable {
$file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
}
if (!empty($file)) {
$options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
$options->currentfile = html_writer::link(moodle_url::make_draftfile_url(
$file->get_itemid(),
$file->get_filepath(),
$file->get_filename(),
), $file->get_filename());
}
}
// initilise options, getting files in root path
// Initialise options, getting files in root path.
$this->options = initialise_filepicker($options);
// copying other options
foreach ($options as $name=>$value) {
// Copying other options.
foreach ($options as $name => $value) {
if (!isset($this->options->$name)) {
$this->options->$name = $value;
}
+2 -2
View File
@@ -75,7 +75,7 @@ class help_icon implements renderable, templatable {
if (!$sm->string_exists($this->identifier, $this->component)) {
debugging("Help title string does not exist: [$this->identifier, $this->component]");
}
if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
if (!$sm->string_exists($this->identifier . '_help', $this->component)) {
debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
}
}
@@ -107,7 +107,7 @@ class help_icon implements renderable, templatable {
$options = [
'component' => $this->component,
'identifier' => $this->identifier,
'lang' => current_language()
'lang' => current_language(),
];
// Debugging feature lets you display string identifier and component.
+127 -119
View File
@@ -38,10 +38,10 @@ class html_writer {
*
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @param string $contents What goes between the opening and closing tags
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function tag($tagname, $contents, array $attributes = null) {
public static function tag($tagname, $contents, ?array $attributes = null) {
return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
}
@@ -49,10 +49,10 @@ class html_writer {
* Outputs an opening tag with attributes
*
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function start_tag($tagname, array $attributes = null) {
public static function start_tag($tagname, ?array $attributes = null) {
return '<' . $tagname . self::attributes($attributes) . '>';
}
@@ -70,10 +70,10 @@ class html_writer {
* Outputs an empty tag with attributes
*
* @param string $tagname The name of tag ('input', 'img', 'br' etc.)
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function empty_tag($tagname, array $attributes = null) {
public static function empty_tag($tagname, ?array $attributes = null) {
return '<' . $tagname . self::attributes($attributes) . ' />';
}
@@ -82,10 +82,10 @@ class html_writer {
*
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @param string $contents What goes between the opening and closing tags
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function nonempty_tag($tagname, $contents, array $attributes = null) {
public static function nonempty_tag($tagname, $contents, ?array $attributes = null) {
if ($contents === '' || is_null($contents)) {
return '';
}
@@ -96,7 +96,7 @@ class html_writer {
* Outputs a HTML attribute and value
*
* @param string $name The name of the attribute ('src', 'href', 'class' etc.)
* @param string $value The value of the attribute. The value will be escaped with {@link s()}
* @param string $value The value of the attribute. The value will be escaped with {@see s()}
* @return string HTML fragment
*/
public static function attribute($name, $value) {
@@ -104,23 +104,23 @@ class html_writer {
return ' ' . $name . '="' . $value->out() . '"';
}
// special case, we do not want these in output
// Special case, we do not want these in output.
if ($value === null) {
return '';
}
// no sloppy trimming here!
// No sloppy trimming here!
return ' ' . $name . '="' . s($value) . '"';
}
/**
* Outputs a list of HTML attributes and values
*
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* The values will be escaped with {@link s()}
* @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* The values will be escaped with {@see s()}
* @return string HTML fragment
*/
public static function attributes(array $attributes = null) {
public static function attributes(?array $attributes = null) {
$attributes = (array)$attributes;
$output = '';
foreach ($attributes as $name => $value) {
@@ -134,10 +134,10 @@ class html_writer {
*
* @param string $src The source of image
* @param string $alt The alternate text for image
* @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
* @param null|array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function img($src, $alt, array $attributes = null) {
public static function img($src, $alt, ?array $attributes = null) {
$attributes = (array)$attributes;
$attributes['src'] = $src;
// In case a null alt text is provided, set it to an empty string.
@@ -161,7 +161,7 @@ class html_writer {
* @param string $base A string fragment that will be included in the random ID.
* @return string A unique ID
*/
public static function random_id($base='random') {
public static function random_id($base = 'random') {
static $counter = 0;
static $uniq;
@@ -170,7 +170,7 @@ class html_writer {
}
$counter++;
return $base.$uniq.$counter;
return $base . $uniq . $counter;
}
/**
@@ -178,10 +178,10 @@ class html_writer {
*
* @param string|moodle_url $url The URL
* @param string $text The text
* @param array $attributes HTML attributes
* @param null|array $attributes HTML attributes
* @return string HTML fragment
*/
public static function link($url, $text, array $attributes = null) {
public static function link($url, $text, ?array $attributes = null) {
$attributes = (array)$attributes;
$attributes['href'] = $url;
return self::tag('a', $text, $attributes);
@@ -194,16 +194,22 @@ class html_writer {
* @param string $value The value of the checkbox
* @param bool $checked Whether the checkbox is checked
* @param string $label The label for the checkbox
* @param array $attributes Any attributes to apply to the checkbox
* @param array $labelattributes Any attributes to apply to the label, if present
* @param null|array $attributes Any attributes to apply to the checkbox
* @param null|array $labelattributes Any attributes to apply to the label, if present
* @return string html fragment
*/
public static function checkbox($name, $value, $checked = true, $label = '',
array $attributes = null, array $labelattributes = null) {
public static function checkbox(
$name,
$value,
$checked = true,
$label = '',
?array $attributes = null,
?array $labelattributes = null,
) {
$attributes = (array) $attributes;
$output = '';
if ($label !== '' and !is_null($label)) {
if ($label !== '' && !is_null($label)) {
if (empty($attributes['id'])) {
$attributes['id'] = self::random_id('checkbox_');
}
@@ -215,7 +221,7 @@ class html_writer {
$output .= self::empty_tag('input', $attributes);
if ($label !== '' and !is_null($label)) {
if ($label !== '' && !is_null($label)) {
$labelattributes = (array) $labelattributes;
$labelattributes['for'] = $attributes['id'];
$output .= self::tag('label', $label, $labelattributes);
@@ -229,11 +235,11 @@ class html_writer {
*
* @param string $name name of select element
* @param bool $selected
* @param array $attributes - html select element attributes
* @param null|array $attributes - html select element attributes
* @return string HTML fragment
*/
public static function select_yes_no($name, $selected=true, array $attributes = null) {
$options = array('1'=>get_string('yes'), '0'=>get_string('no'));
public static function select_yes_no($name, $selected = true, ?array $attributes = null) {
$options = ['1' => get_string('yes'), '0' => get_string('no')];
return self::select($options, $name, $selected, null, $attributes);
}
@@ -250,41 +256,46 @@ class html_writer {
* @param string $name name of select element
* @param string|array $selected value or array of values depending on multiple attribute
* @param array|bool|null $nothing add nothing selected option, or false of not added
* @param array $attributes html select element attributes
* @param null|array $attributes html select element attributes
* @return string HTML fragment
*/
public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
public static function select(
array $options,
$name,
$selected = '',
$nothing = ['' => 'choosedots'],
?array $attributes = null,
) {
$attributes = (array)$attributes;
if (is_array($nothing)) {
foreach ($nothing as $k=>$v) {
if ($v === 'choose' or $v === 'choosedots') {
foreach ($nothing as $k => $v) {
if ($v === 'choose' || $v === 'choosedots') {
$nothing[$k] = get_string('choosedots');
}
}
$options = $nothing + $options; // keep keys, do not override
} else if (is_string($nothing) and $nothing !== '') {
// BC
$options = array(''=>$nothing) + $options;
$options = $nothing + $options; // Keep keys, do not override.
} else if (is_string($nothing) && $nothing !== '') {
// BC.
$options = ['' => $nothing] + $options;
}
// we may accept more values if multiple attribute specified
// We may accept more values if multiple attribute specified.
$selected = (array)$selected;
foreach ($selected as $k=>$v) {
foreach ($selected as $k => $v) {
$selected[$k] = (string)$v;
}
if (!isset($attributes['id'])) {
$id = 'menu'.$name;
// name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
$id = 'menu' . $name;
// Name may contain [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading.
$id = str_replace('[', '', $id);
$id = str_replace(']', '', $id);
$attributes['id'] = $id;
}
if (!isset($attributes['class'])) {
$class = 'menu'.$name;
// name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
$class = 'menu' . $name;
// Name may contain [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading.
$class = str_replace('[', '', $class);
$class = str_replace(']', '', $class);
$attributes['class'] = $class;
@@ -300,9 +311,9 @@ class html_writer {
}
$output = '';
foreach ($options as $value=>$label) {
foreach ($options as $value => $label) {
if (is_array($label)) {
// ignore key, it just has to be unique
// Ignore key, it just has to be unique.
$output .= self::select_optgroup(key($label), current($label), $selected);
} else {
$output .= self::select_option($label, $value, $selected);
@@ -320,7 +331,7 @@ class html_writer {
* @return string HTML fragment
*/
private static function select_option($label, $value, array $selected) {
$attributes = array();
$attributes = [];
$value = (string)$value;
if (in_array($value, $selected, true)) {
$attributes['selected'] = 'selected';
@@ -341,9 +352,9 @@ class html_writer {
if (empty($options)) {
return '';
}
$attributes = array('label'=>$groupname);
$attributes = ['label' => $groupname];
$output = '';
foreach ($options as $value=>$label) {
foreach ($options as $value => $label) {
$output .= self::select_option($label, $value, $selected);
}
return self::tag('optgroup', $output, $attributes);
@@ -356,12 +367,12 @@ class html_writer {
* @param string $name fieldname
* @param int $currenttime A default timestamp in GMT
* @param int $step minute spacing
* @param array $attributes - html select element attributes
* @param null|array $attributes - html select element attributes
* @param float|int|string $timezone the timezone to use to calculate the time
* {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
* @return string HTML fragment
*/
public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null, $timezone = 99) {
public static function select_time($type, $name, $currenttime = 0, $step = 5, ?array $attributes = null, $timezone = 99) {
global $OUTPUT;
if (!$currenttime) {
@@ -371,7 +382,7 @@ class html_writer {
$currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone);
$userdatetype = $type;
$timeunits = array();
$timeunits = [];
switch ($type) {
case 'years':
@@ -388,17 +399,17 @@ class html_writer {
$userdatetype = 'mday';
break;
case 'hours':
for ($i=0; $i<=23; $i++) {
$timeunits[$i] = sprintf("%02d",$i);
for ($i = 0; $i <= 23; $i++) {
$timeunits[$i] = sprintf("%02d", $i);
}
break;
case 'minutes':
if ($step != 1) {
$currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
$currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step;
}
for ($i=0; $i<=59; $i+=$step) {
$timeunits[$i] = sprintf("%02d",$i);
for ($i = 0; $i <= 59; $i += $step) {
$timeunits[$i] = sprintf("%02d", $i);
}
break;
default:
@@ -410,21 +421,21 @@ class html_writer {
'name' => $name,
'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
'label' => get_string(substr($type, 0, -1), 'form'),
'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
'options' => array_map(function ($value) use ($timeunits, $currentdate, $userdatetype) {
return [
'name' => $timeunits[$value],
'value' => $value,
'selected' => $currentdate[$userdatetype] == $value
'selected' => $currentdate[$userdatetype] == $value,
];
}, array_keys($timeunits)),
];
unset($attributes['id']);
unset($attributes['name']);
$data->attributes = array_map(function($name) use ($attributes) {
$data->attributes = array_map(function ($name) use ($attributes) {
return [
'name' => $name,
'value' => $attributes[$name]
'value' => $attributes[$name],
];
}, array_keys($attributes));
@@ -437,14 +448,14 @@ class html_writer {
* Note: 'list' is a reserved keyword ;-)
*
* @param array $items
* @param array $attributes
* @param null|array $attributes
* @param string $tag ul or ol
* @return string
*/
public static function alist(array $items, array $attributes = null, $tag = 'ul') {
$output = self::start_tag($tag, $attributes)."\n";
public static function alist(array $items, ?array $attributes = null, $tag = 'ul') {
$output = self::start_tag($tag, $attributes) . "\n";
foreach ($items as $item) {
$output .= self::tag('li', $item)."\n";
$output .= self::tag('li', $item) . "\n";
}
$output .= self::end_tag($tag);
return $output;
@@ -454,10 +465,10 @@ class html_writer {
* Returns hidden input fields created from url parameters.
*
* @param moodle_url $url
* @param array $exclude list of excluded parameters
* @param null|array $exclude list of excluded parameters
* @return string HTML fragment
*/
public static function input_hidden_params(moodle_url $url, array $exclude = null) {
public static function input_hidden_params(moodle_url $url, ?array $exclude = null) {
$exclude = (array)$exclude;
$params = $url->params();
foreach ($exclude as $key) {
@@ -466,8 +477,8 @@ class html_writer {
$output = '';
foreach ($params as $key => $value) {
$attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
$output .= self::empty_tag('input', $attributes)."\n";
$attributes = ['type' => 'hidden', 'name' => $key, 'value' => $value];
$output .= self::empty_tag('input', $attributes) . "\n";
}
return $output;
}
@@ -479,13 +490,11 @@ class html_writer {
* @param moodle_url|string $url optional url of the external script, $code ignored if specified
* @return string HTML, the code wrapped in <script> tags.
*/
public static function script($jscode, $url=null) {
public static function script($jscode, $url = null) {
if ($jscode) {
return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
} else if ($url) {
return self::tag('script', '', ['src' => $url]) . "\n";
} else {
return '';
}
@@ -503,11 +512,11 @@ class html_writer {
* @return string HTML code
*/
public static function table(html_table $table) {
// prepare table data and populate missing properties with reasonable defaults
// Prepare table data and populate missing properties with reasonable defaults.
if (!empty($table->align)) {
foreach ($table->align as $key => $aa) {
if ($aa) {
$table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
$table->align[$key] = 'text-align:' . fix_align_rtl($aa) . ';'; // Fix for RTL languages.
} else {
$table->align[$key] = null;
}
@@ -516,7 +525,7 @@ class html_writer {
if (!empty($table->size)) {
foreach ($table->size as $key => $ss) {
if ($ss) {
$table->size[$key] = 'width:'. $ss .';';
$table->size[$key] = 'width:' . $ss . ';';
} else {
$table->size[$key] = null;
}
@@ -542,7 +551,6 @@ class html_writer {
if (!isset($table->wrap[$key])) {
$table->wrap[$key] = null;
}
}
}
if (empty($table->attributes['class'])) {
@@ -552,22 +560,22 @@ class html_writer {
$table->attributes['class'] .= ' boxalign' . $table->tablealign;
}
// explicitly assigned properties override those defined via $table->attributes
// Explicitly assigned properties override those defined via $table->attributes.
$table->attributes['class'] = trim($table->attributes['class']);
$attributes = array_merge($table->attributes, array(
$attributes = array_merge($table->attributes, [
'id' => $table->id,
'width' => $table->width,
'summary' => $table->summary,
'cellpadding' => $table->cellpadding,
'cellspacing' => $table->cellspacing,
));
]);
$output = self::start_tag('table', $attributes) . "\n";
$countcols = 0;
// Output a caption if present.
if (!empty($table->caption)) {
$captionattributes = array();
$captionattributes = [];
if ($table->captionhide) {
$captionattributes['class'] = 'accesshide';
}
@@ -581,13 +589,13 @@ class html_writer {
if (!empty($table->head)) {
$countcols = count($table->head);
$output .= self::start_tag('thead', array()) . "\n";
$output .= self::start_tag('tr', array()) . "\n";
$output .= self::start_tag('thead', []) . "\n";
$output .= self::start_tag('tr', []) . "\n";
$keys = array_keys($table->head);
$lastkey = end($keys);
foreach ($table->head as $key => $heading) {
// Convert plain string headings into html_table_cell objects
// Convert plain string headings into html_table_cell objects.
if (!($heading instanceof html_table_cell)) {
$headingtext = $heading;
$heading = new html_table_cell();
@@ -633,9 +641,9 @@ class html_writer {
if (empty($table->data)) {
// For valid XHTML strict every table must contain either a valid tr
// or a valid tbody... both of which must contain a valid td
$output .= self::start_tag('tbody', array('class' => 'empty'));
$output .= self::tag('tr', self::tag('td', '', array('colspan'=>count($table->head))));
// or a valid tbody... both of which must contain a valid td.
$output .= self::start_tag('tbody', ['class' => 'empty']);
$output .= self::tag('tr', self::tag('td', '', ['colspan' => count($table->head)]));
$output .= self::end_tag('tbody');
}
}
@@ -643,13 +651,13 @@ class html_writer {
if (!empty($table->data)) {
$keys = array_keys($table->data);
$lastrowkey = end($keys);
$output .= self::start_tag('tbody', array());
$output .= self::start_tag('tbody', []);
foreach ($table->data as $key => $row) {
if (($row === 'hr') && ($countcols)) {
$output .= self::tag('td', self::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
$output .= self::tag('td', self::tag('div', '', ['class' => 'tabledivider']), ['colspan' => $countcols]);
} else {
// Convert array rows to html_table_rows and cell strings to html_table_cell objects
// Convert array rows to html_table_rows and cell strings to html_table_cell objects.
if (!($row instanceof html_table_row)) {
$newrow = new html_table_row();
@@ -672,18 +680,18 @@ class html_writer {
// Explicitly assigned properties should override those defined in the attributes.
$row->attributes['class'] = trim($row->attributes['class']);
$trattributes = array_merge($row->attributes, array(
$trattributes = array_merge($row->attributes, [
'id' => $row->id,
'style' => $row->style,
));
]);
$output .= self::start_tag('tr', $trattributes) . "\n";
$keys2 = array_keys($row->cells);
$lastkey = end($keys2);
$gotlastkey = false; //flag for sanity checking
$gotlastkey = false; // Flag for sanity checking.
foreach ($row->cells as $key => $cell) {
if ($gotlastkey) {
//This should never happen. Why do we have a cell after the last cell?
// This should never happen. Why do we have a cell after the last cell?
mtrace("A cell with key ($key) was found after the last key ($lastkey)");
}
@@ -711,14 +719,14 @@ class html_writer {
$tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
$tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
$cell->attributes['class'] = trim($cell->attributes['class']);
$tdattributes = array_merge($cell->attributes, array(
$tdattributes = array_merge($cell->attributes, [
'style' => $tdstyle . $cell->style,
'colspan' => $cell->colspan,
'rowspan' => $cell->rowspan,
'id' => $cell->id,
'abbr' => $cell->abbr,
'scope' => $cell->scope,
));
]);
$tagtype = 'td';
if ($cell->header === true) {
$tagtype = 'th';
@@ -760,26 +768,26 @@ class html_writer {
* @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
* @return string HTML of the label element
*/
public static function label($text, $for, $colonize = true, array $attributes=array()) {
public static function label($text, $for, $colonize = true, array $attributes = []) {
if (!is_null($for)) {
$attributes = array_merge($attributes, array('for' => $for));
$attributes = array_merge($attributes, ['for' => $for]);
}
$text = trim($text ?? '');
$label = self::tag('label', $text, $attributes);
// TODO MDL-12192 $colonize disabled for now yet
// if (!empty($text) and $colonize) {
// // the $text may end with the colon already, though it is bad string definition style
// $colon = get_string('labelsep', 'langconfig');
// if (!empty($colon)) {
// $trimmed = trim($colon);
// if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
// //debugging('The label text should not end with colon or other label separator,
// // please fix the string definition.', DEBUG_DEVELOPER);
// } else {
// $label .= $colon;
// }
// }
// the $text may end with the colon already, though it is bad string definition style
// $colon = get_string('labelsep', 'langconfig');
// if (!empty($colon)) {
// $trimmed = trim($colon);
// if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
// debugging('The label text should not end with colon or other label separator,
// please fix the string definition.', DEBUG_DEVELOPER);
// } else {
// $label .= $colon;
// }
// }
// }
return $label;
@@ -793,12 +801,12 @@ class html_writer {
* class parameter, the two values are combined with a space between.
*
* @param string $class Optional CSS class (or classes as space-separated list)
* @param array $attributes Optional other attributes as array
* @param null|array $attributes Optional other attributes as array
* @return array Attributes (or null if still none)
*/
private static function add_class($class = '', array $attributes = null) {
private static function add_class($class = '', ?array $attributes = null) {
if ($class !== '') {
$classattribute = array('class' => $class);
$classattribute = ['class' => $class];
if ($attributes) {
if (array_key_exists('class', $attributes)) {
$attributes['class'] = trim($attributes['class'] . ' ' . $class);
@@ -817,10 +825,10 @@ class html_writer {
*
* @param string $content HTML content of tag
* @param string $class Optional CSS class (or classes as space-separated list)
* @param array $attributes Optional other attributes as array
* @param null|array $attributes Optional other attributes as array
* @return string HTML code for div
*/
public static function div($content, $class = '', array $attributes = null) {
public static function div($content, $class = '', ?array $attributes = null) {
return self::tag('div', $content, self::add_class($class, $attributes));
}
@@ -828,10 +836,10 @@ class html_writer {
* Starts a <div> tag. (Shortcut function.)
*
* @param string $class Optional CSS class (or classes as space-separated list)
* @param array $attributes Optional other attributes as array
* @param null|array $attributes Optional other attributes as array
* @return string HTML code for open div tag
*/
public static function start_div($class = '', array $attributes = null) {
public static function start_div($class = '', ?array $attributes = null) {
return self::start_tag('div', self::add_class($class, $attributes));
}
@@ -849,10 +857,10 @@ class html_writer {
*
* @param string $content HTML content of tag
* @param string $class Optional CSS class (or classes as space-separated list)
* @param array $attributes Optional other attributes as array
* @param null|array $attributes Optional other attributes as array
* @return string HTML code for span
*/
public static function span($content, $class = '', array $attributes = null) {
public static function span($content, $class = '', ?array $attributes = null) {
return self::tag('span', $content, self::add_class($class, $attributes));
}
@@ -860,10 +868,10 @@ class html_writer {
* Starts a <span> tag. (Shortcut function.)
*
* @param string $class Optional CSS class (or classes as space-separated list)
* @param array $attributes Optional other attributes as array
* @param null|array $attributes Optional other attributes as array
* @return string HTML code for open span tag
*/
public static function start_span($class = '', array $attributes = null) {
public static function start_span($class = '', ?array $attributes = null) {
return self::start_tag('span', self::add_class($class, $attributes));
}
-4
View File
@@ -25,8 +25,6 @@
namespace core\output;
defined('MOODLE_INTERNAL') || die();
/**
* Class allowing different systems for mapping and rendering icons.
*
@@ -41,6 +39,4 @@ defined('MOODLE_INTERNAL') || die();
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class icon_system_font extends icon_system {
}
@@ -30,7 +30,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class icon_system_fontawesome extends icon_system_font {
/**
* @var array $map Cached map of moodle icon names to font awesome icon names.
*/
@@ -459,7 +458,7 @@ class icon_system_fontawesome extends icon_system_font {
// Create different mapping keys for different icon system classes, there may be several different
// themes on the same site.
$mapkey = 'mapping_'.preg_replace('/[^a-zA-Z0-9_]/', '_', get_class($this));
$mapkey = 'mapping_' . preg_replace('/[^a-zA-Z0-9_]/', '_', get_class($this));
$this->map = $cache->get($mapkey);
if (empty($this->map)) {
@@ -476,16 +475,16 @@ class icon_system_fontawesome extends icon_system_font {
}
$cache->set($mapkey, $this->map);
}
}
return $this->map;
}
#[\Override]
public function get_amd_name() {
return 'core/icon_system_fontawesome';
}
#[\Override]
public function render_pix_icon(renderer_base $output, pix_icon $icon) {
$subtype = 'pix_icon_fontawesome';
$subpix = new $subtype($icon);
@@ -507,5 +506,4 @@ class icon_system_fontawesome extends icon_system_font {
return $output->render_from_template('core/pix_icon_fontawesome', $data);
}
}
+2 -1
View File
@@ -25,13 +25,14 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class icon_system_standard extends icon_system {
#[\Override]
public function render_pix_icon(renderer_base $output, pix_icon $icon) {
$data = $icon->export_for_template($output);
return $output->render_from_template('core/pix_icon', $data);
}
#[\Override]
public function get_amd_name() {
return 'core/icon_system_standard';
}
}
+2 -2
View File
@@ -124,7 +124,7 @@ class initials_bar implements renderable, templatable {
$groupletter = new stdClass();
$groupletter->name = $letter;
if (!$this->minirender) {
$groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
$groupletter->url = $this->url->out(false, [$this->urlvar => $letter]);
} else {
$groupletter->input = $letter;
}
@@ -140,7 +140,7 @@ class initials_bar implements renderable, templatable {
$data->class = $this->class;
$data->title = $this->title;
if (!$this->minirender) {
$data->url = $this->url->out(false, array($this->urlvar => ''));
$data->url = $this->url->out(false, [$this->urlvar => '']);
} else {
$data->input = 'ALL';
}
+20 -10
View File
@@ -40,7 +40,7 @@ use lang_string;
* @copyright 2016 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class inplace_editable implements templatable, renderable {
class inplace_editable implements renderable, templatable {
/**
* @var string component responsible for diplsying/updating
*/
@@ -101,7 +101,8 @@ class inplace_editable implements templatable, renderable {
* Constructor.
*
* @param string $component name of the component or plugin responsible for the updating of the value (must declare callback)
* @param string $itemtype type of the item inside the component - each component/plugin may implement multiple inplace-editable elements
* @param string $itemtype type of the item inside the component
* Each component/plugin may implement multiple inplace-editable elements.
* @param int $itemid identifier of the item that can be edited in-place
* @param bool $editable whether this value is editable (check capabilities and editing mode), if false, only "displayvalue"
* will be displayed without anything else
@@ -112,8 +113,17 @@ class inplace_editable implements templatable, renderable {
* @param lang_string|string $editlabel label for the input element in the editing mode (for screenreaders)
* @param pix_icon|null $editicon icon to use to toggle editing
*/
public function __construct($component, $itemtype, $itemid, $editable,
$displayvalue, $value = null, $edithint = null, $editlabel = null, ?pix_icon $editicon = null) {
public function __construct(
$component,
$itemtype,
$itemid,
$editable,
$displayvalue,
$value = null,
$edithint = null,
$editlabel = null,
?pix_icon $editicon = null
) {
$this->component = $component;
$this->itemtype = $itemtype;
$this->itemid = $itemid;
@@ -138,7 +148,7 @@ class inplace_editable implements templatable, renderable {
*/
public function set_type_toggle($options = null) {
if ($options === null) {
$options = array(0, 1);
$options = [0, 1];
}
$options = array_values($options);
$idx = array_search($this->value, $options, true);
@@ -235,16 +245,16 @@ class inplace_editable implements templatable, renderable {
*/
public function export_for_template(\renderer_base $output) {
if (!$this->editable) {
return array(
'displayvalue' => (string)$this->displayvalue
);
return [
'displayvalue' => (string)$this->displayvalue,
];
}
if ($this->editicon === null) {
$this->editicon = new pix_icon('t/editstring', (string) $this->edithint);
}
return array(
return [
'component' => $this->component,
'itemtype' => $this->itemtype,
'itemid' => $this->itemid,
@@ -256,7 +266,7 @@ class inplace_editable implements templatable, renderable {
'type' => $this->type,
'options' => $this->options,
'linkeverything' => $this->get_linkeverything() ? 1 : 0,
);
];
}
/**
+14 -14
View File
@@ -30,11 +30,11 @@ class js_writer {
* Returns javascript code calling the function
*
* @param string $function function name, can be complex like Y.Event.purgeElement
* @param array $arguments parameters
* @param null|array $arguments parameters
* @param int $delay execution delay in seconds
* @return string JS code fragment
*/
public static function function_call($function, array $arguments = null, $delay=0) {
public static function function_call($function, ?array $arguments = null, $delay = 0) {
if ($arguments) {
$arguments = array_map('json_encode', convert_to_array($arguments));
$arguments = implode(', ', $arguments);
@@ -44,7 +44,7 @@ class js_writer {
$js = "$function($arguments);";
if ($delay) {
$delay = $delay * 1000; // in miliseconds
$delay = $delay * 1000; // Delay in miliseconds.
$js = "setTimeout(function() { $js }, $delay);";
}
return $js . "\n";
@@ -54,10 +54,10 @@ class js_writer {
* Special function which adds Y as first argument of function call.
*
* @param string $function The function to call
* @param array $extraarguments Any arguments to pass to it
* @param null|array $extraarguments Any arguments to pass to it
* @return string Some JS code
*/
public static function function_call_with_Y($function, array $extraarguments = null) {
public static function function_call_with_y($function, ?array $extraarguments = null) {
if ($extraarguments) {
$extraarguments = array_map('json_encode', convert_to_array($extraarguments));
$arguments = 'Y, ' . implode(', ', $extraarguments);
@@ -72,12 +72,12 @@ class js_writer {
*
* @param string $var If it is null then no var is assigned the new object.
* @param string $class The class to initialise an object for.
* @param array $arguments An array of args to pass to the init method.
* @param array $requirements Any modules required for this class.
* @param null|array $arguments An array of args to pass to the init method.
* @param null|array $requirements Any modules required for this class.
* @param int $delay The delay before initialisation. 0 = no delay.
* @return string Some JS code
*/
public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
public static function object_init($var, $class, ?array $arguments = null, ?array $requirements = null, $delay = 0) {
if (is_array($arguments)) {
$arguments = array_map('json_encode', convert_to_array($arguments));
$arguments = implode(', ', $arguments);
@@ -85,14 +85,14 @@ class js_writer {
if ($var === null) {
$js = "new $class(Y, $arguments);";
} else if (strpos($var, '.')!==false) {
} else if (strpos($var, '.') !== false) {
$js = "$var = new $class(Y, $arguments);";
} else {
$js = "var $var = new $class(Y, $arguments);";
}
if ($delay) {
$delay = $delay * 1000; // in miliseconds
$delay = $delay * 1000; // Delay in miliseconds.
$js = "setTimeout(function() { $js }, $delay);";
}
@@ -100,7 +100,7 @@ class js_writer {
$requirements = implode("', '", $requirements);
$js = "Y.use('$requirements', function(Y){ $js });";
}
return $js."\n";
return $js . "\n";
}
/**
@@ -122,7 +122,7 @@ class js_writer {
}
}
$output .= "$name = ".json_encode($value).";";
$output .= "$name = " . json_encode($value) . ";";
return $output;
}
@@ -134,10 +134,10 @@ class js_writer {
* array or string, element id is in the form "#idvalue"
* @param string $event A valid DOM event (click, mousedown, change etc.)
* @param string $function The name of the function to call
* @param array $arguments An optional array of argument parameters to pass to the function
* @param null|array $arguments An optional array of argument parameters to pass to the function
* @return string JS code fragment
*/
public static function event_handler($selector, $event, $function, array $arguments = null) {
public static function event_handler($selector, $event, $function, ?array $arguments = null) {
$selector = json_encode($selector);
$output = "Y.on('$event', $function, $selector, null";
if (!empty($arguments)) {
+1 -3
View File
@@ -34,7 +34,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class language_menu implements renderable, templatable {
/** @var \moodle_page $page the moodle page that the languague menu belongs to */
protected $page;
@@ -67,7 +66,7 @@ class language_menu implements renderable, templatable {
return false;
}
if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
if ($this->page->course != SITEID && !empty($this->page->course->lang)) {
// Do not show lang menu if language forced.
return false;
}
@@ -175,5 +174,4 @@ class language_menu implements renderable, templatable {
$singleselect->class = 'langmenu';
return $singleselect->export_for_template($output);
}
}
@@ -24,7 +24,7 @@ use stdClass;
/**
* Interface to a subpanel implementation.
*
* @package core_admin
* @package core
* @copyright 2023 Ferran Recio <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -30,7 +30,6 @@ use core\output\choicelist;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class status extends dialog {
/**
* @var choicelist content of dialog.
*/
@@ -27,7 +27,6 @@ use Mustache_LambdaHelper;
* @since 4.0
*/
class mustache_clean_string_helper {
/** @var mustache_string_helper A string helper instance that is being used internally for fetching strings */
private $stringhelper;
+3 -2
View File
@@ -19,6 +19,7 @@
*
* @copyright 2019 Ryan Wyllie <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
*/
namespace core\output;
@@ -28,6 +29,7 @@ namespace core\output;
*
* @copyright 2019 Ryan Wyllie <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
*/
class mustache_engine extends \Mustache_Engine {
/**
@@ -72,8 +74,7 @@ class mustache_engine extends \Mustache_Engine {
*
* @return \Mustache_HelperCollection
*/
public function getHelpers()
{
public function gethelpers() {
if (!isset($this->helpers)) {
$this->helpers = new mustache_helper_collection(null, $this->disallowednestedhelpers);
}
@@ -25,7 +25,6 @@ namespace core\output;
* @since 2.9
*/
class mustache_filesystem_loader extends \Mustache_Loader_FilesystemLoader {
/**
* Provide a default no-args constructor (we don't really need anything).
*/
@@ -39,7 +38,7 @@ class mustache_filesystem_loader extends \Mustache_Loader_FilesystemLoader {
* @param string $name
* @return string Template file name
*/
protected function getFileName($name) {
protected function getfilename($name) {
// Call the Moodle template finder.
return mustache_template_finder::get_template_filepath($name);
}
@@ -52,7 +51,7 @@ class mustache_filesystem_loader extends \Mustache_Loader_FilesystemLoader {
*
* @return bool Whether to check `is_dir` and `file_exists`
*/
protected function shouldCheckPath() {
protected function shouldcheckpath() {
return true;
}
@@ -24,7 +24,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mustache_helper_collection extends \Mustache_HelperCollection {
/**
* @var string[] Names of helpers that aren't allowed to be called within other helpers.
*/
@@ -67,7 +66,7 @@ class mustache_helper_collection extends \Mustache_HelperCollection {
$disallowedlist = $this->disallowednestedhelpers;
if (is_callable($helper) && !empty($disallowedlist)) {
$helper = function($source, \Mustache_LambdaHelper $lambdahelper) use ($helper, $disallowedlist) {
$helper = function ($source, \Mustache_LambdaHelper $lambdahelper) use ($helper, $disallowedlist) {
// Temporarily override the disallowed helpers to return nothing
// so that they can't be executed from within other helpers.
@@ -105,7 +104,7 @@ class mustache_helper_collection extends \Mustache_HelperCollection {
$function = $this->get($name);
// Null out the helper. Must call parent::add here to avoid
// a recursion problem.
parent::add($name, function() {
parent::add($name, function () {
return '';
});
@@ -149,11 +148,11 @@ class mustache_helper_collection extends \Mustache_HelperCollection {
$endtoken = '\/';
}
$regexes = array_map(function($name) use ($starttoken, $endtoken) {
$regexes = array_map(function ($name) use ($starttoken, $endtoken) {
// We only strip out the name of the helper (excluding delimiters)
// the user is able to change the delimeters on a per template
// basis so they may not be curly braces.
return '/\s*' . $starttoken . '\s*'. $name . '\W+.*' . $endtoken . '\s*' . $name . '\s*/';
return '/\s*' . $starttoken . '\s*' . $name . '\W+.*' . $endtoken . '\s*' . $name . '\s*/';
}, $disallowedlist);
// This will strip out unwanted helpers from the $source string
@@ -163,7 +162,7 @@ class mustache_helper_collection extends \Mustache_HelperCollection {
// "core, move, {{#js}} some nasty JS hack {{/js}}"
// After:
// "core, move, {{}}".
return preg_replace_callback($regexes, function() {
return preg_replace_callback($regexes, function () {
return '';
}, $string);
}
@@ -25,7 +25,6 @@ namespace core\output;
* @since 2.9
*/
class mustache_javascript_helper {
/** @var \moodle_page $page - Page used to get requirement manager */
private $page = null;
@@ -32,7 +32,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mustache_quote_helper {
/**
* Wrap content in quotes, and escape all special JSON characters used.
*
@@ -26,7 +26,6 @@ use Mustache_LambdaHelper;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mustache_shorten_text_helper {
/**
* Read a length and text component from the string.
*
@@ -40,7 +39,7 @@ class mustache_shorten_text_helper {
*/
public function shorten($args, Mustache_LambdaHelper $helper) {
// Split the text into an array of variables.
list($length, $text) = explode(',', $args, 2);
[$length, $text] = explode(',', $args, 2);
$length = trim($length);
$text = trim($text);
@@ -25,9 +25,9 @@ use stdClass;
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 2.9
* @package core
*/
class mustache_string_helper {
/**
* Read a lang string from a template and get it from get_string.
*
@@ -26,6 +26,7 @@ use core_component;
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 2.9
* @package core
*/
class mustache_template_finder {
/**
@@ -48,14 +49,14 @@ class mustache_template_finder {
$themename = clean_param($themename, PARAM_COMPONENT);
// Validate the component.
$dirs = array();
$dirs = [];
$compdirectory = core_component::get_component_directory($component);
if (!$compdirectory) {
throw new coding_exception("Component was not valid: " . s($component));
}
// Find the parent themes.
$parents = array();
$parents = [];
if ($themename === $PAGE->theme->name) {
$parents = $PAGE->theme->parents;
} else {
@@ -97,7 +98,7 @@ class mustache_template_finder {
' (' . s($name) . ' requested) ');
}
list($component, $templatename) = explode('/', $name, 2);
[$component, $templatename] = explode('/', $name, 2);
$component = clean_param($component, PARAM_COMPONENT);
$dirs = self::get_template_directories_for_component($component, $themename);
@@ -16,16 +16,16 @@
namespace core\output;
use \Mustache_Tokenizer;
use Mustache_Tokenizer;
/**
* Load template source strings.
*
* @copyright 2018 Ryan Wyllie <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
*/
class mustache_template_source_loader {
/** @var $gettemplatesource Callback function to load the template source from full name */
private $gettemplatesource = null;
@@ -44,7 +44,7 @@ class mustache_template_source_loader {
$this->gettemplatesource = $gettemplatesource;
} else {
// By default we will pull the template from disk.
$this->gettemplatesource = function($component, $name, $themename) {
$this->gettemplatesource = function ($component, $name, $themename) {
$fulltemplatename = $component . '/' . $name;
$filename = mustache_template_finder::get_template_filepath($fulltemplatename, $themename);
return file_get_contents($filename);
@@ -150,7 +150,7 @@ class mustache_template_source_loader {
// Get the requested template source.
$templatesource = $this->load($templatecomponent, $templatename, $themename, $includecomments);
// This is a helper function to save a value in one of the result arrays (either $templates or $strings).
$save = function(array $results, array $seenlist, string $component, string $id, $value) use ($lang) {
$save = function (array $results, array $seenlist, string $component, string $id, $value) use ($lang) {
if (!isset($results[$component])) {
// If the results list doesn't already contain this component then initialise it.
$results[$component] = [];
@@ -165,7 +165,7 @@ class mustache_template_source_loader {
};
// This is a helper function for processing a dependency. Does stuff like ignore duplicate processing,
// common result formatting etc.
$handler = function(array $dependency, array $ignorelist, callable $processcallback) use ($lang) {
$handler = function (array $dependency, array $ignorelist, callable $processcallback) use ($lang) {
foreach ($dependency as $component => $ids) {
foreach ($ids as $id) {
$dependencyid = "$component/$id";
@@ -182,7 +182,7 @@ class mustache_template_source_loader {
};
// Save this template as the first result in the $templates result array.
list($templates, $seentemplates) = $save($templates, $seentemplates, $templatecomponent, $templatename, $templatesource);
[$templates, $seentemplates] = $save($templates, $seentemplates, $templatecomponent, $templatename, $templatesource);
// Check the template for any dependencies that need to be loaded.
$dependencies = $this->scan_template_source_for_dependencies($templatesource);
@@ -194,10 +194,10 @@ class mustache_template_source_loader {
$seenstrings,
// Include $strings and $seenstrings by reference so that their values can be updated
// outside of this anonymous function.
function($component, $id) use ($save, &$strings, &$seenstrings, $lang) {
function ($component, $id) use ($save, &$strings, &$seenstrings, $lang) {
$string = get_string_manager()->get_string($id, $component, null, $lang);
// Save the string in the $strings results array.
list($strings, $seenstrings) = $save($strings, $seenstrings, $component, $id, $string);
[$strings, $seenstrings] = $save($strings, $seenstrings, $component, $id, $string);
}
);
@@ -208,7 +208,10 @@ class mustache_template_source_loader {
$seentemplates,
// Include $strings, $seenstrings, $templates, and $seentemplates by reference so that their values can be updated
// outside of this anonymous function.
function($component, $id) use (
function (
$component,
$id
) use (
$themename,
$includecomments,
&$seentemplates,
@@ -232,14 +235,14 @@ class mustache_template_source_loader {
foreach ($subdependencies['templates'] as $component => $ids) {
foreach ($ids as $id => $value) {
// Include the child themes in our results.
list($templates, $seentemplates) = $save($templates, $seentemplates, $component, $id, $value);
[$templates, $seentemplates] = $save($templates, $seentemplates, $component, $id, $value);
}
};
foreach ($subdependencies['strings'] as $component => $ids) {
foreach ($ids as $id => $value) {
// Include any strings that the child templates need in our results.
list($strings, $seenstrings) = $save($strings, $seenstrings, $component, $id, $value);
[$strings, $seenstrings] = $save($strings, $seenstrings, $component, $id, $value);
}
}
}
@@ -247,7 +250,7 @@ class mustache_template_source_loader {
return [
'templates' => $templates,
'strings' => $strings
'strings' => $strings,
];
}
@@ -280,7 +283,7 @@ class mustache_template_source_loader {
$tokens = $tokenizer->scan($source);
$templates = [];
$strings = [];
$addtodependencies = function($dependencies, $component, $id) {
$addtodependencies = function ($dependencies, $component, $id) {
$id = trim($id);
$component = trim($component);
@@ -302,16 +305,16 @@ class mustache_template_source_loader {
if ($name) {
switch ($type) {
case Mustache_Tokenizer::T_PARTIAL:
list($component, $id) = explode('/', $name, 2);
[$component, $id] = explode('/', $name, 2);
$templates = $addtodependencies($templates, $component, $id);
break;
case Mustache_Tokenizer::T_PARENT:
list($component, $id) = explode('/', $name, 2);
[$component, $id] = explode('/', $name, 2);
$templates = $addtodependencies($templates, $component, $id);
break;
case Mustache_Tokenizer::T_SECTION:
if ($name == 'str') {
list($id, $component) = $this->get_string_identifiers($tokens, $index);
[$id, $component] = $this->get_string_identifiers($tokens, $index);
if ($id) {
$strings = $addtodependencies($strings, $component, $id);
@@ -324,7 +327,7 @@ class mustache_template_source_loader {
return [
'templates' => $templates,
'strings' => $strings
'strings' => $strings,
];
}
@@ -34,7 +34,6 @@ namespace core\output;
* @since 2.9
*/
class mustache_uniqid_helper {
/** @var string $uniqid The unique id */
private $uniqid = null;
@@ -23,6 +23,7 @@ use Mustache_LambdaHelper;
*
* @copyright 2017 Ryan Wyllie <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
*/
class mustache_user_date_helper {
/**
@@ -40,7 +41,7 @@ class mustache_user_date_helper {
*/
public function transform($args, Mustache_LambdaHelper $helper) {
// Split the text into an array of variables.
list($timestamp, $format) = explode(',', $args, 2);
[$timestamp, $format] = explode(',', $args, 2);
$timestamp = trim($timestamp);
$format = trim($format);
+9 -5
View File
@@ -34,7 +34,6 @@ namespace core\output;
* @category output
*/
class notification implements renderable, templatable {
/**
* A notification of level 'success'.
*/
@@ -78,7 +77,7 @@ class notification implements renderable, templatable {
/**
* @var array $extraclasses A list of any extra classes that may be required.
*/
protected $extraclasses = array();
protected $extraclasses = [];
/**
* Notification constructor.
@@ -129,7 +128,7 @@ class notification implements renderable, templatable {
* @param array $classes
* @return $this
*/
public function set_extra_classes($classes = array()) {
public function set_extra_classes($classes = []) {
$this->extraclasses = $classes;
return $this;
@@ -160,7 +159,7 @@ class notification implements renderable, templatable {
* @return array data context for a mustache template
*/
public function export_for_template(\renderer_base $output) {
return array(
return [
'message' => clean_text($this->message),
'extraclasses' => implode(' ', $this->extraclasses),
'announce' => $this->announce,
@@ -169,9 +168,14 @@ class notification implements renderable, templatable {
'isinfo' => $this->messagetype === 'info',
'iswarning' => $this->messagetype === 'warning',
'iserror' => $this->messagetype === 'error',
);
];
}
/**
* Get the name of the template to use for this templatable.
*
* @return string
*/
public function get_template_name() {
$templatemappings = [
// Current types mapped to template names.
+31 -15
View File
@@ -88,7 +88,7 @@ class paging_bar implements renderable, templatable {
/**
* @var array An array of strings. One of them is just a string: the current page
*/
public $pagelinks = array();
public $pagelinks = [];
/**
* Constructor paging_bar with only the required params.
@@ -136,7 +136,11 @@ class paging_bar implements renderable, templatable {
$pagenum = $this->page - 1;
if ($this->page > 0) {
$this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
$this->previouslink = html_writer::link(
new moodle_url($this->baseurl, [$this->pagevar => $pagenum]),
get_string('previous'),
['class' => 'previous'],
);
}
if ($this->perpage > 0) {
@@ -145,23 +149,27 @@ class paging_bar implements renderable, templatable {
$lastpage = 1;
}
if ($this->page > round(($this->maxdisplay/3)*2)) {
$currpage = $this->page - round($this->maxdisplay/3);
if ($this->page > round(($this->maxdisplay / 3) * 2)) {
$currpage = $this->page - round($this->maxdisplay / 3);
$this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
$this->firstlink = html_writer::link(
new moodle_url($this->baseurl, [$this->pagevar => 0]),
'1',
['class' => 'first'],
);
} else {
$currpage = 0;
}
$displaycount = $displaypage = 0;
while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
while ($displaycount < $this->maxdisplay && $currpage < $lastpage) {
$displaypage = $currpage + 1;
if ($this->page == $currpage) {
$this->pagelinks[] = html_writer::span($displaypage, 'current-page');
} else {
$pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
$pagelink = html_writer::link(new moodle_url($this->baseurl, [$this->pagevar => $currpage]), $displaypage);
$this->pagelinks[] = $pagelink;
}
@@ -171,13 +179,21 @@ class paging_bar implements renderable, templatable {
if ($currpage < $lastpage) {
$lastpageactual = $lastpage - 1;
$this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
$this->lastlink = html_writer::link(
new moodle_url($this->baseurl, [$this->pagevar => $lastpageactual]),
$lastpage,
['class' => 'last'],
);
}
$pagenum = $this->page + 1;
if ($pagenum != $lastpage) {
$this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
$this->nextlink = html_writer::link(
new moodle_url($this->baseurl, [$this->pagevar => $pagenum]),
get_string('next'),
['class' => 'next'],
);
}
}
}
@@ -206,7 +222,7 @@ class paging_bar implements renderable, templatable {
if ($this->page > 0) {
$data->previous = [
'page' => $this->page,
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false),
];
}
@@ -215,7 +231,7 @@ class paging_bar implements renderable, templatable {
$currpage = $this->page - round($this->maxdisplay / 3);
$data->first = [
'page' => 1,
'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false),
];
}
@@ -226,7 +242,7 @@ class paging_bar implements renderable, templatable {
$displaycount = 0;
$displaypage = 0;
while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
while ($displaycount < $this->maxdisplay && $currpage < $lastpage) {
$displaypage = $currpage + 1;
$iscurrent = $this->page == $currpage;
@@ -235,7 +251,7 @@ class paging_bar implements renderable, templatable {
$data->pages[] = [
'page' => $displaypage,
'active' => $iscurrent,
'url' => $iscurrent ? null : $link->out(false)
'url' => $iscurrent ? null : $link->out(false),
];
$displaycount++;
@@ -245,14 +261,14 @@ class paging_bar implements renderable, templatable {
if ($currpage < $lastpage) {
$data->last = [
'page' => $lastpage,
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false),
];
}
if ($this->page + 1 != $lastpage) {
$data->next = [
'page' => $this->page + 2,
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false),
];
}
+12 -8
View File
@@ -72,7 +72,7 @@ class participants_action_bar implements renderable {
'renameroles',
],
'groups:group' => [
'groups'
'groups',
],
'permissions:role' => [
'override',
@@ -98,8 +98,10 @@ class participants_action_bar implements renderable {
$formattedcontent = [];
$enrolmentsheading = get_string('enrolments', 'enrol');
if ($this->page->context->contextlevel != CONTEXT_MODULE &&
$this->page->context->contextlevel != CONTEXT_COURSECAT) {
if (
$this->page->context->contextlevel != CONTEXT_MODULE &&
$this->page->context->contextlevel != CONTEXT_COURSECAT
) {
// Pre-populate the formatted tertiary nav items with the "Enrolled users" node if user can view the participants page.
$coursecontext = context_course::instance($this->course->id);
$canviewparticipants = course_can_view_participants($coursecontext);
@@ -108,14 +110,14 @@ class participants_action_bar implements renderable {
$formattedcontent[] = [
$enrolmentsheading => [
$participantsurl => get_string('enrolledusers', 'enrol'),
]
],
];
}
}
$nodes = $this->get_ordered_nodes();
foreach ($nodes as $description => $content) {
list($stringid, $location) = explode(':', $description);
[$stringid, $location] = explode(':', $description);
$heading = get_string($stringid, $location);
$items = [];
foreach ($content as $key) {
@@ -129,7 +131,7 @@ class participants_action_bar implements renderable {
$params = ['id' => $this->course->id];
$items += [
(new moodle_url('/group/groupings.php', $params))->out() => get_string('groupings', 'group'),
(new moodle_url('/group/overview.php', $params))->out() => get_string('overview', 'group')
(new moodle_url('/group/overview.php', $params))->out() => get_string('overview', 'group'),
];
}
}
@@ -145,8 +147,10 @@ class participants_action_bar implements renderable {
}
// If we are accessing a page from a module/category context additional nodes will not be visible.
if ($this->page->context->contextlevel != CONTEXT_MODULE &&
$this->page->context->contextlevel != CONTEXT_COURSECAT) {
if (
$this->page->context->contextlevel != CONTEXT_MODULE &&
$this->page->context->contextlevel != CONTEXT_COURSECAT
) {
// Need to do some funky code here to find out if we have added third party navigation nodes.
$thirdpartynodearray = $this->get_thirdparty_node_array() ?: [];
$formattedcontent = array_merge($formattedcontent, $thirdpartynodearray);
+1 -1
View File
@@ -33,7 +33,7 @@ class pix_emoticon extends pix_icon implements renderable {
* @param string $component emoticon image provider
* @param array $attributes explicit HTML attributes
*/
public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
public function __construct($pix, $alt, $component = 'moodle', array $attributes = []) {
if (empty($attributes['class'])) {
$attributes['class'] = 'emoticon';
}
+15 -11
View File
@@ -26,21 +26,20 @@ namespace core\output;
* @category output
*/
class pix_icon implements renderable, templatable {
/**
* @var string The icon name
*/
var $pix;
public $pix;
/**
* @var string The component the icon belongs to.
*/
var $component;
public $component;
/**
* @var array An array of attributes to use on the icon
*/
var $attributes = array();
public $attributes = [];
/**
* Constructor
@@ -48,9 +47,14 @@ class pix_icon implements renderable, templatable {
* @param string $pix short icon name
* @param string $alt The alt text to use for the icon
* @param string $component component name
* @param array $attributes html attributes
* @param null|array $attributes html attributes
*/
public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
public function __construct(
$pix,
$alt,
$component = 'moodle',
?array $attributes = null,
) {
global $PAGE;
$this->pix = $pix;
@@ -109,18 +113,18 @@ class pix_icon implements renderable, templatable {
}
$attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
$templatecontext = array();
$templatecontext = [];
foreach ($attributes as $name => $value) {
$templatecontext[] = array('name' => $name, 'value' => $value);
$templatecontext[] = ['name' => $name, 'value' => $value];
}
$title = isset($attributes['title']) ? $attributes['title'] : '';
if (empty($title)) {
$title = isset($attributes['alt']) ? $attributes['alt'] : '';
}
$data = array(
$data = [
'attributes' => $templatecontext,
'extraclasses' => $extraclasses
);
'extraclasses' => $extraclasses,
];
return $data;
}
+3 -3
View File
@@ -82,12 +82,12 @@ class pix_icon_font implements templatable {
if (empty($title)) {
$title = $alt;
}
$data = array(
$data = [
'extraclasses' => $pixdata['extraclasses'],
'title' => $title,
'alt' => $alt,
'key' => $this->key
);
'key' => $this->key,
];
return $data;
}
+4 -4
View File
@@ -32,7 +32,7 @@ class plugin_renderer_base extends renderer_base {
/**
* @var renderer_base|core_renderer A reference to the current renderer.
* The renderer provided here will be determined by the page but will in 90%
* of cases by the {@link core_renderer}
* of cases by the {@see core_renderer}
*/
protected $output;
@@ -124,12 +124,12 @@ class plugin_renderer_base extends renderer_base {
*/
public function __call($method, $arguments) {
if (method_exists('renderer_base', $method)) {
throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
throw new coding_exception('Protected method called against ' . get_class($this) . ' :: ' . $method);
}
if (method_exists($this->output, $method)) {
return call_user_func_array(array($this->output, $method), $arguments);
return call_user_func_array([$this->output, $method], $arguments);
} else {
throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
throw new coding_exception('Unknown method called against ' . get_class($this) . ' :: ' . $method);
}
}
}
+16 -16
View File
@@ -35,7 +35,7 @@ use core\exception\coding_exception;
*/
class progress_bar implements renderable, templatable {
/** @var string html id */
private $html_id;
private $htmlid;
/** @var int total width */
private $width;
/** @var int last percentage printed */
@@ -43,7 +43,7 @@ class progress_bar implements renderable, templatable {
/** @var int time when last printed */
private $lastupdate = 0;
/** @var int when did we start printing this */
private $time_start = 0;
private $timestart = 0;
/**
* Constructor
@@ -60,9 +60,9 @@ class progress_bar implements renderable, templatable {
}
if (!empty($htmlid)) {
$this->html_id = $htmlid;
$this->htmlid = $htmlid;
} else {
$this->html_id = 'pbar_'.uniqid();
$this->htmlid = 'pbar_' . uniqid();
}
$this->width = $width;
@@ -77,7 +77,7 @@ class progress_bar implements renderable, templatable {
* @return string id
*/
public function get_id(): string {
return $this->html_id;
return $this->htmlid;
}
/**
@@ -88,7 +88,7 @@ class progress_bar implements renderable, templatable {
public function create() {
global $OUTPUT;
$this->time_start = microtime(true);
$this->timestart = microtime(true);
flush();
echo $OUTPUT->render($this);
@@ -103,21 +103,21 @@ class progress_bar implements renderable, templatable {
* @return void Echo's output
* @throws coding_exception
*/
private function _update($percent, $msg) {
private function update_raw($percent, $msg) {
global $OUTPUT;
if (empty($this->time_start)) {
if (empty($this->timestart)) {
throw new coding_exception('You must call create() (or use the $autostart ' .
'argument to the constructor) before you try updating the progress bar.');
}
$estimate = $this->estimate($percent);
if ($estimate === null) {
if ($estimate === null) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
// Always do the first and last updates.
} else if ($estimate == 0) {
} else if ($estimate == 0) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
// Always do the last updates.
} else if ($this->lastupdate + 20 < time()) {
} else if ($this->lastupdate + 20 < time()) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
// We must update otherwise browser would time out.
} else if (round($this->percent, 2) === round($percent, 2)) {
// No significant change, no need to update anything.
@@ -133,7 +133,7 @@ class progress_bar implements renderable, templatable {
$this->percent = $percent;
$this->lastupdate = microtime(true);
echo $OUTPUT->render_progress_bar_update($this->html_id, $this->percent, $msg, $estimatemsg);
echo $OUTPUT->render_progress_bar_update($this->htmlid, $this->percent, $msg, $estimatemsg);
flush();
}
@@ -153,7 +153,7 @@ class progress_bar implements renderable, templatable {
if ($pt > 99.99999) {
return 0; // Nearly done, right?
}
$consumed = microtime(true) - $this->time_start;
$consumed = microtime(true) - $this->timestart;
if ($consumed < 0.001) {
return null;
}
@@ -169,7 +169,7 @@ class progress_bar implements renderable, templatable {
*/
public function update_full($percent, $msg) {
$percent = max(min($percent, 100), 0);
$this->_update($percent, $msg);
$this->update_raw($percent, $msg);
}
/**
@@ -190,7 +190,7 @@ class progress_bar implements renderable, templatable {
public function restart() {
$this->percent = 0;
$this->lastupdate = 0;
$this->time_start = 0;
$this->timestart = 0;
}
/**
@@ -201,7 +201,7 @@ class progress_bar implements renderable, templatable {
*/
public function export_for_template(renderer_base $output) {
return [
'id' => $this->html_id,
'id' => $this->htmlid,
'width' => $this->width,
];
}
+2 -1
View File
@@ -20,11 +20,12 @@ namespace core\output;
* Interface marking other classes as suitable for renderer_base::render()
*
* @copyright 2010 Petr Skoda (skodak) [email protected]
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
* @category output
*/
interface renderable {
// intentionally empty
// Intentionally empty.
}
// Alias this class to the old name.
+30 -17
View File
@@ -22,6 +22,7 @@ use core\exception\coding_exception;
use core\output\actions\component_action;
use moodle_page;
use moodle_url;
use stdClass;
use Mustache_Exception_UnknownTemplateException;
/**
@@ -104,17 +105,17 @@ class renderer_base {
// We only expose the variables that are exposed to JS templates.
$safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
$helpers = array('config' => $safeconfig,
'str' => array($stringhelper, 'str'),
'cleanstr' => array($cleanstringhelper, 'cleanstr'),
'quote' => array($quotehelper, 'quote'),
'js' => array($jshelper, 'help'),
'pix' => array($pixhelper, 'pix'),
'shortentext' => array($shortentexthelper, 'shorten'),
'userdate' => array($userdatehelper, 'transform'),
);
$helpers = ['config' => $safeconfig,
'str' => [$stringhelper, 'str'],
'cleanstr' => [$cleanstringhelper, 'cleanstr'],
'quote' => [$quotehelper, 'quote'],
'js' => [$jshelper, 'help'],
'pix' => [$pixhelper, 'pix'],
'shortentext' => [$shortentexthelper, 'shorten'],
'userdate' => [$userdatehelper, 'transform'],
];
$this->mustache = new mustache_engine(array(
$this->mustache = new mustache_engine([
'cache' => $cachedir,
'escape' => 's',
'loader' => $loader,
@@ -126,8 +127,7 @@ class renderer_base {
'disallowednestedhelpers' => ['js'],
// Disable lambda rendering - content in helpers is already rendered, no need to render it again.
'disable_lambda_rendering' => true,
));
]);
}
return $this->mustache;
@@ -158,6 +158,7 @@ class renderer_base {
* Simple types are array,stdClass,bool,int,float,string
*
* @since 2.9
* @param string $templatename The template to render
* @param array|stdClass $context Context containing data for the template.
* @return string|boolean
*/
@@ -257,7 +258,7 @@ class renderer_base {
*
* This method adds a JS event for the provided component action to the page
* and then returns the id that the event has been attached to.
* If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
* If no id has been provided then a new ID is generated by {@see html_writer::random_id()}
*
* @param component_action $action
* @param string $id
@@ -357,8 +358,14 @@ class renderer_base {
$filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
// Use $CFG->themerev to prevent browser caching when the file changes.
return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
theme_get_revision(), $logo);
return moodle_url::make_pluginfile_url(
context_system::instance()->id,
'core_admin',
'logo',
$filepath,
theme_get_revision(),
$logo
);
}
/**
@@ -379,8 +386,14 @@ class renderer_base {
$filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
// Use $CFG->themerev to prevent browser caching when the file changes.
return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
theme_get_revision(), $logo);
return moodle_url::make_pluginfile_url(
context_system::instance()->id,
'core_admin',
'logocompact',
$filepath,
theme_get_revision(),
$logo
);
}
/**
@@ -68,15 +68,27 @@ abstract class renderer_factory_base implements renderer_factory_interface {
}
switch ($target) {
case RENDERER_TARGET_CLI: $suffix = '_cli'; break;
case RENDERER_TARGET_AJAX: $suffix = '_ajax'; break;
case RENDERER_TARGET_TEXTEMAIL: $suffix = '_textemail'; break;
case RENDERER_TARGET_HTMLEMAIL: $suffix = '_htmlemail'; break;
case RENDERER_TARGET_MAINTENANCE: $suffix = '_maintenance'; break;
default: $target = RENDERER_TARGET_GENERAL; $suffix = '';
case RENDERER_TARGET_CLI:
$suffix = '_cli';
break;
case RENDERER_TARGET_AJAX:
$suffix = '_ajax';
break;
case RENDERER_TARGET_TEXTEMAIL:
$suffix = '_textemail';
break;
case RENDERER_TARGET_HTMLEMAIL:
$suffix = '_htmlemail';
break;
case RENDERER_TARGET_MAINTENANCE:
$suffix = '_maintenance';
break;
default:
$target = RENDERER_TARGET_GENERAL;
$suffix = '';
}
return array($target, $suffix);
return [$target, $suffix];
}
/**
@@ -102,14 +114,14 @@ abstract class renderer_factory_base implements renderer_factory_interface {
*/
protected function standard_renderer_classnames($component, $subtype = null) {
global $CFG; // Needed in included files.
$classnames = array();
$classnames = [];
// Standardize component name ala frankenstyle.
list($plugin, $type) = core_component::normalize_component($component);
[$plugin, $type] = core_component::normalize_component($component);
if ($type === null) {
$component = $plugin;
} else {
$component = $plugin.'_'.$type;
$component = $plugin . '_' . $type;
}
if ($component !== 'core') {
@@ -121,7 +133,6 @@ abstract class renderer_factory_base implements renderer_factory_interface {
if (file_exists($rendererfile)) {
include_once($rendererfile);
}
} else if (!empty($subtype)) {
$coresubsystems = core_component::get_core_subsystems();
if (!array_key_exists($subtype, $coresubsystems)) { // There may be nulls.
@@ -137,63 +148,63 @@ abstract class renderer_factory_base implements renderer_factory_interface {
if (empty($subtype)) {
// Theme specific auto-loaded name (only valid when prefixed with the theme name).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => true,
'validwithoutprefix' => false,
'autoloaded' => true,
'classname' => '\\output\\' . $component . '_renderer'
);
'classname' => '\\output\\' . $component . '_renderer',
];
// Standard autoloaded plugin name (not valid with a prefix).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => false,
'validwithoutprefix' => true,
'autoloaded' => true,
'classname' => '\\' . $component . '\\output\\renderer'
);
'classname' => '\\' . $component . '\\output\\renderer',
];
// Legacy class name - (valid with or without a prefix).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => true,
'validwithoutprefix' => true,
'autoloaded' => false,
'classname' => $component . '_renderer'
);
'classname' => $component . '_renderer',
];
} else {
// Theme specific auto-loaded name (only valid when prefixed with the theme name).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => true,
'validwithoutprefix' => false,
'autoloaded' => true,
'classname' => '\\output\\' . $component . '\\' . $subtype . '_renderer'
);
'classname' => '\\output\\' . $component . '\\' . $subtype . '_renderer',
];
// Version of the above with subtype being a namespace level on it's own.
$classnames[] = array(
$classnames[] = [
'validwithprefix' => true,
'validwithoutprefix' => false,
'autoloaded' => true,
'classname' => '\\output\\' . $component . '\\' . $subtype . '\\renderer'
);
'classname' => '\\output\\' . $component . '\\' . $subtype . '\\renderer',
];
// Standard autoloaded plugin name (not valid with a prefix).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => false,
'validwithoutprefix' => true,
'autoloaded' => true,
'classname' => '\\' . $component . '\\output\\' . $subtype . '_renderer'
);
'classname' => '\\' . $component . '\\output\\' . $subtype . '_renderer',
];
// Version of the above with subtype being a namespace level on it's own.
$classnames[] = array(
$classnames[] = [
'validwithprefix' => false,
'validwithoutprefix' => true,
'autoloaded' => true,
'classname' => '\\' . $component . '\\output\\' . $subtype . '\\renderer'
);
'classname' => '\\' . $component . '\\output\\' . $subtype . '\\renderer',
];
// Legacy class name - (valid with or without a prefix).
$classnames[] = array(
$classnames[] = [
'validwithprefix' => true,
'validwithoutprefix' => true,
'autoloaded' => false,
'classname' => $component . '_' . $subtype . '_renderer'
);
'classname' => $component . '_' . $subtype . '_renderer',
];
}
return $classnames;
}
@@ -27,7 +27,7 @@ use core\output\renderer_base;
* if created automatically when the theme is set up.
*
* A renderer factory must also have a constructor that takes a theme_config object.
* (See {@link renderer_factory_base::__construct} for an example.)
* (See {@see renderer_factory_base::__construct} for an example.)
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
@@ -61,7 +61,7 @@ interface renderer_factory_interface {
* @param string $target one of rendering target constants
* @return renderer_base an object implementing the requested renderer interface.
*/
public function get_renderer(moodle_page $page, $component, $subtype=null, $target=null);
public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null);
}
// Alias this class to the old name.
@@ -45,7 +45,7 @@ class standard_renderer_factory extends renderer_factory_base {
$classnames = $this->standard_renderer_classnames($component, $subtype);
$classname = '';
list($target, $suffix) = $this->get_target_suffix($target);
[$target, $suffix] = $this->get_target_suffix($target);
// First look for a version with a suffix.
foreach ($classnames as $classnamedetails) {
if ($classnamedetails['validwithoutprefix']) {
@@ -40,7 +40,7 @@ class theme_overridden_renderer_factory extends renderer_factory_base {
/**
* @var array An array of renderer prefixes
*/
protected $prefixes = array();
protected $prefixes = [];
/**
* Constructor.
@@ -64,7 +64,7 @@ class theme_overridden_renderer_factory extends renderer_factory_base {
public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
$classnames = $this->standard_renderer_classnames($component, $subtype);
list($target, $suffix) = $this->get_target_suffix($target);
[$target, $suffix] = $this->get_target_suffix($target);
// Theme lib.php and renderers.php files are loaded automatically
// when loading the theme configs.
@@ -30,7 +30,6 @@ use js_writer;
* @category output
*/
class fragment_requirements_manager extends page_requirements_manager {
/**
* Page fragment constructor.
*/
@@ -84,7 +83,7 @@ class fragment_requirements_manager extends page_requirements_manager {
if (!empty($this->stringsforjs)) {
// Add all needed strings.
$strings = array();
$strings = [];
foreach ($this->stringsforjs as $component => $v) {
foreach ($v as $indentifier => $langstring) {
$strings[$component][$indentifier] = $langstring->out();
@@ -100,7 +99,7 @@ class fragment_requirements_manager extends page_requirements_manager {
if ($this->jsinitvariables['footer']) {
$js = '';
foreach ($this->jsinitvariables['footer'] as $data) {
list($var, $value) = $data;
[$var, $value] = $data;
$js .= js_writer::set_variable($var, $value, true);
}
$output .= html_writer::script($js);
@@ -48,7 +48,7 @@ use stdClass;
* $PAGE->requires->js_function_call('init_mymod', array($data), true);
* </pre>
*
* There are some natural restrictions on some methods. For example, {@link css()}
* There are some natural restrictions on some methods. For example, {@see css()}
* can only be called before the <head> tag is output. See the comments on the
* individual methods for details.
*
@@ -62,71 +62,71 @@ class page_requirements_manager {
/**
* @var array List of string available from JS
*/
protected $stringsforjs = array();
protected $stringsforjs = [];
/**
* @var array List of get_string $a parameters - used for validation only.
*/
protected $stringsforjs_as = array();
protected $stringsforjs_as = []; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
/**
* @var array List of JS variables to be initialised
*/
protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
protected $jsinitvariables = ['head' => [], 'footer' => []];
/**
* @var array Included JS scripts
*/
protected $jsincludes = array('head'=>array(), 'footer'=>array());
protected $jsincludes = ['head' => [], 'footer' => []];
/**
* @var array Inline scripts using RequireJS module loading.
*/
protected $amdjscode = array('');
protected $amdjscode = [''];
/**
* @var array List of needed function calls
*/
protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
protected $jscalls = ['normal' => [], 'ondomready' => []];
/**
* @var array List of skip links, those are needed for accessibility reasons
*/
protected $skiplinks = array();
protected $skiplinks = [];
/**
* @var array Javascript code used for initialisation of page, it should
* be relatively small
*/
protected $jsinitcode = array();
protected $jsinitcode = [];
/**
* @var array of moodle_url Theme sheets, initialised only from core_renderer
*/
protected $cssthemeurls = array();
protected $cssthemeurls = [];
/**
* @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
* Useful mostly only for CSS submitted by teachers that is not part of the theme.
*/
protected $cssurls = array();
protected $cssurls = [];
/**
* @var array List of requested event handlers
*/
protected $eventhandlers = array();
protected $eventhandlers = [];
/**
* @var array Extra modules
*/
protected $extramodules = array();
protected $extramodules = [];
/**
* @var array trackes the names of bits of HTML that are only required once
* per page. See {@link has_one_time_item_been_created()},
* {@link set_one_time_item_created()} and {@link should_create_one_time_item_now()}.
* per page. See {@see has_one_time_item_been_created()},
* {@see set_one_time_item_created()} and {@see should_create_one_time_item_now()}.
*/
protected $onetimeitemsoutput = array();
protected $onetimeitemsoutput = [];
/**
* @var bool Flag indicated head stuff already printed
@@ -146,27 +146,27 @@ class page_requirements_manager {
/**
* @var yui default YUI loader configuration
*/
protected $YUI_config;
protected $YUI_config; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
/**
* @var array $yuicssmodules
*/
protected $yuicssmodules = array();
protected $yuicssmodules = [];
/**
* @var array Some config vars exposed in JS, please no secret stuff there
*/
protected $M_cfg;
protected $M_cfg; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
/**
* @var array list of requested jQuery plugins
*/
protected $jqueryplugins = array();
protected $jqueryplugins = [];
/**
* @var array list of jQuery plugin overrides
*/
protected $jquerypluginoverrides = array();
protected $jquerypluginoverrides = [];
/**
* Page requirements constructor.
@@ -181,8 +181,8 @@ class page_requirements_manager {
$this->YUI_config = new yui();
// Set up some loader options.
$this->yui3loader->local_base = $CFG->wwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
$this->yui3loader->local_comboBase = $CFG->wwwroot . '/theme/yui_combo.php'.$sep;
$this->yui3loader->local_base = $CFG->wwwroot . '/lib/yuilib/' . $CFG->yui3version . '/';
$this->yui3loader->local_comboBase = $CFG->wwwroot . '/theme/yui_combo.php' . $sep;
$this->yui3loader->base = $this->yui3loader->local_base;
$this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
@@ -199,56 +199,58 @@ class page_requirements_manager {
// If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
if (!empty($CFG->yuipatchedmodules) && !empty($CFG->yuipatchlevel)) {
$this->YUI_config->define_patched_core_modules($this->yui3loader->local_comboBase,
$CFG->yui3version,
$CFG->yuipatchlevel,
$CFG->yuipatchedmodules);
$this->YUI_config->define_patched_core_modules(
$this->yui3loader->local_comboBase,
$CFG->yui3version,
$CFG->yuipatchlevel,
$CFG->yuipatchedmodules
);
}
$configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
$this->YUI_config->add_group('yui2', array(
$this->YUI_config->add_group('yui2', [
// Loader configuration for our 2in3.
'base' => $CFG->wwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php'.$sep,
'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep,
'combine' => $this->yui3loader->combine,
'ext' => false,
'root' => '2in3/' . $CFG->yui2version .'/build/',
'patterns' => array(
'yui2-' => array(
'root' => '2in3/' . $CFG->yui2version . '/build/',
'patterns' => [
'yui2-' => [
'group' => 'yui2',
'configFn' => $configname,
)
)
));
],
],
]);
$configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
$this->YUI_config->add_group('moodle', array(
$this->YUI_config->add_group('moodle', [
'name' => 'moodle',
'base' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
'combine' => $this->yui3loader->combine,
'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php'.$sep,
'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep,
'ext' => false,
'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
'patterns' => array(
'moodle-' => array(
'root' => 'm/' . $jsrev . '/', // Add the rev to the root path so that we can control caching.
'patterns' => [
'moodle-' => [
'group' => 'moodle',
'configFn' => $configname,
)
)
));
],
],
]);
$this->YUI_config->add_group('gallery', array(
$this->YUI_config->add_group('gallery', [
'name' => 'gallery',
'base' => $CFG->wwwroot . '/lib/yuilib/gallery/',
'combine' => $this->yui3loader->combine,
'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep,
'ext' => false,
'root' => 'gallery/' . $jsrev . '/',
'patterns' => array(
'gallery-' => array(
'patterns' => [
'gallery-' => [
'group' => 'gallery',
)
)
));
],
],
]);
// Set some more loader options applying to groups too.
if ($CFG->debugdeveloper) {
@@ -291,13 +293,14 @@ class page_requirements_manager {
* Return the safe config values that get set for javascript in "M.cfg".
*
* @since 2.9
* @param moodle_page $page The page to add JS to
* @param renderer_base $renderer The renderer to use
* @return array List of safe config values that are available to javascript.
*/
public function get_config_for_javascript(moodle_page $page, renderer_base $renderer) {
global $CFG;
if (empty($this->M_cfg)) {
$iconsystem = \core\output\icon_system::instance();
// It is possible that the $page->context is null, so we can't use $page->context->id.
@@ -310,7 +313,7 @@ class page_requirements_manager {
$coursecontext = context_course::instance($courseid);
}
$this->M_cfg = array(
$this->M_cfg = [
'wwwroot' => $CFG->wwwroot,
'homeurl' => $page->navigation->action,
'sesskey' => sesskey(),
@@ -332,14 +335,13 @@ class page_requirements_manager {
'langrev' => get_string_manager()->get_revision(),
'templaterev' => $this->get_templaterev(),
'siteId' => (int) SITEID,
);
];
if ($CFG->debugdeveloper) {
$this->M_cfg['developerdebug'] = true;
}
if (defined('BEHAT_SITE_RUNNING')) {
$this->M_cfg['behatsiterunning'] = true;
}
}
return $this->M_cfg;
}
@@ -369,21 +371,25 @@ class page_requirements_manager {
$this->js_init_call('M.util.init_frametop');
}
// Include block drag/drop if editing is on
// Include block drag/drop if editing is on.
if ($page->user_is_editing()) {
$params = array(
$params = [
'regions' => $page->blocks->get_regions(),
'pagehash' => $page->get_edited_page_hash(),
);
];
if (!empty($page->cm->id)) {
$params['cmid'] = $page->cm->id;
}
// Strings for drag and drop.
$this->strings_for_js(array('movecontent',
'tocontent',
'emptydragdropregion'),
'moodle');
$page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
$this->strings_for_js(
[
'movecontent',
'tocontent',
'emptydragdropregion',
],
'moodle',
);
$page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', [$params], null, true);
$page->requires->js_call_amd('core_block/edit', 'init', ['pagehash' => $page->get_edited_page_hash()]);
}
@@ -459,7 +465,7 @@ class page_requirements_manager {
*
* NOTE: this should not be used in official Moodle distribution!
*
* {@link https://moodledev.io/docs/guides/javascript/jquery}
* @link https://moodledev.io/docs/guides/javascript/jquery
*/
public function jquery() {
$this->jquery_plugin('jquery');
@@ -521,15 +527,18 @@ class page_requirements_manager {
return false;
}
if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css'))) {
debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
if ($component !== 'core' && in_array($plugin, ['jquery', 'ui', 'ui-css'])) {
debugging(
"jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.",
DEBUG_DEVELOPER,
);
$component = 'core';
} else if ($component !== 'core' and strpos($component, '_') === false) {
} else if ($component !== 'core' && strpos($component, '_') === false) {
// Let's normalise the legacy activity names, Frankenstyle rulez!
$component = 'mod_' . $component;
}
if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
if (empty($this->jqueryplugins) && ($component !== 'core' || $plugin !== 'jquery')) {
// Make sure the jQuery itself is always loaded first,
// the order of all other plugins depends on order of $PAGE_>requires->.
$this->jquery_plugin('jquery', 'core');
@@ -541,12 +550,12 @@ class page_requirements_manager {
}
$componentdir = core_component::get_component_directory($component);
if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
if (!file_exists($componentdir) || !file_exists("$componentdir/jquery/plugins.php")) {
debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
return false;
}
$plugins = array();
$plugins = [];
require("$componentdir/jquery/plugins.php");
if (!isset($plugins[$plugin])) {
@@ -557,7 +566,7 @@ class page_requirements_manager {
$this->jqueryplugins[$plugin] = new stdClass();
$this->jqueryplugins[$plugin]->plugin = $plugin;
$this->jqueryplugins[$plugin]->component = $component;
$this->jqueryplugins[$plugin]->urls = array();
$this->jqueryplugins[$plugin]->urls = [];
foreach ($plugins[$plugin]['files'] as $file) {
if ($CFG->debugdeveloper) {
@@ -575,12 +584,11 @@ class page_requirements_manager {
if (!empty($CFG->slasharguments)) {
$url = new moodle_url("/theme/jquery.php");
$url->set_slashargument("/$component/$file");
} else {
// This is not really good, we need slasharguments for relative links, this means no caching...
$path = realpath("$componentdir/jquery/$file");
if (strpos($path, $CFG->dirroot) === 0) {
$url = $CFG->wwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
$url = $CFG->wwwroot . preg_replace('/^' . preg_quote($CFG->dirroot, '/') . '/', '', $path);
// Replace all occurences of backslashes characters in url to forward slashes.
$url = str_replace('\\', '/', $url);
$url = new moodle_url($url);
@@ -618,7 +626,7 @@ class page_requirements_manager {
* This code prevents loading of standard 'ui-css' which my be requested by other plugins,
* the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
*
* {@link https://moodledev.io/docs/guides/javascript/jquery}
* @link https://moodledev.io/docs/guides/javascript/jquery
*
* @param string $oldplugin original plugin
* @param string $newplugin the replacement
@@ -642,8 +650,8 @@ class page_requirements_manager {
return '';
}
$included = array();
$urls = array();
$included = [];
$urls = [];
foreach ($this->jqueryplugins as $name => $unused) {
if (isset($included[$name])) {
@@ -655,7 +663,7 @@ class page_requirements_manager {
// in blank page.
$cyclic = true;
$oldname = $name;
for ($i=0; $i<100; $i++) {
for ($i = 0; $i < 100; $i++) {
$name = $this->jquerypluginoverrides[$name];
if (!array_key_exists($name, $this->jquerypluginoverrides)) {
$cyclic = false;
@@ -666,15 +674,12 @@ class page_requirements_manager {
// We can not do much with cyclic references here, let's use the old plugin.
$name = $oldname;
debugging("Cyclic overrides detected for jQuery plugin '$name'");
} else if (empty($name)) {
// Developer requested removal of the plugin.
continue;
} else if (!isset($this->jqueryplugins[$name])) {
debugging("Unknown jQuery override plugin '$name' detected");
$name = $oldname;
} else if (isset($included[$name])) {
// The plugin was already included, easy.
continue;
@@ -687,7 +692,7 @@ class page_requirements_manager {
}
$output = '';
$attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
$attributes = ['rel' => 'stylesheet', 'type' => 'text/css'];
foreach ($urls as $url) {
if (preg_match('/\.js$/', $url)) {
$output .= html_writer::script('', $url);
@@ -743,7 +748,7 @@ class page_requirements_manager {
return new moodle_url('/lib/javascript.php', ['rev' => $jsrev, 'jsfile' => $url]);
} else {
$returnurl = new moodle_url('/lib/javascript.php');
$returnurl->set_slashargument('/'.$jsrev.$url);
$returnurl->set_slashargument('/' . $jsrev . $url);
return $returnurl;
}
} else {
@@ -768,77 +773,104 @@ class page_requirements_manager {
if (strpos($component, 'core_') === 0) {
// Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
// so that we do nto have to repeat the definition of these modules over and over again.
switch($component) {
switch ($component) {
case 'core_filepicker':
$module = array('name' => 'core_filepicker',
'fullpath' => '/repository/filepicker.js',
'requires' => array(
'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue'
),
'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
array('referencesexist', 'repository'), array('select', 'repository')
));
$module = [
'name' => 'core_filepicker',
'fullpath' => '/repository/filepicker.js',
'requires' => [
'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue',
],
'strings' => [
['lastmodified', 'moodle'],
['name', 'moodle'],
['type', 'repository'],
['size', 'repository'],
['invalidjson', 'repository'],
['error', 'moodle'],
['info', 'moodle'],
['nofilesattached', 'repository'],
['filepicker', 'repository'],
['logout', 'repository'],
['nofilesavailable', 'repository'],
['norepositoriesavailable', 'repository'],
['fileexistsdialogheader', 'repository'],
['fileexistsdialog_editor', 'repository'],
['fileexistsdialog_filemanager', 'repository'],
['renameto', 'repository'],
['referencesexist', 'repository'],
['select', 'repository'],
],
];
break;
case 'core_comment':
$module = array('name' => 'core_comment',
'fullpath' => '/comment/comment.js',
'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay', 'escape'),
'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
);
$module = [
'name' => 'core_comment',
'fullpath' => '/comment/comment.js',
'requires' => ['base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay', 'escape'],
'strings' => [['confirmdeletecomments', 'admin'], ['yes', 'moodle'], ['no', 'moodle']],
];
break;
case 'core_role':
$module = array('name' => 'core_role',
'fullpath' => '/admin/roles/module.js',
'requires' => array('node', 'cookie'));
$module = [
'name' => 'core_role',
'fullpath' => '/admin/roles/module.js',
'requires' => ['node', 'cookie'],
];
break;
case 'core_completion':
break;
case 'core_message':
$module = array('name' => 'core_message',
'requires' => array('base', 'node', 'event', 'node-event-simulate'),
'fullpath' => '/message/module.js');
$module = [
'name' => 'core_message',
'requires' => ['base', 'node', 'event', 'node-event-simulate'],
'fullpath' => '/message/module.js',
];
break;
case 'core_group':
$module = array('name' => 'core_group',
'fullpath' => '/group/module.js',
'requires' => array('node', 'overlay', 'event-mouseenter'));
$module = [
'name' => 'core_group',
'fullpath' => '/group/module.js',
'requires' => ['node', 'overlay', 'event-mouseenter'],
];
break;
case 'core_question_engine':
$module = array('name' => 'core_question_engine',
'fullpath' => '/question/qengine.js',
'requires' => array('node', 'event'));
$module = [
'name' => 'core_question_engine',
'fullpath' => '/question/qengine.js',
'requires' => ['node', 'event'],
];
break;
case 'core_rating':
$module = array('name' => 'core_rating',
'fullpath' => '/rating/module.js',
'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
$module = [
'name' => 'core_rating',
'fullpath' => '/rating/module.js',
'requires' => ['node', 'event', 'overlay', 'io-base', 'json'],
];
break;
case 'core_dndupload':
$module = array('name' => 'core_dndupload',
'fullpath' => '/lib/form/dndupload.js',
'requires' => array('node', 'event', 'json', 'core_filepicker'),
'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesfile', 'error'),
array('sizegb', 'moodle'), array('sizemb', 'moodle'), array('sizekb', 'moodle'), array('sizeb', 'moodle'),
array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
array('changesmadereallygoaway', 'moodle'), array('complete', 'moodle')
));
$module = [
'name' => 'core_dndupload',
'fullpath' => '/lib/form/dndupload.js',
'requires' => ['node', 'event', 'json', 'core_filepicker'],
'strings' => [
['uploadformlimit', 'moodle'], ['droptoupload', 'moodle'], ['maxfilesreached', 'moodle'],
['dndenabled_inbox', 'moodle'], ['fileexists', 'moodle'], ['maxbytesfile', 'error'],
['sizegb', 'moodle'], ['sizemb', 'moodle'], ['sizekb', 'moodle'], ['sizeb', 'moodle'],
['maxareabytesreached', 'moodle'], ['serverconnection', 'error'],
['changesmadereallygoaway', 'moodle'], ['complete', 'moodle'],
],
];
break;
}
} else {
if ($dir = core_component::get_component_directory($component)) {
if (file_exists("$dir/module.js")) {
if (strpos($dir, $CFG->dirroot.'/') === 0) {
if (strpos($dir, $CFG->dirroot . '/') === 0) {
$dir = substr($dir, strlen($CFG->dirroot));
$module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
$module = ['name' => $component, 'fullpath' => "$dir/module.js", 'requires' => []];
}
}
}
@@ -865,7 +897,7 @@ class page_requirements_manager {
$module = $this->find_module($module);
}
if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
if (empty($module) || empty($module['name']) || empty($module['fullpath'])) {
throw new coding_exception('Missing YUI3 module details.');
}
@@ -883,7 +915,7 @@ class page_requirements_manager {
// Process module requirements and attempt to load each. This allows
// moodle modules to require each other.
if (!empty($module['requires'])){
if (!empty($module['requires'])) {
foreach ($module['requires'] as $requirement) {
$rmodule = $this->find_module($requirement);
if (is_array($rmodule)) {
@@ -919,7 +951,7 @@ class page_requirements_manager {
* Ensure that the specified CSS file is linked to from this page.
*
* Because stylesheet links must go in the <head> part of the HTML, you must call
* this function before {@link get_head_code()} is called. That normally means before
* this function before {@see get_head_code()} is called. That normally means before
* the call to print_header. If you call it when it is too late, an exception
* will be thrown.
*
@@ -942,8 +974,9 @@ class page_requirements_manager {
throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
}
// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
if ($stylesheet instanceof moodle_url) {
// ok
// Ok.
} else if (strpos($stylesheet, '/') === 0) {
$stylesheet = new moodle_url($stylesheet);
} else {
@@ -967,7 +1000,7 @@ class page_requirements_manager {
/**
* Ensure that a skip link to a given target is printed at the top of the <body>.
*
* You must call this function before {@link get_top_of_body_code()}, (if not, an exception
* You must call this function before {@see get_top_of_body_code()}, (if not, an exception
* will be thrown). That normally means you must call this before the call to print_header.
*
* If you ask for a particular skip link to be printed, it is then your responsibility
@@ -1007,16 +1040,21 @@ class page_requirements_manager {
* @param string $function the name of the JavaScritp function to call. Can
* be a compound name like 'Y.Event.purgeElement'. Can also be
* used to create and object by using a 'function name' like 'new user_selector'.
* @param array $arguments and array of arguments to be passed to the function.
* @param null|array $arguments and array of arguments to be passed to the function.
* When generating the function call, this will be escaped using json_encode,
* so passing objects and arrays should work.
* @param bool $ondomready If tru the function is only called when the dom is
* ready for manipulation.
* @param int $delay The delay before the function is called.
*/
public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
public function js_function_call(
$function,
?array $arguments = null,
$ondomready = false,
$delay = 0,
) {
$where = $ondomready ? 'ondomready' : 'normal';
$this->jscalls[$where][] = array($function, $arguments, $delay);
$this->jscalls[$where][] = [$function, $arguments, $delay];
}
/**
@@ -1042,7 +1080,7 @@ class page_requirements_manager {
* @param string $func Optional function from the module to call, defaults to just loading the AMD module.
* @param array $params The params to pass to the function (will be serialized into JSON).
*/
public function js_call_amd($fullmodule, $func = null, $params = array()) {
public function js_call_amd($fullmodule, $func = null, $params = []) {
global $CFG;
$modulepath = explode('/', $fullmodule);
@@ -1056,7 +1094,7 @@ class page_requirements_manager {
if ($func !== null) {
$func = clean_param($func, PARAM_ALPHANUMEXT);
$jsonparams = array();
$jsonparams = [];
foreach ($params as $param) {
$jsonparams[] = json_encode($param);
}
@@ -1096,20 +1134,34 @@ class page_requirements_manager {
*
* @param array|string $modules One or more modules
* @param string $function The function to call once modules have been loaded
* @param array $arguments An array of arguments to pass to the function
* @param string $galleryversion Deprecated: The gallery version to use
* @param null|array $arguments An array of arguments to pass to the function
* @param null|string $galleryversion Deprecated: The gallery version to use
* @param bool $ondomready
*/
public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
public function yui_module(
$modules,
$function,
?array $arguments = null,
$galleryversion = null,
$ondomready = false,
) {
if (!is_array($modules)) {
$modules = array($modules);
$modules = [$modules];
}
if ($galleryversion != null) {
debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
}
$jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
$jscode = 'Y.use(' .
join(
',',
array_map(
'json_encode',
convert_to_array($modules)
)
) .
',function() {' . js_writer::function_call($function, $arguments) . '});';
if ($ondomready) {
$jscode = "Y.on('domready', function() { $jscode });";
}
@@ -1121,7 +1173,7 @@ class page_requirements_manager {
*
* @param array $modules The list of YUI CSS Modules to include.
*/
public function set_yuicssmodules(array $modules = array()) {
public function set_yuicssmodules(array $modules = []) {
$this->yuicssmodules = $modules;
}
@@ -1131,13 +1183,18 @@ class page_requirements_manager {
*
* @param string $function the name of the JavaScritp function to with init code,
* usually something like 'M.mod_mymodule.init'
* @param array $extraarguments and array of arguments to be passed to the function.
* @param null|array $extraarguments and array of arguments to be passed to the function.
* The first argument is always the YUI3 Y instance with all required dependencies
* already loaded.
* @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
* @param array $module JS module specification array
* @param null|array $module JS module specification array
*/
public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
public function js_init_call(
$function,
?array $extraarguments = null,
$ondomready = false,
?array $module = null,
) {
$jscode = js_writer::function_call_with_Y($function, $extraarguments);
if (!$module) {
// Detect module automatically.
@@ -1157,10 +1214,14 @@ class page_requirements_manager {
*
* @param string $jscode
* @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
* @param array $module JS module specification array
* @param null|array $module JS module specification array
*/
public function js_init_code($jscode, $ondomready = false, array $module = null) {
$jscode = trim($jscode, " ;\n"). ';';
public function js_init_code(
$jscode,
$ondomready = false,
?array $module = null,
) {
$jscode = trim($jscode, " ;\n") . ';';
$uniqid = html_writer::random_id();
$startjs = " M.util.js_pending('" . $uniqid . "');";
@@ -1212,7 +1273,7 @@ class page_requirements_manager {
* alert(M.str.moodle.fullnamedisplay);
*
* To substitute the placeholder at client side, use M.util.get_string()
* function. It implements the same logic as {@link get_string()}:
* function. It implements the same logic as {@see get_string()}:
*
* // Require the string in PHP but keep {$a} as it is.
* $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
@@ -1222,7 +1283,7 @@ class page_requirements_manager {
*
* If you do need the same string expanded with different $a values in PHP
* on server side, then the solution is to put them in your own data structure
* (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
* (e.g. and array) that you pass to JavaScript with {@see data_for_js()}.
*
* @param string $identifier the desired string.
* @param string $component the language file to look in.
@@ -1232,9 +1293,11 @@ class page_requirements_manager {
if (!$component) {
throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
}
if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
throw new coding_exception("Attempt to re-define already required string '$identifier' " .
"from lang file '$component' with different \$a parameter?");
if (isset($this->stringsforjs_as[$component][$identifier]) && $this->stringsforjs_as[$component][$identifier] !== $a) {
throw new coding_exception(
"Attempt to re-define already required string '$identifier' " .
"from lang file '$component' with different \$a parameter?",
);
}
if (!isset($this->stringsforjs[$component][$identifier])) {
$this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
@@ -1245,7 +1308,7 @@ class page_requirements_manager {
/**
* Make an array of language strings available for JS.
*
* This function calls the above function {@link string_for_js()} for each requested
* This function calls the above function {@see string_for_js()} for each requested
* string in the $identifiers array that is passed to the argument for a single module
* passed in $module.
*
@@ -1297,9 +1360,9 @@ class page_requirements_manager {
* @param bool $inhead initialise in head
* @return void
*/
public function data_for_js($variable, $data, $inhead=false) {
public function data_for_js($variable, $data, $inhead = false) {
$where = $inhead ? 'head' : 'footer';
$this->jsinitvariables[$where][] = array($variable, $data);
$this->jsinitvariables[$where][] = [$variable, $data];
}
/**
@@ -1308,10 +1371,15 @@ class page_requirements_manager {
* @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
* @param string $event A valid DOM event (click, mousedown, change etc.)
* @param string $function The name of the function to call
* @param array $arguments An optional array of argument parameters to pass to the function
* @param null|array $arguments An optional array of argument parameters to pass to the function
*/
public function event_handler($selector, $event, $function, array $arguments = null) {
$this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
public function event_handler(
$selector,
$event,
$function,
?array $arguments = null,
) {
$this->eventhandlers[] = ['selector' => $selector, 'event' => $event, 'function' => $function, 'arguments' => $arguments];
}
/**
@@ -1439,21 +1507,27 @@ EOF;
$code = '';
if ($this->yui3loader->combine) {
if (!empty($this->yuicssmodules)) {
$modules = array();
$modules = [];
foreach ($this->yuicssmodules as $module) {
$modules[] = "$CFG->yui3version/$module/$module-min.css";
}
$code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
$code .= '<link rel="stylesheet" type="text/css" href="' .
$this->yui3loader->comboBase . implode('&amp;', $modules) . '" />';
}
$code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
$code .= '<link rel="stylesheet" type="text/css" href="' .
$this->yui3loader->local_comboBase . 'rollup/' . $CFG->yui3version . '/yui-moodlesimple' . $yuiformat .
'.css" />';
} else {
if (!empty($this->yuicssmodules)) {
foreach ($this->yuicssmodules as $module) {
$code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
$code .= '<link rel="stylesheet" type="text/css"href="' .
$this->yui3loader->base . $module . '/' . $module .
'-min.css" />';
}
}
$code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
$code .= '<link rel="stylesheet" type="text/css" href="' .
$this->yui3loader->local_comboBase . 'rollup/' . $CFG->yui3version . '/yui-moodlesimple' . $yuiformat .
'.css" />';
}
if ($this->yui3loader->filter === 'RAW') {
@@ -1489,9 +1563,9 @@ EOF;
$rollupversion .= '_' . $CFG->yuipatchlevel;
}
$baserollups = array(
$baserollups = [
'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
);
];
if ($this->yui3loader->combine) {
return '<script src="' .
@@ -1501,11 +1575,10 @@ EOF;
} else {
$code = '';
foreach ($baserollups as $rollup) {
$code .= '<script src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
$code .= '<script src="' . $this->yui3loader->local_comboBase . $rollup . '"></script>';
}
return $code;
}
}
/**
@@ -1518,7 +1591,7 @@ EOF;
// Please note custom CSS is strongly discouraged,
// because it can not be overridden by themes!
// It is suitable only for things like mod/data which accepts CSS from teachers.
$attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
$attributes = ['rel' => 'stylesheet', 'type' => 'text/css'];
// Add the YUI code first. We want this to be overridden by any Moodle CSS.
$code = $this->get_yui3lib_headcss();
@@ -1528,7 +1601,11 @@ EOF;
// As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
// ignored whenever another resource is added until such time as a redraw
// is forced, usually by moving the mouse over the affected element.
$code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
$code .= html_writer::tag(
'script',
'/** Required in order to fix style inclusion problems in IE with YUI **/',
['id' => 'firstthemesheet', 'type' => 'text/css'],
);
$urls = $this->cssthemeurls + $this->cssurls;
foreach ($urls as $url) {
@@ -1550,7 +1627,7 @@ EOF;
if (empty($this->extramodules)) {
return '';
}
return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
return html_writer::script(js_writer::function_call('M.yui.add_module', [$this->extramodules]));
}
/**
@@ -1588,7 +1665,7 @@ EOF;
// Set up global YUI3 loader object - this should contain all code needed by plugins.
// Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
// this needs to be done before including any other script.
// this needs to be done before including any other script.
$js .= $this->YUI_config->get_config_functions();
$js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
$js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
@@ -1600,7 +1677,7 @@ EOF;
if ($this->jsinitvariables['head']) {
$js = '';
foreach ($this->jsinitvariables['head'] as $data) {
list($var, $value) = $data;
[$var, $value] = $data;
$js .= js_writer::set_variable($var, $value, true);
}
$output .= html_writer::script($js);
@@ -1670,7 +1747,7 @@ EOF;
if ($CFG->debugdeveloper) {
$logconfig->level = 'trace';
}
$this->js_call_amd('core/log', 'setConfig', array($logconfig));
$this->js_call_amd('core/log', 'setConfig', [$logconfig]);
// Add any global JS that needs to run on all pages.
$this->js_call_amd('core/page_global', 'init');
$this->js_call_amd('core/utility');
@@ -1692,7 +1769,7 @@ EOF;
// Add all needed strings.
// First add core strings required for some dialogues.
$this->strings_for_js(array(
$this->strings_for_js([
'confirm',
'yes',
'no',
@@ -1705,17 +1782,17 @@ EOF;
// TODO MDL-70830 shortforms should preload the collapseall/expandall strings properly.
'collapseall',
'expandall',
), 'moodle');
$this->strings_for_js(array(
], 'moodle');
$this->strings_for_js([
'debuginfo',
'line',
'stacktrace',
), 'debug');
], 'debug');
$this->string_for_js('labelsep', 'langconfig');
if (!empty($this->stringsforjs)) {
$strings = array();
foreach ($this->stringsforjs as $component=>$v) {
foreach($v as $indentifier => $langstring) {
$strings = [];
foreach ($this->stringsforjs as $component => $v) {
foreach ($v as $indentifier => $langstring) {
$strings[$component][$indentifier] = $langstring->out();
}
}
@@ -1726,7 +1803,7 @@ EOF;
if ($this->jsinitvariables['footer']) {
$js = '';
foreach ($this->jsinitvariables['footer'] as $data) {
list($var, $value) = $data;
[$var, $value] = $data;
$js .= js_writer::set_variable($var, $value, true);
}
$output .= html_writer::script($js);
@@ -1766,9 +1843,9 @@ EOF;
/**
* Should we generate a bit of content HTML that is only required once on
* this page (e.g. the contents of the modchooser), now? Basically, we call
* {@link has_one_time_item_been_created()}, and if the thing has not already
* {@see has_one_time_item_been_created()}, and if the thing has not already
* been output, we return true to tell the caller to generate it, and also
* call {@link set_one_time_item_created()} to record the fact that it is
* call {@see set_one_time_item_created()} to record the fact that it is
* about to be generated.
*
* That is, a typical usage pattern (in a renderer method) is:
@@ -1796,7 +1873,7 @@ EOF;
* Has a particular bit of HTML that is only required once on this page
* (e.g. the contents of the modchooser) already been generated?
*
* Normally, you can use the {@link should_create_one_time_item_now()} helper
* Normally, you can use the {@see should_create_one_time_item_now()} helper
* method rather than calling this method directly.
*
* @param string $thing identifier for the bit of content. Should be of the form
@@ -1811,7 +1888,7 @@ EOF;
* Indicate that a particular bit of HTML that is only required once on this
* page (e.g. the contents of the modchooser) has been generated (or is about to be)?
*
* Normally, you can use the {@link should_create_one_time_item_now()} helper
* Normally, you can use the {@see should_create_one_time_item_now()} helper
* method rather than calling this method directly.
*
* @param string $thing identifier for the bit of content. Should be of the form
+46 -31
View File
@@ -46,8 +46,8 @@ class yui {
public $combine;
public $filter = null;
public $insertBefore = 'firstthemesheet';
public $groups = array();
public $modules = array();
public $groups = [];
public $modules = [];
/** @var array The log sources that should be not be logged. */
public $logInclude = [];
/** @var array Tog sources that should be logged. */
@@ -58,7 +58,7 @@ class yui {
/**
* @var array List of functions used by the YUI Loader group pattern recognition.
*/
protected $jsconfigfunctions = array();
protected $jsconfigfunctions = [];
/**
* Create a new group within the YUI_config system.
@@ -70,7 +70,10 @@ class yui {
*/
public function add_group($name, $config) {
if (isset($this->groups[$name])) {
throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
throw new coding_exception(
"A YUI configuration group for '{$name}' already exists. " .
'To make changes to this group use YUI_config->update_group().',
);
}
$this->groups[$name] = $config;
}
@@ -88,7 +91,10 @@ class yui {
*/
public function update_group($name, $config) {
if (!isset($this->groups[$name])) {
throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
throw new coding_exception(
'The Moodle YUI module does not exist. ' .
'You must define the moodle module config using YUI_config->add_module_config first.',
);
}
$this->groups[$name] = $config;
}
@@ -101,13 +107,15 @@ class yui {
* The JS function your write will be passed a single argument 'name' containing the
* name of the module being loaded.
*
* @param $function String the body of the JavaScript function. This should be used i
* @param string $function String the body of the JavaScript function. This should be used i
* @return string the name of the function to use in the group pattern configuration.
*/
public function set_config_function($function) {
$configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
if (isset($this->jsconfigfunctions[$configname])) {
throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
throw new coding_exception(
"A YUI config function with this name already exists. Config function names must be unique.",
);
}
$this->jsconfigfunctions[$configname] = $function;
return '@' . $configname . '@';
@@ -119,7 +127,7 @@ class yui {
*
* When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
*
* @param $file The path to the JavaScript function used for YUI configuration.
* @param string $file The path to the JavaScript function used for YUI configuration.
* @return string the name of the function to use in the group pattern configuration.
*/
public function set_config_source($file) {
@@ -136,7 +144,7 @@ class yui {
$configfn = $cache->get($keyname);
if ($configfn === false) {
require_once($CFG->libdir . '/jslib.php');
$configfn = core_minify::js_files(array($fullpath));
$configfn = core_minify::js_files([$fullpath]);
$cache->set($keyname, $configfn);
}
}
@@ -161,7 +169,7 @@ class yui {
/**
* Update the header JavaScript with any required modification for the YUI Loader.
*
* @param $js String The JavaScript to manipulate.
* @param string $js String The JavaScript to manipulate.
* @return string the modified JS string.
*/
public function update_header_js($js) {
@@ -187,10 +195,13 @@ class yui {
public function add_module_config($name, $config, $group = null) {
if ($group) {
if (!isset($this->groups[$name])) {
throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
throw new coding_exception(
'The Moodle YUI module does not exist. ' .
'You must define the moodle module config using YUI_config->add_module_config first.',
);
}
if (!isset($this->groups[$group]['modules'])) {
$this->groups[$group]['modules'] = array();
$this->groups[$group]['modules'] = [];
}
$modules = &$this->groups[$group]['modules'];
} else {
@@ -212,16 +223,19 @@ class yui {
public function add_moodle_metadata() {
global $CFG;
if (!isset($this->groups['moodle'])) {
throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
throw new coding_exception(
'The Moodle YUI module does not exist. ' .
'You must define the moodle module config using YUI_config->add_module_config first.',
);
}
if (!isset($this->groups['moodle']['modules'])) {
$this->groups['moodle']['modules'] = array();
$this->groups['moodle']['modules'] = [];
}
$cache = cache::make('core', 'yuimodules');
if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
$metadata = array();
$metadata = [];
$metadata = $this->get_moodle_metadata();
$cache->delete('metadata');
} else {
@@ -233,8 +247,10 @@ class yui {
}
// Merge with any metadata added specific to this page which was added manually.
$this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
$metadata);
$this->groups['moodle']['modules'] = array_merge(
$this->groups['moodle']['modules'],
$metadata
);
}
/**
@@ -246,7 +262,7 @@ class yui {
* @return array of module metadata
*/
private function get_moodle_metadata() {
$moodlemodules = array();
$moodlemodules = [];
// Core isn't a plugin type or subsystem - handle it seperately.
if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
$moodlemodules = array_merge($moodlemodules, $module);
@@ -286,11 +302,11 @@ class yui {
private function get_moodle_path_metadata($path) {
// Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
$baseyui = $path . '/yui/src';
$modules = array();
$modules = [];
if (is_dir($baseyui)) {
$items = new DirectoryIterator($baseyui);
foreach ($items as $item) {
if ($item->isDot() or !$item->isDir()) {
if ($item->isDot() || !$item->isDir()) {
continue;
}
$metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
@@ -324,35 +340,34 @@ class yui {
// If we are using the local combobase in the loader, we can add a group and still make use of the combo
// loader. We just need to specify a different root which includes a slightly different YUI version number
// to include our patchlevel.
$patterns = array();
$modules = array();
$patterns = [];
$modules = [];
foreach ($patchedmodules as $modulename) {
// We must define the pattern and module here so that the loader uses our group configuration instead of
// the standard module definition. We may lose some metadata provided by upstream but this will be
// loaded when the module is loaded anyway.
$patterns[$modulename] = array(
$patterns[$modulename] = [
'group' => 'yui-patched',
);
$modules[$modulename] = array();
];
$modules[$modulename] = [];
}
// Actually add the patch group here.
$this->add_group('yui-patched', array(
$this->add_group('yui-patched', [
'combine' => true,
'root' => $subversion . '/',
'patterns' => $patterns,
'modules' => $modules,
));
]);
} else {
// The CDN is in use - we need to instead use the local combobase for this module and override the modules
// definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
// local base in browser caches.
$fullpathbase = $combobase . $subversion . '/';
foreach ($patchedmodules as $modulename) {
$this->modules[$modulename] = array(
'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
);
$this->modules[$modulename] = [
'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js',
];
}
}
}
+1 -1
View File
@@ -83,7 +83,7 @@ class select_menu implements renderable, templatable {
'name' => $groupname,
'isgroup' => true,
'id' => \html_writer::random_id('select-menu-group'),
'options' => []
'options' => [],
];
}
foreach ($optoptions as $optvalue => $optoption) {
+10 -5
View File
@@ -40,7 +40,7 @@ class single_button implements renderable {
self::BUTTON_SUCCESS,
self::BUTTON_DANGER,
self::BUTTON_WARNING,
self::BUTTON_INFO
self::BUTTON_INFO,
];
/**
@@ -117,7 +117,7 @@ class single_button implements renderable {
/**
* @var array List of attached actions
*/
public $actions = array();
public $actions = [];
/**
* @var array $params URL Params
@@ -143,8 +143,13 @@ class single_button implements renderable {
* @param string $type whether this is a primary button or another type, used for styling
* @param array $attributes Attributes for the HTML button tag
*/
public function __construct(moodle_url $url, $label, $method = 'post', $type = self::BUTTON_SECONDARY,
$attributes = []) {
public function __construct(
moodle_url $url,
$label,
$method = 'post',
$type = self::BUTTON_SECONDARY,
$attributes = []
) {
if (is_bool($type)) {
debugging('The boolean $primary is deprecated and replaced by $type,
use single_button::BUTTON_PRIMARY or self::BUTTON_SECONDARY instead');
@@ -262,7 +267,7 @@ class single_button implements renderable {
// Button actions.
$actions = $this->actions;
$data->actions = array_map(function($action) use ($output) {
$data->actions = array_map(function ($action) use ($output) {
return $action->export_for_template($output);
}, $actions);
$data->hasactions = !empty($data->actions);
+27 -22
View File
@@ -33,16 +33,15 @@ use stdClass;
* @category output
*/
class single_select implements renderable, templatable {
/**
* @var moodle_url Target url - includes hidden fields
*/
var $url;
public $url;
/**
* @var string Name of the select element.
*/
var $name;
public $name;
/**
* @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
@@ -50,62 +49,62 @@ class single_select implements renderable, templatable {
* array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
* array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
*/
var $options;
public $options;
/**
* @var string Selected option
*/
var $selected;
public $selected;
/**
* @var array Nothing selected
*/
var $nothing;
public $nothing;
/**
* @var array Extra select field attributes
*/
var $attributes = array();
public $attributes = [];
/**
* @var string Button label
*/
var $label = '';
public $label = '';
/**
* @var array Button label's attributes
*/
var $labelattributes = array();
public $labelattributes = [];
/**
* @var string Form submit method post or get
*/
var $method = 'get';
public $method = 'get';
/**
* @var string Wrapping div class
*/
var $class = 'singleselect';
public $class = 'singleselect';
/**
* @var bool True if button disabled, false if normal
*/
var $disabled = false;
public $disabled = false;
/**
* @var string Button tooltip
*/
var $tooltip = null;
public $tooltip = null;
/**
* @var string Form id
*/
var $formid = null;
public $formid = null;
/**
* @var help_icon The help icon for this element.
*/
var $helpicon = null;
public $helpicon = null;
/** @var component_action[] component action. */
public $actions = [];
@@ -119,7 +118,14 @@ class single_select implements renderable, templatable {
* @param ?array $nothing
* @param string $formid
*/
public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
public function __construct(
moodle_url $url,
$name,
array $options,
$selected = '',
$nothing = ['' => 'choosedots'],
$formid = null,
) {
$this->url = $url;
$this->name = $name;
$this->options = $options;
@@ -135,7 +141,7 @@ class single_select implements renderable, templatable {
* @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
*/
public function add_confirm_action($confirmmessage) {
$this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
$this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', ['message' => $confirmmessage]));
}
/**
@@ -172,10 +178,9 @@ class single_select implements renderable, templatable {
* @param string $label
* @param array $attributes (optional)
*/
public function set_label($label, $attributes = array()) {
public function set_label($label, $attributes = []) {
$this->label = $label;
$this->labelattributes = $attributes;
}
/**
@@ -207,7 +212,7 @@ class single_select implements renderable, templatable {
unset($attributes['disabled']);
// Map the attributes.
$data->attributes = array_map(function($key) use ($attributes) {
$data->attributes = array_map(function ($key) use ($attributes) {
return ['name' => $key, 'value' => $attributes[$key]];
}, array_keys($attributes));
@@ -260,7 +265,7 @@ class single_select implements renderable, templatable {
$data->options[] = [
'name' => $optgroupname,
'optgroup' => true,
'options' => $sublist
'options' => $sublist,
];
}
} else {
@@ -268,7 +273,7 @@ class single_select implements renderable, templatable {
'value' => $value,
'name' => $options[$value],
'selected' => strval($this->selected) === strval($value),
'optgroup' => false
'optgroup' => false,
];
if ($hasnothing && $nothingkey === $value) {
-1
View File
@@ -33,7 +33,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class sticky_footer implements named_templatable, renderable {
/**
* @var string content of the sticky footer.
*/
+11 -11
View File
@@ -23,28 +23,29 @@ use moodle_url;
*
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core
* @copyright Marina Glancy
*/
class tabobject implements renderable, templatable {
/** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
var $id;
public $id;
/** @var moodle_url|string link */
var $link;
public $link;
/** @var string text on the tab */
var $text;
public $text;
/** @var string title under the link, by defaul equals to text */
var $title;
public $title;
/** @var bool whether to display a link under the tab name when it's selected */
var $linkedwhenselected = false;
public $linkedwhenselected = false;
/** @var bool whether the tab is inactive */
var $inactive = false;
public $inactive = false;
/** @var bool indicates that this tab's child is selected */
var $activated = false;
public $activated = false;
/** @var bool indicates that this tab is selected */
var $selected = false;
public $selected = false;
/** @var array stores children tabobjects */
var $subtree = array();
public $subtree = [];
/** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
var $level = 1;
public $level = 1;
/**
* Constructor
@@ -140,7 +141,6 @@ class tabobject implements renderable, templatable {
'level' => $this->level,
];
}
}
// Alias this class to the old name.
+1 -1
View File
@@ -87,7 +87,7 @@ class tabtree extends tabobject {
return (object) [
'tabs' => $tabs,
'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false,
];
}
}
File diff suppressed because it is too large Load Diff
-3
View File
@@ -25,7 +25,6 @@ namespace core\output;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class theme_usage {
/** @var string The theme usage type for users. */
public const THEME_USAGE_TYPE_USER = 'user';
@@ -61,7 +60,6 @@ class theme_usage {
$isused = $cache->get($themename);
if ($isused === false) {
$sqlunions = [];
// For each context, check if the config is enabled and there is at least one use.
@@ -119,7 +117,6 @@ class theme_usage {
// Cache the result so we don't have to keep checking for this theme.
$cache->set($themename, $isused);
return $isused;
} else {
return $isused;
}
-6
View File
@@ -25,8 +25,6 @@
namespace core\output;
defined('MOODLE_INTERNAL') || die();
/**
* URL rewriter interface
*
@@ -36,7 +34,6 @@ defined('MOODLE_INTERNAL') || die();
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface url_rewriter {
/**
* Rewrite moodle_urls into another form.
*
@@ -52,7 +49,4 @@ interface url_rewriter {
* @return void
*/
public static function html_head_setup();
}
+17 -19
View File
@@ -36,62 +36,62 @@ class url_select implements renderable, templatable {
* array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
* array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
*/
var $urls;
public $urls;
/**
* @var string Selected option
*/
var $selected;
public $selected;
/**
* @var array Nothing selected
*/
var $nothing;
public $nothing;
/**
* @var array Extra select field attributes
*/
var $attributes = array();
public $attributes = [];
/**
* @var string Button label
*/
var $label = '';
public $label = '';
/**
* @var array Button label's attributes
*/
var $labelattributes = array();
public $labelattributes = [];
/**
* @var string Wrapping div class
*/
var $class = 'urlselect';
public $class = 'urlselect';
/**
* @var bool True if button disabled, false if normal
*/
var $disabled = false;
public $disabled = false;
/**
* @var string Button tooltip
*/
var $tooltip = null;
public $tooltip = null;
/**
* @var string Form id
*/
var $formid = null;
public $formid = null;
/**
* @var help_icon The help icon for this element.
*/
var $helpicon = null;
public $helpicon = null;
/**
* @var string If set, makes button visible with given name for button
*/
var $showbutton = null;
public $showbutton = null;
/**
* Constructor
@@ -102,7 +102,7 @@ class url_select implements renderable, templatable {
* @param string $showbutton Set to text of button if it should be visible
* or null if it should be hidden (hidden version always has text 'go')
*/
public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
public function __construct(array $urls, $selected = '', $nothing = ['' => 'choosedots'], $formid = null, $showbutton = null) {
$this->urls = $urls;
$this->selected = $selected;
$this->nothing = $nothing;
@@ -135,7 +135,7 @@ class url_select implements renderable, templatable {
* @param string $label
* @param array $attributes (optional)
*/
public function set_label($label, $attributes = array()) {
public function set_label($label, $attributes = []) {
$this->label = $label;
$this->labelattributes = $attributes;
}
@@ -149,12 +149,11 @@ class url_select implements renderable, templatable {
protected function clean_url($value) {
global $CFG;
// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
if (empty($value)) {
// Nothing.
} else if (strpos($value, $CFG->wwwroot . '/') === 0) {
$value = str_replace($CFG->wwwroot, '', $value);
} else if (strpos($value, '/') !== 0) {
debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
}
@@ -181,7 +180,7 @@ class url_select implements renderable, templatable {
$flattened[$groupname] = [
'name' => $groupname,
'isgroup' => true,
'options' => []
'options' => [],
];
}
foreach ($optoptions as $optvalue => $optoption) {
@@ -193,7 +192,6 @@ class url_select implements renderable, templatable {
];
}
}
} else {
$cleanedvalue = $this->clean_url($value);
$flattened[$cleanedvalue] = [
@@ -208,7 +206,7 @@ class url_select implements renderable, templatable {
$value = key($nothing);
$name = reset($nothing);
$flattened = [
$value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
$value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value],
] + $flattened;
}
+65 -33
View File
@@ -17,6 +17,7 @@
namespace core\output;
use core\context\user as context_user;
use core\exception\coding_exception;
use moodle_page;
use moodle_url;
use stdClass;
@@ -40,7 +41,7 @@ class user_picture implements renderable {
/**
* @var int The course id. Used when constructing the link to the user's
* profile, page course id used if not specified.
*/
*/
public $courseid;
/**
@@ -99,20 +100,28 @@ class user_picture implements renderable {
throw new coding_exception('User id is required when printing user avatar image.');
}
// only touch the DB if we are missing data and complain loudly...
// Only touch the DB if we are missing data and complain loudly...
$needrec = false;
foreach (\core_user\fields::get_picture_fields() as $field) {
if (!property_exists($user, $field)) {
$needrec = true;
debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
.'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER);
debugging(
"Missing {$field} property in {$user} object, "
. "this is a performance problem that needs to be fixed by a developer. "
. 'Please use the \core_user\fields API to get the full list of required fields.',
DEBUG_DEVELOPER,
);
break;
}
}
if ($needrec) {
$this->user = $DB->get_record('user', array('id' => $user->id),
implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST);
$this->user = $DB->get_record(
'user',
['id' => $user->id],
implode(',', \core_user\fields::get_picture_fields()),
MUST_EXIST
);
} else {
$this->user = clone($user);
}
@@ -126,14 +135,20 @@ class user_picture implements renderable {
* id of the result record. Please note it has to be converted back to id before rendering.
*
* @param string $tableprefix name of database table prefix in query
* @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
* @param null|array $extrafields extra fields to be included in result
* Do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE.
* @param string $idalias alias of id field
* @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
* @return string
* @deprecated since Moodle 3.11 MDL-45242
* @see \core_user\fields
*/
public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
public static function fields(
$tableprefix = '',
?array $extrafields = null,
$idalias = 'id',
$fieldprefix = '',
) {
debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER);
$userfields = \core_user\fields::for_userpic();
if ($extrafields) {
@@ -152,17 +167,21 @@ class user_picture implements renderable {
/**
* Extract the aliased user fields from a given record
*
* Given a record that was previously obtained using {@link self::fields()} with aliases,
* Given a record that was previously obtained using {@see self::fields()} with aliases,
* this method extracts user related unaliased fields.
*
* @param stdClass $record containing user picture fields
* @param array $extrafields extra fields included in the $record
* @param null|array $extrafields extra fields included in the $record
* @param string $idalias alias of the id field
* @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
* @return stdClass object with unaliased user fields
*/
public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
public static function unalias(
stdClass $record,
?array $extrafields = null,
$idalias = 'id',
$fieldprefix = '',
) {
if (empty($idalias)) {
$idalias = 'id';
}
@@ -175,18 +194,18 @@ class user_picture implements renderable {
$return->id = $record->{$idalias};
}
} else {
if (property_exists($record, $fieldprefix.$field)) {
$return->{$field} = $record->{$fieldprefix.$field};
if (property_exists($record, $fieldprefix . $field)) {
$return->{$field} = $record->{$fieldprefix . $field};
}
}
}
// add extra fields if not already there
// Add extra fields if not already there.
if ($extrafields) {
foreach ($extrafields as $e) {
if ($e === 'id' or property_exists($return, $e)) {
if ($e === 'id' || property_exists($return, $e)) {
continue;
}
$return->{$e} = $record->{$fieldprefix.$e};
$return->{$e} = $record->{$fieldprefix . $e};
}
}
@@ -200,10 +219,13 @@ class user_picture implements renderable {
* if requests are made for non-existent files etc.
*
* @param moodle_page $page
* @param renderer_base $renderer
* @param null|renderer_base $renderer
* @return moodle_url
*/
public function get_url(moodle_page $page, renderer_base $renderer = null) {
public function get_url(
moodle_page $page,
?renderer_base $renderer = null,
) {
global $CFG;
if (is_null($renderer)) {
@@ -215,7 +237,7 @@ class user_picture implements renderable {
if (empty($this->size)) {
$filename = 'f2';
$size = 35;
} else if ($this->size === true or $this->size == 1) {
} else if ($this->size === true || $this->size == 1) {
$filename = 'f1';
$size = 100;
} else if ($this->size > 100) {
@@ -229,10 +251,12 @@ class user_picture implements renderable {
$size = (int)$this->size;
}
$defaulturl = $renderer->image_url('u/'.$filename); // default image
$defaulturl = $renderer->image_url('u/' . $filename); // Default image.
if ((!empty($CFG->forcelogin) and !isloggedin()) ||
(!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
if (
(!empty($CFG->forcelogin) && !isloggedin()) ||
(!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))
) {
// Protect images if login required and not logged in;
// also if login is required for profile images and is not logged in or guest
// do not use require_login() because it is expensive and not suitable here anyway.
@@ -240,7 +264,7 @@ class user_picture implements renderable {
}
// First try to detect deleted users - but do not read from database for performance reasons!
if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
if (!empty($this->user->deleted) || !str_contains($this->user->email, '@')) {
// All deleted users should have email replaced by md5 hash,
// all active users are expected to have valid email.
return $defaulturl;
@@ -265,27 +289,35 @@ class user_picture implements renderable {
// in the circumstance that the profile picture is not available
// when the user actually requests it they still get the profile
// picture for the correct theme.
$path .= $page->theme->name.'/';
$path .= $page->theme->name . '/';
}
// Set the image URL to the URL for the uploaded file and return.
$url = moodle_url::make_pluginfile_url(
$contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
$contextid,
'user',
'icon',
null,
$path,
$filename,
false,
$this->includetoken
);
$url->param('rev', $this->user->picture);
return $url;
}
if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
// Normalise the size variable to acceptable bounds
if ($this->user->picture == 0 && !empty($CFG->enablegravatar)) {
// Normalise the size variable to acceptable bounds.
if ($size < 1 || $size > 512) {
$size = 35;
}
// Hash the users email address
// Hash the users email address.
$md5 = md5(strtolower(trim($this->user->email)));
// Build a gravatar URL with what we know.
// Find the best default image URL we can (MDL-35669)
// Find the best default image URL we can (MDL-35669).
if (empty($CFG->gravatardefaulturl)) {
$absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
$absoluteimagepath = $page->theme->resolve_image_location('u/' . $filename, 'core');
if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
$gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
} else {
@@ -298,9 +330,9 @@ class user_picture implements renderable {
// If the currently requested page is https then we'll return an
// https gravatar page.
if (is_https()) {
return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", ['s' => $size, 'd' => $gravatardefault]);
} else {
return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
return new moodle_url("http://www.gravatar.com/avatar/{$md5}", ['s' => $size, 'd' => $gravatardefault]);
}
}
+4 -4
View File
@@ -36,16 +36,16 @@ class xhtml_container_stack {
/**
* @var array Stores the list of open containers.
*/
protected $opencontainers = array();
protected $opencontainers = [];
/**
* @var array In developer debug mode, stores a stack trace of all opens and
* closes, so we can output helpful error messages when there is a mismatch.
*/
protected $log = array();
protected $log = [];
/**
* @var boolean Store whether we are developer debug mode. We need this in
* @var bool Store whether we are developer debug mode. We need this in
* several places including in the destructor where we may not have access to $CFG.
*/
protected $isdebugging;
@@ -61,7 +61,7 @@ class xhtml_container_stack {
/**
* Push the close HTML for a recently opened container onto the stack.
*
* @param string $type The type of container. This is checked when {@link pop()}
* @param string $type The type of container. This is checked when {@see pop()}
* is called and must match, otherwise a developer debug warning is output.
* @param string $closehtml The HTML required to close the container.
*/
+2
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
+2
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
+2
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
+3 -1
View File
@@ -14,7 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
// This file is deprecated, but it should never have been manually included by anything outside of lib/pagelib.php.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
'This file should not be manually included by any component.',
+13 -10
View File
@@ -59,7 +59,6 @@ function theme_get_revision() {
} else {
return $CFG->themerev;
}
} else {
return -1;
}
@@ -99,11 +98,11 @@ function theme_get_next_revision() {
global $CFG;
$next = time();
if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
if (isset($CFG->themerev) && ($next <= $CFG->themerev) && (($CFG->themerev - $next) < 60 * 60)) {
// This resolves problems when reset is requested repeatedly within 1s,
// the < 1h condition prevents accidental switching to future dates
// because we might not recover from it.
$next = $CFG->themerev+1;
$next = $CFG->themerev + 1;
}
return $next;
@@ -120,7 +119,7 @@ function theme_get_next_sub_revision_for_theme($themename) {
$next = time();
$current = theme_get_sub_revision_for_theme($themename);
if ($next <= $current and $current - $next < 60 * 60) {
if ($next <= $current && $current - $next < 60 * 60) {
// This resolves problems when reset is requested repeatedly within 1s,
// the < 1h condition prevents accidental switching to future dates
// because we might not recover from it.
@@ -160,7 +159,7 @@ function theme_get_config_file_path($themename) {
if (file_exists("{$CFG->dirroot}/theme/{$themename}/config.php")) {
return "{$CFG->dirroot}/theme/{$themename}/config.php";
} else if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$themename}/config.php")) {
} else if (!empty($CFG->themedir) && file_exists("{$CFG->themedir}/{$themename}/config.php")) {
return "{$CFG->themedir}/{$themename}/config.php";
} else {
return null;
@@ -191,8 +190,12 @@ function theme_get_css_filename($themename, $globalrevision, $themerevision, $di
* @param bool $cache Should the generated files be stored in local cache.
* @return array The built theme content in a multi-dimensional array of name => direction => content
*/
function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'],
$cache = true, $mtraceprogress = false): array {
function theme_build_css_for_themes(
$themeconfigs = [],
$directions = ['rtl', 'ltr'],
$cache = true,
$mtraceprogress = false
): array {
global $CFG;
if (empty($themeconfigs)) {
@@ -344,7 +347,7 @@ function template_reset_all_caches() {
global $CFG;
$next = time();
if (isset($CFG->templaterev) and $next <= $CFG->templaterev and $CFG->templaterev - $next < 60 * 60) {
if (isset($CFG->templaterev) && $next <= $CFG->templaterev && $CFG->templaterev - $next < 60 * 60) {
// This resolves problems when reset is requested repeatedly within 1s,
// the < 1h condition prevents accidental switching to future dates
// because we might not recover from it.
@@ -361,11 +364,11 @@ function js_reset_all_caches() {
global $CFG;
$next = time();
if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
if (isset($CFG->jsrev) && $next <= $CFG->jsrev && $CFG->jsrev - $next < 60 * 60) {
// This resolves problems when reset is requested repeatedly within 1s,
// the < 1h condition prevents accidental switching to future dates
// because we might not recover from it.
$next = $CFG->jsrev+1;
$next = $CFG->jsrev + 1;
}
set_config('jsrev', $next);
+2
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
+2
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php.
// Throwing an exception here should be fine because removing the manual inclusion should have no impact.
throw new \core\exception\coding_exception(
+21 -25
View File
@@ -27,25 +27,23 @@ require_once("{$CFG->libdir}/tablelib.php");
/**
* The table base export format.
*
* @package moodlecore
* @package core_table
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class base_export_format {
/**
* @var flexible_table or child class reference pointing to table class
* object from which to export data.
* @var flexible_table or child class reference pointing to table class object from which to export data.
*/
var $table;
public $table;
/**
* @var bool output started. Keeps track of whether any output has been
* started yet.
* @var bool output started. Keeps track of whether any output has been started yet.
*/
var $documentstarted = false;
public $documentstarted = false;
/**
* Constructor
* Constructor.
*
* @param flexible_table $table
*/
@@ -53,39 +51,37 @@ class base_export_format {
$this->table =& $table;
}
/**
* Old syntax of class constructor. Deprecated in PHP7.
*
* @deprecated since Moodle 3.1
*/
public function table_default_export_format_parent(&$table) {
debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
self::__construct($table);
}
function set_table(&$table) {
public function set_table(&$table) {
$this->table =& $table;
}
function add_data($row) {
public function add_data($row) {
return false;
}
function add_seperator() {
public function add_seperator() {
return false;
}
function document_started() {
public function document_started() {
return $this->documentstarted;
}
/**
* Format the text.
*
* Given text in a variety of format codings, this function returns
* the text as safe HTML or as plain text dependent on what is appropriate
* for the download format. The default removes all tags.
*
* @param string $text
* @param int $format
* @param null|array $options
* @param null|int $courseid
*/
function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
//use some whitespace to indicate where there was some line spacing.
$text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
public function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid = null) {
// Use some whitespace to indicate where there was some line spacing.
$text = str_replace(['</p>', "\n", "\r"], ' ', $text);
return html_entity_decode(strip_tags($text), ENT_COMPAT);
}
@@ -29,7 +29,7 @@ use core\dataformat;
/**
* Dataformat exporter
*
* @package core
* @package core_table
* @subpackage tablelib
* @copyright 2016 Brendan Heywood ([email protected])
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File diff suppressed because it is too large Load Diff
+8 -9
View File
@@ -17,7 +17,7 @@
namespace core_table\output;
/**
* Holds all the information required to render a <table> by {@link core_renderer::table()}
* Holds all the information required to render a <table> by {@see core_renderer::table()}
*
* Example of usage:
* $t = new html_table();
@@ -27,11 +27,10 @@ namespace core_table\output;
* @copyright 2009 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
* @package core
* @package core_table
* @category output
*/
class html_table {
/**
* @var string Value to use for the id attribute of the table
*/
@@ -40,7 +39,7 @@ class html_table {
/**
* @var array Attributes of HTML attributes for the <table> element
*/
public $attributes = array();
public $attributes = [];
/**
* @var array An array of headings. The n-th array item is used as a heading of the n-th column.
@@ -54,8 +53,8 @@ class html_table {
/**
* @var array An array that can be used to make a heading span multiple columns.
* In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
* the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
* In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
* the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
*
* Example of usage:
* $t->headspan = array(2,1);
@@ -122,20 +121,20 @@ class html_table {
public $data = [];
/**
* @deprecated since Moodle 2.0. Styling should be in the CSS.
* @var string Width of the table, percentage of the page preferred.
* @deprecated since Moodle 2.0. Styling should be in the CSS.
*/
public $width = null;
/**
* @deprecated since Moodle 2.0. Styling should be in the CSS.
* @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
* @deprecated since Moodle 2.0. Styling should be in the CSS.
*/
public $tablealign = null;
/**
* @deprecated since Moodle 2.0. Styling should be in the CSS.
* @var int Padding on each cell, in pixels
* @deprecated since Moodle 2.0. Styling should be in the CSS.
*/
public $cellpadding = null;
+2 -2
View File
@@ -22,7 +22,7 @@ namespace core_table\output;
* @copyright 2009 Nicolas Connault
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
* @package core
* @package core_table
* @category output
*/
class html_table_cell {
@@ -69,7 +69,7 @@ class html_table_cell {
/**
* @var array Attributes of additional HTML attributes for the <td> element
*/
public $attributes = array();
public $attributes = [];
/**
* Constructs a table cell
+6 -5
View File
@@ -22,7 +22,7 @@ namespace core_table\output;
* @copyright 2009 Nicolas Connault
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
* @package core
* @package core_table
* @category output
*/
class html_table_row {
@@ -34,7 +34,7 @@ class html_table_row {
/**
* @var array Array of html_table_cell objects
*/
public $cells = array();
public $cells = [];
/**
* @var string Value to use for the style attribute of the table row
@@ -44,13 +44,14 @@ class html_table_row {
/**
* @var array Attributes of additional HTML attributes for the <tr> element
*/
public $attributes = array();
public $attributes = [];
/**
* Constructor
* @param array $cells
*
* @param null|array $cells
*/
public function __construct(array $cells=null) {
public function __construct(?array $cells = null) {
$this->attributes['class'] = '';
$cells = (array)$cells;
foreach ($cells as $cell) {
+60 -39
View File
@@ -29,38 +29,39 @@ require_once("{$CFG->libdir}/tablelib.php");
/**
* A table whose data is provided by SQL queries.
*
* @package moodlecore
* @package core_table
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class sql_table extends flexible_table {
public $countsql = NULL;
public $countparams = NULL;
/**
* @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
*/
public $sql = NULL;
/**
* @var array|\Traversable Data fetched from the db.
*/
public $rawdata = NULL;
/** @var string The SQL query to count records */
public $countsql = null;
/**
* @var bool Overriding default for this.
*/
public $is_sortable = true;
/**
* @var bool Overriding default for this.
*/
public $is_collapsible = true;
/** @var array The parameters for the Count SQL */
public $countparams = null;
/** @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params' */
public $sql = null;
/** @var array|\Traversable Data fetched from the db */
public $rawdata = null;
/** @var bool Overriding default for this */
public $is_sortable = true; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
/** @var bool Overriding default for this */
public $is_collapsible = true; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
/**
* Create a new instance of the sql_table.
*
* @param string $uniqueid a string identifying this table.Used as a key in
* session vars.
*/
function __construct($uniqueid) {
public function __construct($uniqueid) {
parent::__construct($uniqueid);
// some sensible defaults
// Set some sensible defaults.
$this->set_attribute('class', 'generaltable generalbox');
}
@@ -89,8 +90,10 @@ class sql_table extends flexible_table {
* Closes recordset (for use after building the table).
*/
public function close_recordset() {
if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
$this->rawdata instanceof moodle_recordset)) {
if (
$this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
$this->rawdata instanceof moodle_recordset)
) {
$this->rawdata->close();
$this->rawdata = null;
}
@@ -98,14 +101,17 @@ class sql_table extends flexible_table {
/**
* Get any extra classes names to add to this row in the HTML.
* @param $row array the data for this row.
*
* @param array $row the data for this row.
* @return string added to the class="" attribute of the tr.
*/
function get_row_class($row) {
public function get_row_class($row) {
return '';
}
/**
* Set the SQL used to count records.
*
* This is only needed if you want to use different sql to count rows.
* Used for example when perhaps all db JOINS are not needed when counting
* records. You don't need to call this function the count_sql
@@ -113,8 +119,11 @@ class sql_table extends flexible_table {
*
* We need to count rows returned by the db seperately to the query itself
* as we need to know how many pages of data we have to display.
*
* @param string $sql
* @param null|array $params
*/
function set_count_sql($sql, array $params = NULL) {
public function set_count_sql($sql, ?array $params = null) {
$this->countsql = $sql;
$this->countparams = $params;
}
@@ -124,8 +133,13 @@ class sql_table extends flexible_table {
* SELECT $fields FROM $from WHERE $where
* Of course you can use sub-queries, JOINS etc. by putting them in the
* appropriate clause of the query.
*
* @param string $fields
* @param string $from
* @param string $where
* @param array $params
*/
function set_sql($fields, $from, $where, array $params = array()) {
public function set_sql($fields, $from, $where, array $params = []) {
$this->sql = new stdClass();
$this->sql->fields = $fields;
$this->sql->from = $from;
@@ -140,11 +154,11 @@ class sql_table extends flexible_table {
* @param bool $useinitialsbar do you want to use the initials bar. Bar
* will only be used if there is a fullname column defined for the table.
*/
function query_db($pagesize, $useinitialsbar=true) {
public function query_db($pagesize, $useinitialsbar = true) {
global $DB;
if (!$this->is_downloading()) {
if ($this->countsql === NULL) {
$this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
if ($this->countsql === null) {
$this->countsql = 'SELECT COUNT(1) FROM ' . $this->sql->from . ' WHERE ' . $this->sql->where;
$this->countparams = $this->sql->params;
}
$grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
@@ -152,12 +166,12 @@ class sql_table extends flexible_table {
$this->initialbars(true);
}
list($wsql, $wparams) = $this->get_sql_where();
[$wsql, $wparams] = $this->get_sql_where();
if ($wsql) {
$this->countsql .= ' AND '.$wsql;
$this->countsql .= ' AND ' . $wsql;
$this->countparams = array_merge($this->countparams, $wparams);
$this->sql->where .= ' AND '.$wsql;
$this->sql->where .= ' AND ' . $wsql;
$this->sql->params = array_merge($this->sql->params, $wparams);
$total = $DB->count_records_sql($this->countsql, $this->countparams);
@@ -168,7 +182,7 @@ class sql_table extends flexible_table {
$this->pagesize($pagesize, $total);
}
// Fetch the attempts
// Fetch the attempts.
$sort = $this->get_sql_sort();
if ($sort) {
$sort = "ORDER BY $sort";
@@ -189,14 +203,21 @@ class sql_table extends flexible_table {
/**
* Convenience method to call a number of methods for you to display the
* table.
*
* @param int $pagesize
* @param bool $useinitialsbar
* @param string $downloadhelpbutton
*/
function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') {
global $DB;
if (!$this->columns) {
$onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
$this->sql->params, IGNORE_MULTIPLE);
//if columns is not set then define columns as the keys of the rows returned
//from the db.
$onerow = $DB->get_record_sql(
"SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
$this->sql->params,
IGNORE_MULTIPLE
);
// If columns is not set then define columns as the keys of the rows returned
// from the db.
$this->define_columns(array_keys((array)$onerow));
$this->define_headers(array_keys((array)$onerow));
}
@@ -14,15 +14,24 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core\output;
use core_table\output\html_table;
use core_table\output\html_table_cell;
use core_table\output\html_table_row;
// phpcs:disable moodle.Commenting.DocblockDescription.Missing
/**
* Unit tests for the html_writer class.
*
* @package core
* @copyright 2010 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \html_writer
* @coversDefaultClass \html_writer
* @covers \core\output\html_writer
* @coversDefaultClass \\core\output\html_writer
*/
final class html_writer_test extends basic_testcase {
final class html_writer_test extends \basic_testcase {
/**
* @covers ::start_tag
*/
@@ -34,16 +43,20 @@ final class html_writer_test extends basic_testcase {
* @covers ::start_tag
*/
public function test_start_tag_with_attr(): void {
$this->assertSame('<div class="frog">',
html_writer::start_tag('div', array('class' => 'frog')));
$this->assertSame(
'<div class="frog">',
html_writer::start_tag('div', ['class' => 'frog'])
);
}
/**
* @covers ::start_tag
*/
public function test_start_tag_with_attrs(): void {
$this->assertSame('<div class="frog" id="mydiv">',
html_writer::start_tag('div', array('class' => 'frog', 'id' => 'mydiv')));
$this->assertSame(
'<div class="frog" id="mydiv">',
html_writer::start_tag('div', ['class' => 'frog', 'id' => 'mydiv']),
);
}
/**
@@ -64,48 +77,60 @@ final class html_writer_test extends basic_testcase {
* @covers ::empty_Tag
*/
public function test_empty_tag_with_attrs(): void {
$this->assertSame('<input type="submit" value="frog" />',
html_writer::empty_tag('input', array('type' => 'submit', 'value' => 'frog')));
$this->assertSame(
'<input type="submit" value="frog" />',
html_writer::empty_tag('input', ['type' => 'submit', 'value' => 'frog']),
);
}
/**
* @covers ::nonempty_tag
*/
public function test_nonempty_tag_with_content(): void {
$this->assertSame('<div>Hello world!</div>',
html_writer::nonempty_tag('div', 'Hello world!'));
$this->assertSame(
'<div>Hello world!</div>',
html_writer::nonempty_tag('div', 'Hello world!'),
);
}
/**
* @covers ::nonempty_tag
*/
public function test_nonempty_tag_empty(): void {
$this->assertSame('',
html_writer::nonempty_tag('div', ''));
$this->assertSame(
'',
html_writer::nonempty_tag('div', ''),
);
}
/**
* @covers ::nonempty_tag
*/
public function test_nonempty_tag_null(): void {
$this->assertSame('',
html_writer::nonempty_tag('div', null));
$this->assertSame(
'',
html_writer::nonempty_tag('div', null),
);
}
/**
* @covers ::nonempty_tag
*/
public function test_nonempty_tag_zero(): void {
$this->assertSame('<div class="score">0</div>',
html_writer::nonempty_tag('div', 0, array('class' => 'score')));
$this->assertSame(
'<div class="score">0</div>',
html_writer::nonempty_tag('div', 0, ['class' => 'score'])
);
}
/**
* @covers ::nonempty_tag
*/
public function test_nonempty_tag_zero_string(): void {
$this->assertSame('<div class="score">0</div>',
html_writer::nonempty_tag('div', '0', array('class' => 'score')));
$this->assertSame(
'<div class="score">0</div>',
html_writer::nonempty_tag('div', '0', ['class' => 'score'])
);
}
/**
@@ -113,20 +138,30 @@ final class html_writer_test extends basic_testcase {
*/
public function test_div(): void {
// All options.
$this->assertSame('<div class="frog" id="kermit">ribbit</div>',
html_writer::div('ribbit', 'frog', array('id' => 'kermit')));
$this->assertSame(
'<div class="frog" id="kermit">ribbit</div>',
html_writer::div('ribbit', 'frog', ['id' => 'kermit'])
);
// Combine class from attributes and $class.
$this->assertSame('<div class="amphibian frog">ribbit</div>',
html_writer::div('ribbit', 'frog', array('class' => 'amphibian')));
$this->assertSame(
'<div class="amphibian frog">ribbit</div>',
html_writer::div('ribbit', 'frog', ['class' => 'amphibian'])
);
// Class only.
$this->assertSame('<div class="frog">ribbit</div>',
html_writer::div('ribbit', 'frog'));
$this->assertSame(
'<div class="frog">ribbit</div>',
html_writer::div('ribbit', 'frog')
);
// Attributes only.
$this->assertSame('<div id="kermit">ribbit</div>',
html_writer::div('ribbit', '', array('id' => 'kermit')));
$this->assertSame(
'<div id="kermit">ribbit</div>',
html_writer::div('ribbit', '', ['id' => 'kermit'])
);
// No options.
$this->assertSame('<div>ribbit</div>',
html_writer::div('ribbit'));
$this->assertSame(
'<div>ribbit</div>',
html_writer::div('ribbit')
);
}
/**
@@ -134,20 +169,30 @@ final class html_writer_test extends basic_testcase {
*/
public function test_start_div(): void {
// All options.
$this->assertSame('<div class="frog" id="kermit">',
html_writer::start_div('frog', array('id' => 'kermit')));
$this->assertSame(
'<div class="frog" id="kermit">',
html_writer::start_div('frog', ['id' => 'kermit'])
);
// Combine class from attributes and $class.
$this->assertSame('<div class="amphibian frog">',
html_writer::start_div('frog', array('class' => 'amphibian')));
$this->assertSame(
'<div class="amphibian frog">',
html_writer::start_div('frog', ['class' => 'amphibian'])
);
// Class only.
$this->assertSame('<div class="frog">',
html_writer::start_div('frog'));
$this->assertSame(
'<div class="frog">',
html_writer::start_div('frog')
);
// Attributes only.
$this->assertSame('<div id="kermit">',
html_writer::start_div('', array('id' => 'kermit')));
$this->assertSame(
'<div id="kermit">',
html_writer::start_div('', ['id' => 'kermit'])
);
// No options.
$this->assertSame('<div>',
html_writer::start_div());
$this->assertSame(
'<div>',
html_writer::start_div()
);
}
/**
@@ -162,20 +207,30 @@ final class html_writer_test extends basic_testcase {
*/
public function test_span(): void {
// All options.
$this->assertSame('<span class="frog" id="kermit">ribbit</span>',
html_writer::span('ribbit', 'frog', array('id' => 'kermit')));
$this->assertSame(
'<span class="frog" id="kermit">ribbit</span>',
html_writer::span('ribbit', 'frog', ['id' => 'kermit'])
);
// Combine class from attributes and $class.
$this->assertSame('<span class="amphibian frog">ribbit</span>',
html_writer::span('ribbit', 'frog', array('class' => 'amphibian')));
$this->assertSame(
'<span class="amphibian frog">ribbit</span>',
html_writer::span('ribbit', 'frog', ['class' => 'amphibian'])
);
// Class only.
$this->assertSame('<span class="frog">ribbit</span>',
html_writer::span('ribbit', 'frog'));
$this->assertSame(
'<span class="frog">ribbit</span>',
html_writer::span('ribbit', 'frog')
);
// Attributes only.
$this->assertSame('<span id="kermit">ribbit</span>',
html_writer::span('ribbit', '', array('id' => 'kermit')));
$this->assertSame(
'<span id="kermit">ribbit</span>',
html_writer::span('ribbit', '', ['id' => 'kermit'])
);
// No options.
$this->assertSame('<span>ribbit</span>',
html_writer::span('ribbit'));
$this->assertSame(
'<span>ribbit</span>',
html_writer::span('ribbit')
);
}
/**
@@ -183,20 +238,30 @@ final class html_writer_test extends basic_testcase {
*/
public function test_start_span(): void {
// All options.
$this->assertSame('<span class="frog" id="kermit">',
html_writer::start_span('frog', array('id' => 'kermit')));
$this->assertSame(
'<span class="frog" id="kermit">',
html_writer::start_span('frog', ['id' => 'kermit'])
);
// Combine class from attributes and $class.
$this->assertSame('<span class="amphibian frog">',
html_writer::start_span('frog', array('class' => 'amphibian')));
$this->assertSame(
'<span class="amphibian frog">',
html_writer::start_span('frog', ['class' => 'amphibian'])
);
// Class only.
$this->assertSame('<span class="frog">',
html_writer::start_span('frog'));
$this->assertSame(
'<span class="frog">',
html_writer::start_span('frog')
);
// Attributes only.
$this->assertSame('<span id="kermit">',
html_writer::start_span('', array('id' => 'kermit')));
$this->assertSame(
'<span id="kermit">',
html_writer::start_span('', ['id' => 'kermit'])
);
// No options.
$this->assertSame('<span>',
html_writer::start_span());
$this->assertSame(
'<span>',
html_writer::start_span()
);
}
/**
@@ -208,9 +273,9 @@ final class html_writer_test extends basic_testcase {
/**
* @covers ::table
* @covers \html_table_row
* @covers \html_table_cell
* @covers \html_table
* @covers \core_table\output\html_table_row
* @covers \core_table\output\html_table_cell
* @covers \core_table\output\html_table
*/
public function test_table(): void {
$row = new html_table_row();
@@ -268,11 +333,11 @@ EOF;
$table = new html_table();
$table->id = "whodat";
$table->data = array(
array('fred', 'MDK'),
array('bob', 'Burgers'),
array('dave', 'Competitiveness')
);
$table->data = [
['fred', 'MDK'],
['bob', 'Burgers'],
['dave', 'Competitiveness'],
];
$table->caption = "Who even knows?";
$table->captionhide = true;
$table->responsive = false;