. /** * Class to abstract information about (category) context for web service export * @package local_treestudyplan * @copyright 2023 P.M. Kuipers * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace local_treestudyplan; use \context; /** * Class to abstract information about (category) context for web service export */ class contextinfo { /** @var context */ public $context; /** * Create new based on context * @param context $context The context to describe */ public function __construct(context $context) { $this->context = $context; } /** * Describe the result for the webservice model * @param int $value Webservice requirement constant * @return external_single_structure Webservice output structure */ public static function structure($value = VALUE_REQUIRED) { return new \external_single_structure([ "name" => new \external_value(PARAM_TEXT, 'context name'), "shortname" => new \external_value(PARAM_TEXT, 'context short name'), "path" => new \external_multiple_structure( new \external_value(PARAM_TEXT)), "shortpath" => new \external_multiple_structure( new \external_value(PARAM_TEXT)), ], 'context information', $value); } /** * Make the webservice result model * @return array Webservice value */ public function model() { $ctxpath = array_reverse($this->context->get_parent_context_ids(true)); if (count($ctxpath) > 1 && $ctxpath[0] == 1) { array_shift($ctxpath); } return [ "name" => $this->context->get_context_name(false, false), "shortname" => $this->context->get_context_name(false, true), "path" => array_map(function($c) { return \context::instance_by_id($c)->get_context_name(false, false); }, $ctxpath), "shortpath" => array_map(function($c) { return \context::instance_by_id($c)->get_context_name(false, true); }, $ctxpath), ]; } /** * Make new Contextinfo for context id * @param int $contextid Context id * @return self Contextinfo based on context id */ public static function by_id($contextid): self { return new self(self::context_by_id($contextid)); } /** * Find context by id, but also return system context for context id 0 * @param int $contextid Context id * @return context The context */ private static function context_by_id($contextid): \context { if ($contextid <= 1) { $contextid = 1; } return \context::instance_by_id($contextid); } }