MDL-31789: Allowing context object to be passed to JS using json_encode()

Classes with magic properties such as context do not pass through json_encode().
The solution is to implement iterator in such classes and convert what we
feed to json_encode to array using 'foreach' before we pass it to json_encode():
- class context implements IteratorAggregate
- added function convert_to_array() that converts anything to array
- before calling json_encode we convert the argument to array
This commit is contained in:
Marina Glancy
2012-03-30 08:27:53 +08:00
parent a280078197
commit b2cb00c2e9
4 changed files with 58 additions and 5 deletions
+20 -1
View File
@@ -4541,7 +4541,7 @@ function role_change_permission($roleid, $context, $capname, $permission) {
* @property-read string $path path to context, starts with system context
* @property-read int $depth
*/
abstract class context extends stdClass {
abstract class context extends stdClass implements IteratorAggregate {
/**
* The context id
@@ -4787,6 +4787,25 @@ abstract class context extends stdClass {
debugging('Can not unset context instance properties!');
}
// ====== implementing method from interface IteratorAggregate ======
/**
* Create an iterator because magic vars can't be seen by 'foreach'.
*
* Now we can convert context object to array using convert_to_array(),
* and feed it properly to json_encode().
*/
public function getIterator() {
$ret = array(
'id' => $this->id,
'contextlevel' => $this->contextlevel,
'instanceid' => $this->instanceid,
'path' => $this->path,
'depth' => $this->depth
);
return new ArrayIterator($ret);
}
// ====== general context methods ======
/**