SMMP/build/generic/core/View.php

117 lines
2.9 KiB
PHP
Raw Permalink Normal View History

<?php
namespace generic\core;
class View{
/* (1) Attributes
---------------------------------------------------------*/
private $core_class;
private $patch_class = [];
private $arguments;
public static $html_error = "<span class='error'>Une erreur est survenue, veuilez contacter le webmaster si cette erreur persiste.</span>";
/* (2) Instance constructor (add patches)
*
* @core_class<String> The target view class
*
---------------------------------------------------------*/
private function __construct(String $core_class){
/* (1) Get class directory & namespace */
$root_ns = str_replace('/', '\\', dirname( str_replace('\\', '/', $core_class) ) ).'\\';
$root_dir = __BUILD__.'/generic/'.dirname( str_replace('\\', '/', $core_class) );
/* (2) Get patches */
foreach( glob($root_dir.'/*.php') as $class ){
// {1} Extract basename (without '.php') //
$basename = basename($class);
$basename = substr($basename, 0, strlen($basename)-strlen('.php'));
$class_ns = $root_ns.$basename;
// {2} Ignore main (core class) //
if( $basename == 'main' )
continue;
// {3} Check if class exists //
if( !class_exists($class_ns) )
continue;
// {4} Check if instance of 'i_patch' //
if( !(new $class_ns() instanceof i_patch) )
continue;
// {5} Check if it corresponds to a warehouse's module //
if( !in_array($basename, $_SESSION['WAREHOUSE']['modules']) )
continue;
// {6} Store each patch instance //
$this->patch_class[$basename] = new $class_ns();
}
/* (3) Store core class */
$this->core_class = $core_class;
}
/* (3) Renders a view with injected data
*
* @injected_data<Array> Data to inject
*
* @return render<String> Rendered view
*
---------------------------------------------------------*/
public function render(array $injected_data=[]){
/* (1) Create core instance with data */
$view = new $this->core_class(...$injected_data);
/* (2) Patch it every @patch_class */
foreach($this->patch_class as $patch_name=>$patch_inst)
$view->patch($patch_name, $patch_inst);
/* (3) Dispatch rendering */
return $view->render();
}
/* (4) Loads a view from its path (builder)
*
* @view_path<String> View path
*
* @return view<View> View instance
* NULL on error
*
---------------------------------------------------------*/
public static function load(String $view_path){
/* (1) Check arguments
---------------------------------------------------------*/
/* (1) Check path format */
if( !preg_match('@^[\w+\.]+$@', $view_path) )
return null;
/* (2) Extract class */
$core_class = '\\view\\'.str_replace('.', '\\', $view_path).'\\main';
/* (3) Check if class exists */
if( !class_exists($core_class) )
return null;
/* (2) Return View instance
---------------------------------------------------------*/
return new self($core_class);
}
}