<?php
namespace Lia\Utility;
/**
* For working with namespaces
*/
class NS {
/**
*
* @param &$inputName the input value to parse AND will be set to name without namespace
* @param &$namespace variable to set namespace to
* @param &$fullyQualifiedName variable to set fully qualified name to. Always contains a colon, even if namespace is empty
*/
static public function parseNamespace(&$inputName,&$namespace,&$fullyQualifiedName=null){
$fullyQualifiedName = $inputName;
$parts = explode(':',$inputName);
if (count($parts)>1)$namespace = array_shift($parts);
else $namespace = false;
$unqualifiedName = implode(':', $parts);
$inputName = $unqualifiedName;
if (strlen($namespace)==0){
$namespace = false;
}
$fullyQualifiedName = $namespace.':'.$unqualifiedName;
}
/**
* Get a value from a namespaced array
*
* @param $data your array of data
* @param $name the name to retrieve, namespace may be included here
* @param &$namespace sets to the namespace in name
*/
static public function get(array $data, $name, &$namespace=null){
\Lia\Utility\NS::parseNamespace($name, $namespace);
// $keys = ;
// if (in_array(false, $keys))
if ($namespace==false
&&!in_array(false, array_keys($data[$name]))){
$value = array_values(($data[$name]??[]))[0] ?? null;
} else {
$value = $data[$name][$namespace] ?? null;
}
return $value;
}
/**
* Set a value to your namespaced array.
*
* @param &$data your array of data
* @param $fqn The fully qualified name to set. Namespace is optional & recommended.
* @param $value the value to set
* @return void
*/
static public function set(array &$data, string $fqn, $value){
$name = $fqn;
\Lia\Utility\NS::parseNamespace($name, $namespace);
$data[$name][$namespace] = $value;
}
/**
*
*
*/
static public function unset(array &$data, string $fqn){
$name = $fqn;
static::parseNamespace($name,$namespace);
unset($data[$name][$namespace]);
}
/**
* Check if the fully-qualified-name is set
* @param &$data your array of data
* @param $fqn `namespace:the.name`, namespace optional.
* @return true/false
*/
static public function has(array &$data, string $fqn){
$name = $fqn;
static::parseNamespace($name, $namespace);
if (!array_key_exists($name, $data))return false;
if ($namespace===false){
return in_array($namespace, array_keys($data[$name]));
} else if (array_key_exists($namespace,$data[$name])){
return true;
}
return false;
}
/**
* Check if the namespace has been set
* @param &$data your array of data
* @param $fqnOrNamespace `namespace` or `namespace:some.name` or `:some.name`/`` to check no namespace.
*/
static public function hasNamespace(array &$data, string $fqnOrNamespace){
$fqnOrNamespace .= ':';
$ns = static::parseNamespace($fqnOrNamespace, $ns);
foreach ($data as $name=>$value){
if (array_key_exists($ns, $name))return true;
}
return false;
}
}