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-28 11:43:46 +08:00
parent a81e8c47f1
commit 67ace38c82
4 changed files with 58 additions and 5 deletions
+20 -1
View File
@@ -4487,7 +4487,7 @@ function role_change_permission($roleid, $context, $capname, $permission) {
* @property-read string $path path to context, starts with system context
* @property-read dept $depth
*/
abstract class context extends stdClass {
abstract class context extends stdClass implements IteratorAggregate {
/*
* Google confirms that no other important framework is using "context" class,
@@ -4695,6 +4695,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 ======
/**