* @copyright Copyright (c) 2013 - 2019, TechFuze. (http://techfuze.net) */ class Helpers { use ComponentPathsTrait; /** * Array of loadedHelpers, so that they won't be reloaded * * @var array Array of loaded helperNames */ protected array $helpers = []; /** * Load a helper. * * Supply the name and the helper will be loaded from the supplied directory, * or from one of the helperPaths (which you can add). * * @param string $helperName Name of the helper * @param array $helperPaths * @return bool Whether the helper was successfully loaded (true if yes) * @throws HelperException */ public function load(string $helperName, array $helperPaths = []): bool { // Determine what directories should be checked $helperPaths = (empty($helperPaths) ? $this->componentPaths : [3 => $helperPaths]); // Check it is already loaded if (isset($this->helpers[$helperName])) { Logger::log("Helper '".$helperName."' is already loaded. Skipping"); return false; } /** @var HelperLoadEvent $event */ try { $event = Events::fireEvent('helperLoadEvent', $helperName, $helperPaths); // @codeCoverageIgnoreStart } catch (EventException $e) { throw new HelperException("Could not load helper. helperLoadEvent failed: '" . $e->getMessage() . "''"); // @codeCoverageIgnoreEnd } // If cancelled by event, abort loading helper if ($event->isCancelled()) { Logger::log("Not loading helper. Aborted by event"); return false; } // Iterate over helperPaths and attempt to load if helper exists for ($i=Priority::getHighestPriority(); $i<=Priority::getLowestPriority(); $i++) { if (!isset($event->helperPaths[$i])) continue; foreach ($event->helperPaths[$i] as $helperPath) { $file = $helperPath . DS . $event->helperName . '.php'; $subfile = $helperPath . DS . $event->helperName . DS . $event->helperName . '.php'; if (file_exists($file)) { // Load and register include_once($file); $this->helpers[$event->helperName] = true; Logger::log("Loaded helper '".$event->helperName."'"); return true; } // If php file not in main directory, check subdirectories elseif (file_exists($subfile)) { // Load and register include_once($subfile); $this->helpers[$event->helperName] = true; Logger::log("Loaded helper '".$event->helperName."''"); return true; } } } throw new HelperException("Could not load helper. Helper not found.", 1); } /** * Alias for load * @param string $helperName Name of the helper * @param array $helperPaths * @return bool Whether the helper was successfully loaded (true if yes) * @throws HelperException *@see load() for more details * */ public function get(string $helperName, array $helperPaths = []): bool { return $this->load($helperName, $helperPaths); } }