Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
namespace core\navigation\output;
18
 
19
use ReflectionMethod;
20
 
21
/**
22
 * Primary navigation renderable test
23
 *
24
 * @package     core
25
 * @category    navigation
26
 * @copyright   2021 onwards Peter Dias
27
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
29
class primary_test extends \advanced_testcase {
30
    /**
31
     * Basic setup to make sure the nav objects gets generated without any issues.
32
     */
33
    public function setUp(): void {
34
        global $PAGE;
35
        $this->resetAfterTest();
36
        $pagecourse = $this->getDataGenerator()->create_course();
37
        $assign = $this->getDataGenerator()->create_module('assign', ['course' => $pagecourse->id]);
38
        $cm = get_coursemodule_from_id('assign', $assign->cmid);
39
        $contextrecord = \context_module::instance($cm->id);
40
        $pageurl = new \moodle_url('/mod/assign/view.php', ['id' => $cm->instance]);
41
        $PAGE->set_cm($cm);
42
        $PAGE->set_url($pageurl);
43
        $PAGE->set_course($pagecourse);
44
        $PAGE->set_context($contextrecord);
45
    }
46
 
47
    /**
48
     * Test the primary export to confirm we are getting the nodes
49
     *
50
     * @dataProvider primary_export_provider
51
     * @param bool $withcustom Setup with custom menu
52
     * @param bool $withlang Setup with langs
53
     * @param string $userloggedin The type of user ('admin' or 'guest') if creating setup with logged in user,
54
     *                             otherwise consider the user as non-logged in
55
     * @param array $expecteditems An array of nodes expected with content in them.
56
     */
57
    public function test_primary_export(bool $withcustom, bool $withlang, string $userloggedin, array $expecteditems) {
58
        global $PAGE, $CFG;
59
        if ($withcustom) {
60
            $CFG->custommenuitems = "Course search|/course/search.php
61
                Google|https://google.com.au/
62
                Netflix|https://netflix.com/au";
63
        }
64
        if ($userloggedin === 'admin') {
65
            $this->setAdminUser();
66
        } else if ($userloggedin === 'guest') {
67
            $this->setGuestUser();
68
        } else {
69
            $this->setUser(0);
70
        }
71
 
72
        // Mimic multiple langs installed. To trigger responses 'get_list_of_translations'.
73
        // Note: The text/title of the nodes generated will be 'English(fr), English(de)' but we don't care about this.
74
        // We are testing whether the nodes gets generated when the lang menu is available.
75
        if ($withlang) {
76
            mkdir("$CFG->dataroot/lang/de", 0777, true);
77
            mkdir("$CFG->dataroot/lang/fr", 0777, true);
78
            // Ensure the new langs are picked up and not taken from the cache.
79
            $stringmanager = get_string_manager();
80
            $stringmanager->reset_caches(true);
81
        }
82
 
83
        $primary = new primary($PAGE);
84
        $renderer = $PAGE->get_renderer('core');
85
        $data = array_filter($primary->export_for_template($renderer));
86
 
87
        // Assert that the number of returned menu items equals the expected result.
88
        $this->assertCount(count($expecteditems), $data);
89
        // Assert that returned menu items match the expected items.
90
        foreach ($data as $menutype => $value) {
91
            $this->assertTrue(in_array($menutype, $expecteditems));
92
        }
93
        // When the user is logged in (excluding guest access), assert that lang menu is included as a part of the
94
        // user menu when multiple languages are installed.
95
        if (isloggedin() && !isguestuser()) {
96
            // Look for a language menu item within the user menu items.
97
            $usermenulang = array_filter($data['user']['items'], function($usermenuitem) {
98
                return $usermenuitem->itemtype !== 'divider' && $usermenuitem->title === get_string('language');
99
            });
100
            if ($withlang) { // If multiple languages are installed.
101
                // Assert that the language menu exists within the user menu.
102
                $this->assertNotEmpty($usermenulang);
103
            } else { // If the aren't any additional installed languages.
104
                $this->assertEmpty($usermenulang);
105
            }
106
        } else { // Otherwise assert that the user menu does not contain any items.
107
            $this->assertArrayNotHasKey('items', $data['user']);
108
        }
109
    }
110
 
111
    /**
112
     * Provider for the test_primary_export function.
113
     *
114
     * @return array
115
     */
