diff options
Diffstat (limited to 'src/web/core/component.php')
-rw-r--r-- | src/web/core/component.php | 119 |
1 files changed, 119 insertions, 0 deletions
diff --git a/src/web/core/component.php b/src/web/core/component.php new file mode 100644 index 0000000..376e24d --- /dev/null +++ b/src/web/core/component.php @@ -0,0 +1,119 @@ +<?php /* Copyright (c) 2024 Freya Murphy */ + +/** + * Gives access to imporant + * needed utility functions for + * accessing everything else! + */ +abstract class Component extends Core { + + // keep track of what has been loaded + private static array $loaded = array(); + +// ============================= LOADABLE OBJECTS == + + /** + * Loads a $type of object from a $dir with a given $name + * @param string $name - the name of the object to load + * @param string $dir - the directory theese objects are stored in + * @param string $type - the type of the object + */ + private function load_type($name, $dir, $type): object|NULL + { + + $path = $dir . '/' . $name . '.php'; + + // dont reload an ohject + if (array_key_exists($path, Component::$loaded)) + return Component::$loaded[$path]; + + // only load a object if it exists + if (!file_exists($path)) + return NULL; + + + $parts = explode('/', $name); + $part = end($parts); + $class = ucfirst($part) . '_' . $type; + require($path); + + $ref = NULL; + try { + $ref = new ReflectionClass($class); + } catch (Exception $_e) {} + + if ($ref === NULL) + return NULL; + + $obj = $ref->newInstance(); + Component::$loaded[$path] = $obj; + + return $obj; + } + + /** + * Loads a model + * @param string $name - the name of the model to load + */ + protected function load_model($name): Model|NULL + { + $dir = WEB_ROOT . '/_model'; + return $this->load_type($name, $dir, 'model'); + } + + /** + * Loads a controller + * @param string $name - the name of the controller to load + */ + public function load_controller($name): Controller|NULL + { + $dir = WEB_ROOT . '/_controller'; + return $this->load_type($name, $dir, 'controller'); + } + +// ========================================= LANG == + + /** + * Loads a php lang file into the lang array + */ + private static function load_lang_file(string $file): void + { + $lang = $GLOBALS['__lang']; + require($file); + $GLOBALS['__lang'] = $lang; + } + + /** + * Loads each php file lang strings in a directory + */ + private static function load_lang_dir(string $dir): void + { + if ($handle = opendir($dir)) { + while (false !== ($entry = readdir($handle))) { + if ($entry === '.' || $entry === '..') + continue; + Component::load_lang_file($entry); + } + } + } + + /** + * Loads the given common lang + */ + protected static function load_lang(string ...$langs): void + { + $root = WEB_ROOT . '/lang'; + + foreach ($langs as $lang) { + $file = "{$root}/{$lang}.php"; + $dir = "{$root}/{$lang}"; + + if (file_exists($file)) + Component::load_lang_file($file); + else if (is_dir($dir)) + Component::load_lang_dir($dir); + + } + } + +} |