Skip to content

Commit

Permalink
Add ability to check for non-existant properties without using except…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
thekid committed Nov 2, 2022
1 parent 64d7e47 commit 04b9dab
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
24 changes: 15 additions & 9 deletions src/main/php/web/Environment.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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[] */
Expand Down
9 changes: 7 additions & 2 deletions src/test/php/web/unittest/EnvironmentTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 04b9dab

Please sign in to comment.