]> git.mjollnir.org Git - moodle.git/commitdiff
New convinience function in accesslib: get_parent_contextid. Also, the start of some...
authortjhunt <tjhunt>
Mon, 12 May 2008 15:28:34 +0000 (15:28 +0000)
committertjhunt <tjhunt>
Mon, 12 May 2008 15:28:34 +0000 (15:28 +0000)
lib/accesslib.php
lib/simpletest/testaccesslib.php [new file with mode: 0644]

index 22b7c477e2a05806cf1a15fac59145530e3f8a02..205d405564bcbfd71f03ef152938f92384c80211 100755 (executable)
@@ -3555,6 +3555,20 @@ function get_parent_contexts($context) {
     return array_reverse($parentcontexts);
 }
 
+/**
+ * Return the id of the parent of this context, or false if there is no parent (only happens if this
+ * is the site context.)
+ *
+ * @param object $context
+ * @return integer the id of the parent context.
+ */
+function get_parent_contextid($context) {
+    $parentcontexts = get_parent_contexts($context);
+    if (count($parentcontexts) == 0) {
+        return false; 
+    }
+    return array_shift($parentcontexts);
+}
 
 /**
  * Recursive function which, given a context, find all its children context ids.
diff --git a/lib/simpletest/testaccesslib.php b/lib/simpletest/testaccesslib.php
new file mode 100644 (file)
index 0000000..db04a70
--- /dev/null
@@ -0,0 +1,49 @@
+<?php
+/**
+ * Unit tests for (some of) ../accesslib.php.
+ *
+ * @copyright &copy; 2006 The Open University
+ * @author T.J.Hunt@open.ac.uk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+ * @package moodlecore
+ */
+
+if (!defined('MOODLE_INTERNAL')) {
+    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
+}
+
+class accesslib_test extends UnitTestCase {
+
+    function setUp() {
+    }
+
+    function tearDown() {
+    }
+
+    function test_get_parent_contexts() {
+        $context = get_context_instance(CONTEXT_SYSTEM);
+        $this->assertEqual(get_parent_contexts($context), array());
+
+        $context = new stdClass;
+        $context->path = '/1/25';
+        $this->assertEqual(get_parent_contexts($context), array(1));
+
+        $context = new stdClass;
+        $context->path = '/1/123/234/345/456';
+        $this->assertEqual(get_parent_contexts($context), array(345, 234, 123, 1));
+    }
+
+    function test_get_parent_contextid() {
+        $context = get_context_instance(CONTEXT_SYSTEM);
+        $this->assertFalse(get_parent_contextid($context));
+
+        $context = new stdClass;
+        $context->path = '/1/25';
+        $this->assertEqual(get_parent_contextid($context), 1);
+
+        $context = new stdClass;
+        $context->path = '/1/123/234/345/456';
+        $this->assertEqual(get_parent_contextid($context), 345);
+    }
+}
+?>