diff --git a/src/main/php/web/Environment.class.php b/src/main/php/web/Environment.class.php index 693bd422..6268f2bd 100755 --- a/src/main/php/web/Environment.class.php +++ b/src/main/php/web/Environment.class.php @@ -87,10 +87,11 @@ public function variable($name) { * Gets properties * * @param string $name + * @param bool $optional Whether to return or throw if properties aren't found. * @return util.PropertyAccess * @throws lang.ElementNotFoundException */ - public function properties($name) { + public function properties($name, $optional= false) { $expand= function($name) { return $this->{$name}(); }; $found= []; foreach ($this->sources as $source) { @@ -99,15 +100,20 @@ public function properties($name) { } } - switch (sizeof($found)) { - case 1: return $found[0]; - case 0: throw new ElementNotFoundException(sprintf( - 'Cannot find properties "%s" in any of %s', - $name, - Objects::stringOf($this->sources) - )); - default: return new CompositeProperties($found); + $n= sizeof($found); + if ($n > 1) { + return new CompositeProperties($found); + } else if (1 === $n) { + return $found[0]; + } else if ($optional) { + return null; } + + throw new ElementNotFoundException(sprintf( + 'Cannot find properties "%s" in any of %s', + $name, + Objects::stringOf($this->sources) + )); } /** @return string[] */ diff --git a/src/test/php/web/unittest/EnvironmentTest.class.php b/src/test/php/web/unittest/EnvironmentTest.class.php index 500021ca..a5901daa 100755 --- a/src/test/php/web/unittest/EnvironmentTest.class.php +++ b/src/test/php/web/unittest/EnvironmentTest.class.php @@ -91,10 +91,15 @@ public function non_existant_properties() { } #[Test] - public function properties() { + public function optional_non_existant_properties() { + $this->assertNull((new Environment('dev', '.', 'static', []))->properties('inject', true)); + } + + #[Test, Values([true, false])] + public function properties($optional) { $prop= new Properties('inject.ini'); $environment= new Environment('dev', '.', 'static', [new RegisteredPropertySource('inject', $prop)]); - $this->assertEquals($prop, $environment->properties('inject')); + $this->assertEquals($prop, $environment->properties('inject', $optional)); } #[Test]