116
    public function primary_export_provider(): array {
117
        return [
118
            "Export the menu data when: custom menu exists; multiple langs installed; user is not logged in." => [
119
                true, true, '', ['mobileprimarynav', 'moremenu', 'lang', 'user']
120
            ],
121
            "Export the menu data when: custom menu exists; langs not installed; user is not logged in." => [
122
                true, false, '', ['mobileprimarynav', 'moremenu', 'user']
123
            ],
124
            "Export the menu data when: custom menu exists; multiple langs installed; logged in as admin." => [
125
                true, true, 'admin', ['mobileprimarynav', 'moremenu', 'user']
126
            ],
127
            "Export the menu data when: custom menu exists; langs not installed; logged in as admin." => [
128
                true, false, 'admin', ['mobileprimarynav', 'moremenu', 'user']
129
            ],
130
            "Export the menu data when: custom menu exists; multiple langs installed; logged in as guest." => [
131
                true, true, 'guest', ['mobileprimarynav', 'moremenu', 'lang', 'user']
132
            ],
133
            "Export the menu data when: custom menu exists; langs not installed; logged in as guest." => [
134
                true, false, 'guest', ['mobileprimarynav', 'moremenu', 'user']
135
            ],
136
            "Export the menu data when: custom menu does not exist; multiple langs installed; logged in as guest." => [
137
                false, true, 'guest', ['mobileprimarynav', 'moremenu', 'lang', 'user']
138
            ],
139
            "Export the menu data when: custom menu does not exist; multiple langs installed; logged in as admin." => [
140
                false, true, 'admin', ['mobileprimarynav', 'moremenu', 'user']
141
            ],
142
            "Export the menu data when: custom menu does not exist; langs not installed; user is not logged in." => [
143
                false, false, '', ['mobileprimarynav', 'moremenu', 'user']
144
            ],
145
        ];
146
    }
147
 
148
    /**
149
     * Test the custom menu getter to confirm the nodes gets generated and are returned correctly.
150
     *
151
     * @dataProvider custom_menu_provider
152
     * @param string $config
153
     * @param array $expected
154
     */
155
    public function test_get_custom_menu(string $config, array $expected) {
156
        $actual = $this->get_custom_menu($config);
157
        $this->assertEquals($expected, $actual);
158
    }
159
 
160
    /**
161
     * Helper method to get the template data for the custommenuitem that is set here via parameter.
162
     * @param string $config
163
     * @return array
164
     * @throws \ReflectionException
165
     */
166
    protected function get_custom_menu(string $config): array {
167
        global $CFG, $PAGE;
168
        $CFG->custommenuitems = $config;
169
        $output = new primary($PAGE);
170
        $method = new ReflectionMethod('core\navigation\output\primary', 'get_custom_menu');
171
        $renderer = $PAGE->get_renderer('core');
172
 
173
        // We can't assert the value of each menuitem "moremenuid" property (because it's random).
174
        $custommenufilter = static function(array $custommenu) use (&$custommenufilter): void {
175
            foreach ($custommenu as $menuitem) {
176
                unset($menuitem->moremenuid);
177
                // Recursively move through child items.
178
                $custommenufilter($menuitem->children);
179
            }
180
        };
181
 
182
        $actual = $method->invoke($output, $renderer);
183
        $custommenufilter($actual);
184
        return $actual;
185
    }
186
 
187
    /**
188
     * Provider for test_get_custom_menu
189
     *
190
     * @return array
191
     */
