You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
105 lines
2.9 KiB
PHP
105 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace jrosset\EnvReader;
|
|
|
|
use jrosset\ArrayClasses\IArrayCast;
|
|
use jrosset\ArrayClasses\IArrayClass;
|
|
use jrosset\ArrayClasses\ImmutableArrayClass;
|
|
use UnexpectedValueException;
|
|
|
|
/**
|
|
* Trait for multi-level properties
|
|
*/
|
|
trait TMultiLevelProperties {
|
|
/**
|
|
* Check if a property id defined
|
|
*
|
|
* @param string|string[]|IArrayCast $name The property name
|
|
*
|
|
* @return bool Is the property defined ?
|
|
*/
|
|
public function hasProperty ($name): bool {
|
|
$levels = $this->getPropertyLevels($name);
|
|
|
|
$value = $this->getProperties();
|
|
foreach ($levels as $level) {
|
|
if ($value instanceof IArrayClass) {
|
|
if (!$value->has($level)) {
|
|
return false;
|
|
}
|
|
$value = $value->get($level);
|
|
}
|
|
else {
|
|
if (!isset($value[$level])) {
|
|
return false;
|
|
}
|
|
$value = $value[$level];
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
/**
|
|
* Get a property value
|
|
*
|
|
* @param string|string[]|IArrayCast $name The property name
|
|
* @param mixed $default The default value if property is not set
|
|
* Raise an exception if property is not set AND $default is Null
|
|
*
|
|
* @return mixed The property value
|
|
*
|
|
* @throws UnexpectedValueException If property is not set AND $default is Null
|
|
*/
|
|
public function getProperty ($name, $default = null) {
|
|
if (!$this->hasProperty($name)) {
|
|
if ($default === null) {
|
|
throw new UnexpectedValueException('The "' . $name . '" property is not set');
|
|
}
|
|
return $default;
|
|
}
|
|
|
|
$levels = $this->getPropertyLevels($name);
|
|
|
|
$value = $this->getProperties();
|
|
foreach ($levels as $level) {
|
|
if ($value instanceof IArrayClass) {
|
|
$value = $value->get($level);
|
|
}
|
|
else {
|
|
$value = $value[$level];
|
|
}
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/**
|
|
* Provide the multi-level separator
|
|
*
|
|
* Reimplements to override
|
|
*
|
|
* @return string The separator
|
|
*/
|
|
protected function getPropertySeparator (): string {
|
|
return '/';
|
|
}
|
|
/**
|
|
* Get array of levels of a property name
|
|
*
|
|
* @param string|string[]|IArrayCast $propertyName The property name
|
|
*
|
|
* @return ImmutableArrayClass The property levels
|
|
*/
|
|
private function getPropertyLevels ($propertyName): ImmutableArrayClass {
|
|
if ($propertyName instanceof IArrayCast) {
|
|
$parts = $propertyName->toArray();
|
|
}
|
|
elseif (is_array($propertyName)) {
|
|
$parts = $propertyName;
|
|
}
|
|
else {
|
|
$parts = explode($this->getPropertySeparator(), $propertyName);
|
|
}
|
|
return new ImmutableArrayClass($parts);
|
|
}
|
|
} |