TMultiLevelProperties: allow array as property name

2.x 2.1.1
Julien Rosset 3 years ago
parent 55e1bc70d7
commit 402b891552

@ -2,6 +2,7 @@
namespace jrosset\EnvReader;
use jrosset\ArrayClasses\IArrayCast;
use jrosset\ArrayClasses\IArrayClass;
use jrosset\ArrayClasses\ImmutableArrayClass;
use UnexpectedValueException;
@ -11,9 +12,13 @@ use UnexpectedValueException;
*/
trait TMultiLevelProperties {
/**
* @inheritDoc
* Check if a property id defined
*
* @param string|string[]|IArrayCast $name The property name
*
* @return bool Is the property defined ?
*/
public function hasProperty (string $name): bool {
public function hasProperty ($name): bool {
$levels = $this->getPropertyLevels($name);
$value = $this->getProperties();
@ -35,9 +40,17 @@ trait TMultiLevelProperties {
return true;
}
/**
* @inheritDoc
* 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 (string $name, $default = null) {
public function getProperty ($name, $default = null) {
if (!$this->hasProperty($name)) {
if ($default === null) {
throw new UnexpectedValueException('The "' . $name . '" property is not set');
@ -59,6 +72,7 @@ trait TMultiLevelProperties {
return $value;
}
/**
* Provide the multi-level separator
*
@ -72,11 +86,20 @@ trait TMultiLevelProperties {
/**
* Get array of levels of a property name
*
* @param string $propertyName The property name
* @param string|string[]|IArrayCast $propertyName The property name
*
* @return ImmutableArrayClass The property levels
*/
private function getPropertyLevels (string $propertyName): ImmutableArrayClass {
return new ImmutableArrayClass(explode($this->getPropertySeparator(), $propertyName));
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);
}
}
Loading…
Cancel
Save