MDL-50163 behat: Return subcontext from session
[moodle.git] / lib / behat / classes / behat_context_helper.php
CommitLineData
020cf9ae
DM
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.
13//
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/>.
16
17/**
8f76de32 18 * Helper to get behat contexts from other contexts.
020cf9ae
DM
19 *
20 * @package core
af4830a2 21 * @category test
020cf9ae
DM
22 * @copyright 2014 David MonllaĆ³
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
8f76de32 28use \Behat\Behat\Context\BehatContext;
020cf9ae
DM
29
30/**
31 * Helper to get behat contexts.
32 *
33 * @package core
af4830a2 34 * @category test
020cf9ae
DM
35 * @copyright 2014 David MonllaĆ³
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class behat_context_helper {
39
40 /**
8f76de32 41 * @var BehatContext main behat context.
020cf9ae 42 */
8f76de32 43 protected static $maincontext = false;
020cf9ae
DM
44
45 /**
8f76de32 46 * Save main behat context reference to be used for finding sub-contexts.
020cf9ae 47 *
8f76de32 48 * @param BehatContext $maincontext
020cf9ae
DM
49 * @return void
50 */
8f76de32
RT
51 public static function set_main_context(BehatContext $maincontext) {
52 self::$maincontext = $maincontext;
020cf9ae
DM
53 }
54
55 /**
56 * Gets the required context.
57 *
58 * Getting a context you get access to all the steps
59 * that uses direct API calls; steps returning step chains
60 * can not be executed like this.
61 *
62 * @throws coding_exception
af4830a2 63 * @param string $classname Context identifier (the class name).
020cf9ae
DM
64 * @return behat_base
65 */
66 public static function get($classname) {
67
8f76de32 68 if (!$subcontext = self::$maincontext->getSubcontextByClassName($classname)) {
020cf9ae
DM
69 throw coding_exception('The required "' . $classname . '" class does not exist');
70 }
71
8f76de32 72 return $subcontext;
020cf9ae 73 }
020cf9ae 74}