From 402b891552e49ee8895b00c287b453e63ea72296 Mon Sep 17 00:00:00 2001 From: Julien Rosset Date: Thu, 20 Oct 2022 09:46:20 +0200 Subject: [PATCH] TMultiLevelProperties: allow array as property name --- src/EnvReader/TMultiLevelProperties.php | 37 ++++++++++++++++++++----- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/src/EnvReader/TMultiLevelProperties.php b/src/EnvReader/TMultiLevelProperties.php index 5a0ad2e..5cb1b41 100644 --- a/src/EnvReader/TMultiLevelProperties.php +++ b/src/EnvReader/TMultiLevelProperties.php @@ -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); } } \ No newline at end of file