ptut-vhost/build/api/core/Config.php

138 lines
3.0 KiB
PHP
Raw Permalink Normal View History

2018-02-17 17:18:58 +00:00
<?php
namespace api\core;
use \error\core\Error;
use \error\core\Err;
class Config{
/* (1) Attributes
---------------------------------------------------------*/
/* (1) Static */
private static $inst = null; // singleton instance
private static function config_path(){ return __ROOT__.'/config/modules.json'; }
public static $allowed_http_methods = [ "GET", "POST", "PUT", "DELETE" ];
/* (2) Instance */
private $raw;
public $index;
public $error;
/* (2) Private constructor
*
* @path<String> Configuration path
*
---------------------------------------------------------*/
private function __construct($path=null){
// Set default error
$this->error = new Error(Err::Success);
/* (1) Access file content
---------------------------------------------------------*/ {
/* (1) Vérification existence fichier config */
if( !file_exists($path) )
return $this->error->set(Err::UnreachableResource);
/* (2) Lecture fichier config */
$conf = @file_get_contents($path);
/* (3) Si erreur lecture */
if( $conf === false )
return $this->error->set(Err::UnreachableResource);
/* (4) Parsage json */
$this->raw = json_decode( $conf, true );
/* (5) Gestion de l'erreur de parsage */
if( $this->raw == null )
return $this->error->set(Err::ParsingFailed, 'json');
}
/* (2) Construction de l'index des chemins
---------------------------------------------------------*/ {
/* (1) Initialisation */
$this->index = [];
$ref = [ '/' => array_merge($this->raw) ];
/* (2) Tant qu'il reste des @ref à traiter */
while( count($ref) > 0 ){
/* (2.1) For each ref */
foreach($ref as $ref_path=>$ref_children){
/* (2.2) For each children */
foreach($ref_children as $path=>$method_or_subpath){
/* (2.2.1) If is an HTTP method -> add to index */
if( in_array($path, self::$allowed_http_methods) ){
/* (2.2.1.1) If no index for this path -> add it */
if( !isset($this->index[$ref_path]) )
$this->index[$ref_path] = [];
/* (2.2.1.2) Add the HTTP method definition */
$this->index[$ref_path][$path] = $method_or_subpath;
/* (2.2.2) If a sub path -> add it to next refs to process */
}else{
if( $ref_path == '/' )
$ref["$ref_path$path"] = $method_or_subpath;
else
$ref["$ref_path/$path"] = $method_or_subpath;
}
}
/* (2.3) In all cases -> remove current from ref */
unset($ref[$ref_path]);
}
}
}
}
/* (3) Static singleton 'get-or-create'
*
* @return inst<Config> Configuration singleton
*
---------------------------------------------------------*/
public static function get(){
/* (1) If @inst already exists -> return singleton */
if( self::$inst instanceof Config )
return self::$inst;
/* (2) If @inst not set -> create singleton and return it */
self::$inst = new self( self::config_path() );
return self::$inst;
}
}