Merge branch 'MDL-81073' of https://github.com/paulholden/moodle
[moodle.git] / availability / classes / capability_checker.php
blobb83be9d1bb1575fbafff521eeca9769209e282a2
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Used while evaluating conditions in bulk.
20 * This object caches get_users_by_capability results in case they are needed
21 * by multiple conditions.
23 * @package core_availability
24 * @copyright 2014 The Open University
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 namespace core_availability;
30 defined('MOODLE_INTERNAL') || die();
32 /**
33 * Used while evaluating conditions in bulk.
35 * This object caches get_users_by_capability results in case they are needed
36 * by multiple conditions.
38 * @package core_availability
39 * @copyright 2014 The Open University
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class capability_checker {
43 /** @var \context Course or module context */
44 protected $context;
46 /** @var array Associative array of capability => result */
47 protected $cache = array();
49 /**
50 * Constructs for given context.
52 * @param \context $context Context
54 public function __construct(\context $context) {
55 $this->context = $context;
58 /**
59 * Gets users on course who have the specified capability. Returns an array
60 * of user objects which only contain the 'id' field. If the same capability
61 * has already been checked (e.g. by another condition) then a cached
62 * result will be used.
64 * More fields are not necessary because this code is only used to filter
65 * users from an existing list.
67 * @param string $capability Required capability
68 * @return array Associative array of user id => objects containing only id
70 public function get_users_by_capability($capability) {
71 if (!array_key_exists($capability, $this->cache)) {
72 $this->cache[$capability] = get_users_by_capability(
73 $this->context, $capability, 'u.id');
75 return $this->cache[$capability];