192
    public function custom_menu_provider(): array {
193
        return [
194
            'Simple custom menu' => [
195
                "Course search|/course/search.php
196
                Google|https://google.com.au/
197
                Netflix|https://netflix.com/au", [
198
                    (object) [
199
                        'text' => 'Course search',
200
                        'url' => 'https://www.example.com/moodle/course/search.php',
201
                        'title' => '',
202
                        'sort' => 1,
203
                        'children' => [],
204
                        'haschildren' => false,
205
                    ],
206
                    (object) [
207
                        'text' => 'Google',
208
                        'url' => 'https://google.com.au/',
209
                        'title' => '',
210
                        'sort' => 2,
211
                        'children' => [],
212
                        'haschildren' => false,
213
                    ],
214
                    (object) [
215
                        'text' => 'Netflix',
216
                        'url' => 'https://netflix.com/au',
217
                        'title' => '',
218
                        'sort' => 3,
219
                        'children' => [],
220
                        'haschildren' => false,
221
                    ],
222
                ]
223
            ],
224
            'Complex, nested custom menu' => [
225
                "Moodle community|http://moodle.org
226
                -Moodle free support|http://moodle.org/support
227
                -Moodle development|http://moodle.org/development
228
                --Moodle Tracker|http://tracker.moodle.org
229
                --Moodle Docs|https://docs.moodle.org
230
                -Moodle News|http://moodle.org/news
231
                Moodle company
232
                -Moodle commercial hosting|http://moodle.com/hosting
233
                -Moodle commercial support|http://moodle.com/support", [
234
                    (object) [
235
                        'text' => 'Moodle community',
236
                        'url' => 'http://moodle.org',
237
                        'title' => '',
238
                        'sort' => 1,
239
                        'children' => [
240
                            (object) [
241
                                'text' => 'Moodle free support',
242
                                'url' => 'http://moodle.org/support',
243
                                'title' => '',
244
                                'sort' => 2,
245
                                'children' => [],
246
                                'haschildren' => false,
247
                            ],
248
                            (object) [
249
                                'text' => 'Moodle development',
250
                                'url' => 'http://moodle.org/development',
251
                                'title' => '',
252
                                'sort' => 3,
253
                                'children' => [
254
                                    (object) [
255
                                        'text' => 'Moodle Tracker',
256
                                        'url' => 'http://tracker.moodle.org',
257
                                        'title' => '',
258
                                        'sort' => 4,
259
                                        'children' => [],
260
                                        'haschildren' => false,
261
                                    ],
262
                                    (object) [
263
                                        'text' => 'Moodle Docs',
264
                                        'url' => 'https://docs.moodle.org',
265
                                        'title' => '',
266
                                        'sort' => 5,
267
                                        'children' => [],
268
                                        'haschildren' => false,
269
                                    ],
270
                                ],
271
                                'haschildren' => true,
272
                            ],
273
                            (object) [
274
                                'text' => 'Moodle News',
275
                                'url' => 'http://moodle.org/news',
276
                                'title' => '',
277
                                'sort' => 6,
278
                                'children' => [],
279
                                'haschildren' => false,
280
                            ],
281
                        ],
282
                        'haschildren' => true,
283
                    ],
284
                    (object) [
285
                        'text' => 'Moodle company',
286
                        'url' => null,
287
                        'title' => '',
288
                        'sort' => 7,
289
                        'children' => [
290
                            (object) [
291
                                'text' => 'Moodle commercial hosting',
292
                                'url' => 'http://moodle.com/hosting',
293
                                'title' => '',
294
                                'sort' => 8,
295
                                'children' => [],
296
                                'haschildren' => false,
297
                            ],
298
                            (object) [
299
                                'text' => 'Moodle commercial support',
300
                                'url' => 'http://moodle.com/support',
301
                                'title' => '',
302
                                'sort' => 9,
303
                                'children' => [],
304
                                'haschildren' => false,
305
                            ],
306
                        ],
307
                        'haschildren' => true,
308
                    ],
309
                ]
310
            ]
311
        ];
312
    }
313
 
314
    /**
315
     * Test the merge_primary_and_custom and the eval_is_active method. Merge  primary and custom menu with different
316
     * page urls and check that the correct nodes are active and open, depending on the data for each menu.
317
     *
318
     * @covers \core\navigation\output\primary::merge_primary_and_custom
319
     * @covers \core\navigation\output\primary::flag_active_nodes
320
     * @return void
321
     * @throws \ReflectionException
322
     * @throws \moodle_exception
323
     */
