MDL-61621 blocks: New API function
authorDavid Monllao <davidm@moodle.com>
Wed, 7 Mar 2018 14:35:50 +0000 (15:35 +0100)
committerDavid Monllao <davidm@moodle.com>
Fri, 6 Apr 2018 11:12:30 +0000 (13:12 +0200)
lib/blocklib.php
lib/tests/blocklib_test.php

index 219a378..c8fa245 100644 (file)
@@ -1961,6 +1961,20 @@ function block_method_result($blockname, $method, $param = NULL) {
     return call_user_func(array('block_'.$blockname, $method), $param);
 }
 
+/**
+ * Returns a new instance of the specified block instance id.
+ *
+ * @param int $blockinstanceid
+ * @return block_base the requested block instance.
+ */
+function block_instance_by_id($blockinstanceid) {
+    global $DB;
+
+    $blockinstance = $DB->get_record('block_instances', ['id' => $blockinstanceid]);
+    $instance = block_instance($blockinstance->blockname, $blockinstance);
+    return $instance;
+}
+
 /**
  * Creates a new instance of the specified block class.
  *
index 92c94d4..664abc6 100644 (file)
@@ -324,6 +324,31 @@ class core_blocklib_testcase extends advanced_testcase {
         $this->assertEquals('4', $blocks[1]->instance->weight);
     }
 
+    /**
+     * Test block instances.
+     *
+     * @return null
+     */
+    public function test_block_instances() {
+        $this->purge_blocks();
+
+        // Set up fixture.
+        $regionname = 'a-region';
+        $blockname = $this->get_a_known_block_type();
+        $context = context_system::instance();
+
+        list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
+            $context, 'page-type');
+
+        $blockmanager->add_blocks(array($regionname => array($blockname, $blockname)), null, null, false, 3);
+        $blockmanager->load_blocks();
+
+        $blocks = $blockmanager->get_blocks_for_region($regionname);
+
+        $this->assertInstanceOf('\block_base', block_instance($blockname, $blocks[0]->instance));
+        $this->assertInstanceOf('\block_base', block_instance_by_id($blocks[0]->instance->id));
+    }
+
     public function test_block_not_included_in_different_context() {
         $this->purge_blocks();