Merge branch 'MDL-62899-search-icons-master' of https://github.com/dmitriim/moodle
[moodle.git] / search / classes / document_factory.php
CommitLineData
db48207e
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/**
18 * Search documents factory.
19 *
20 * @package core_search
21 * @copyright 2015 David Monllao {@link http://www.davidmonllao.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_search;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Search document factory.
31 *
32 * @package core_search
33 * @copyright 2015 David Monllao {@link http://www.davidmonllao.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class document_factory {
37
38 /**
39 * The document class used by search engines.
40 *
41 * Defined as an array to prevent unexpected caching issues, it should only contain one search
42 * engine as only one search engine will be used during a request. This might change during
43 * testing, remember to use document_factory::clean_statics in that case.
44 *
45 * @var array
46 */
47 protected static $docclassnames = array();
48
49 /**
50 * Returns the appropiate document object as it depends on the engine.
51 *
52 * @param int $itemid Document itemid
53 * @param string $componentname Document component name
54 * @param string $areaname Document area name
55 * @param \core_search\engine $engine Falls back to the search engine in use.
56 * @return \core_search\document Base document or the engine implementation.
57 */
58 public static function instance($itemid, $componentname, $areaname, $engine = false) {
59
60 if ($engine === false) {
61 $search = \core_search\manager::instance();
62 $engine = $search->get_engine();
63 }
64
65 $pluginname = $engine->get_plugin_name();
66
67 if (!empty(self::$docclassnames[$pluginname])) {
68 return new self::$docclassnames[$pluginname]($itemid, $componentname, $areaname);
69 }
70
71 self::$docclassnames[$pluginname] = $engine->get_document_classname();
72
73 return new self::$docclassnames[$pluginname]($itemid, $componentname, $areaname);
74 }
75
76 /**
77 * Clears static vars.
78 *
79 * @return void
80 */
81 public static function clean_static() {
82 self::$docclassnames = array();
83 }
84}