324
    public function test_merge_primary_and_custom() {
325
        global $PAGE;
326
 
327
        $menu = $this->merge_and_render_menus();
328
 
329
        $this->assertEquals(4, count(\array_keys($menu)));
330
        $msg = 'No active nodes for page ' . $PAGE->url;
331
        $this->assertEmpty($this->get_menu_item_names_by_type($menu, 'isactive'), $msg);
332
        $this->assertEmpty($this->get_menu_item_names_by_type($menu, 'isopen'), str_replace('active', 'open', $msg));
333
 
334
        $msg = 'Active nodes desktop for /course/search.php';
335
        $menu = $this->merge_and_render_menus('/course/search.php');
336
        $isactive = $this->get_menu_item_names_by_type($menu, 'isactive');
337
        $this->assertEquals(['Courses', 'Course search'], $isactive, $msg);
338
        $this->assertEmpty($this->get_menu_item_names_by_type($menu, 'isopem'), str_replace('Active', 'Open', $msg));
339
 
340
        $msg = 'Active nodes mobile for /course/search.php';
341
        $menu = $this->merge_and_render_menus('/course/search.php', true);
342
        $isactive = $this->get_menu_item_names_by_type($menu, 'isactive');
343
        $this->assertEquals(['Course search'], $isactive, $msg);
344
        $isopen = $this->get_menu_item_names_by_type($menu, 'isopen');
345
        $this->assertEquals(['Courses'], $isopen, str_replace('Active', 'Open', $msg));
346
 
347
        $msg = 'Active nodes desktop for /course/search.php?areaids=core_course-course&q=test';
348
        $menu = $this->merge_and_render_menus('/course/search.php?areaids=core_course-course&q=test');
349
        $isactive = $this->get_menu_item_names_by_type($menu, 'isactive');
350
        $this->assertEquals(['Courses', 'Course search'], $isactive, $msg);
351
 
352
        $msg = 'Active nodes desktop for /?theme=boost';
353
        $menu = $this->merge_and_render_menus('/?theme=boost');
354
        $isactive = $this->get_menu_item_names_by_type($menu, 'isactive');
355
        $this->assertEquals(['Theme', 'Boost'], $isactive, $msg);
356
    }
357
 
358
    /**
359
     * Internal function to get an array of top menu items from the primary and the custom menu. The latter is defined
360
     * in this function.
361
     * @param string|null $url
362
     * @param bool|null $ismobile
363
     * @return array
364
     * @throws \ReflectionException
365
     * @throws \coding_exception
366
     */
367
    protected function merge_and_render_menus(?string $url = null, ?bool $ismobile = false): array {
368
        global $PAGE, $FULLME;
369
 
370
        if ($url !== null) {
371
            $PAGE->set_url($url);
372
            $FULLME = $PAGE->url->out();
373
        }
374
        $primary = new primary($PAGE);
375
 
376
        $method = new ReflectionMethod('core\navigation\output\primary', 'get_primary_nav');
377
        $dataprimary = $method->invoke($primary);
378
 
379
        // Take this custom menu that would come from the  setting custommenitems.
380
        $custommenuitems = <<< ENDMENU
381
        Theme
382
        -Boost|/?theme=boost
383
        -Classic|/?theme=classic
384
        -Purge Cache|/admin/purgecaches.php
385
        Courses
386
        -All courses|/course/
387
        -Course search|/course/search.php
388
        -###
389
        -FAQ|https://example.org/faq
390
        -My Important Course|/course/view.php?id=4
391
        Mobile app|https://example.org/app|Download our app
392
        ENDMENU;
393
 
394
        $datacustom = $this->get_custom_menu($custommenuitems);
395
        $method = new ReflectionMethod('core\navigation\output\primary', 'merge_primary_and_custom');
396
        $menucomplete = $method->invoke($primary, $dataprimary, $datacustom, $ismobile);
397
        return $menucomplete;
398
    }
399
 
400
    /**
401
     * Traverse the menu array structure (all nodes recursively) and fetch the node texts from the menu nodes that are
402
     * active/open (determined via param $nodetype that can be "inactive" or "isopen"). The returned array contains a
403
     * list of nade names that match this criterion.
404
     * @param array $menu
405
     * @param string $nodetype
406
     * @return array
407
     */
408
    protected function get_menu_item_names_by_type(array $menu, string $nodetype): array {
409
        $matchednodes = [];
410
        foreach ($menu as $menuitem) {
411
            // Either the node is an array.
412
            if (is_array($menuitem)) {
413
                if ($menuitem[$nodetype] ?? false) {
414
                    $matchednodes[] = $menuitem['text'];
415
                }
416
                // Recursively move through child items.
417
                if (array_key_exists('children', $menuitem) && count($menuitem['children'])) {
418
                    $matchednodes = array_merge($matchednodes, $this->get_menu_item_names_by_type($menuitem['children'], $nodetype));
419
                }
420
            } else {
421
                // Otherwise the node is a standard object.
422
                if (isset($menuitem->{$nodetype}) && $menuitem->{$nodetype} === true) {
423
                    $matchednodes[] = $menuitem->text;
424
                }
425
                // Recursively move through child items.
426
                if (isset($menuitem->children) && is_array($menuitem->children) && !empty($menuitem->children)) {
427
                    $matchednodes = array_merge($matchednodes, $this->get_menu_item_names_by_type($menuitem->children, $nodetype));
428
                }
429
            }
430
        }
431
        return $matchednodes;
432
    }
433
}