<?php
namespace ROF;
class Resource {
static protected $files = [];
static protected $info = [];
static protected $scopes = [];
static public function init(...$filePaths){
static::$info['get'] = $_GET;
static::$info['post'] = $_POST;
static::$files = array_merge(static::$files,$filePaths);
static::processFiles(...$filePaths);
}
static public function all(){
return static::$info;
}
static public function getResource($lookupKey='',$callingFile=NULL,$callingFunction=NULL,$newValue=NULL){
if ($newValue!==NULL){
$this->setNewValue($lookupKey,$callingFile,$callingFunction,$newValue);
$parts = explode($lookupKey);
$newValue
static::$info = array_replace_recursive(static::$info,$json);
}
if ($callingFile!=NULL){
$scope = $callingFunction.':_:'.$callingFile;
if (isset(static::$scopes[$scope])){
$lookupKey = static::$scopes[$scope].'.'.$lookupKey;
}
}
$parts = explode('.',$lookupKey);
$value = static::$info;
$throw = FALSE;
$lastPart = NULL;
foreach ($parts as $part){
$value = \ROF\Resource\Deriver::derive($lastPart,$value,$lookupKey);
if (!isset($value[$part])&&!isset($value[strtolower($part)])
&&$part!=''
&&$part!=NULL){
throw new \Exception("A resource is not saved for part '{$part}' in lookup key '{$lookupKey}'");
}
$value = $value[$part] ?? $value[strtolower($part)] ?? $value;
if (!\ROF\Resource\TypeValidator::isValid($lastPart,$value)){
\ROF\Resource\TypeValidator::throwMismatchError($lookupKey,$lastPart,$part,$value);
}
if (!\ROF\Resource\KeyValidator::isValid($lastPart,$part)){
\ROF\Resource\KeyValidator::throwKeyError($lookupKey,$lastPart,$part,$value);
}
$lastPart = $part;
}
return $value;
}
static public function setScopedNamespace($callingFile,$callingFunction,$namespaceName){
$scope = $callingFunction.':_:'.$callingFile;
static::$scopes[$scope] = $namespaceName;
if ($namespaceName==NULL){
unset(static::$scopes[$scope]);
}
}
static protected function processFiles(...$files){
foreach ($files as $filePath){
static::processFile($filePath);
}
}
static protected function processDirectory($filePath){
throw new \Exception("Sorry, we don't process directories yet. File at '{$filePath}' is a directory");
}
static protected function processFile($filePath){
if (!is_file($filePath)){
throw new \Exception("File at \'{$filePath}\' does not exist");
} else if (is_dir($filePath)){
static::processDirectory($filePath);
return;
}
$content = file_get_contents($filePath);
$json = json_decode($content,TRUE);
if (!is_array($json)){
throw new \Exception("There was an error processing the json in file \'{$filePath}\'");
}
static::$info = array_replace_recursive(static::$info,$json);
}
}
require_once(__DIR__.'/R_funcs.php');