diff --git a/src/Illuminate/Support/Optional.php b/src/Illuminate/Support/Optional.php index 7f7faab1ce2d..101f6a7ae530 100644 --- a/src/Illuminate/Support/Optional.php +++ b/src/Illuminate/Support/Optional.php @@ -59,6 +59,25 @@ public function __call($method, $parameters) } } + /** + * Dynamically check a property exists on the underlying object. + * + * @param $name + * @return bool + */ + public function __isset($name) + { + if (is_object($this->value)) { + return isset($this->value->{$name}); + } + + if (is_array($this->value) || $this->value instanceof \ArrayObject) { + return isset($this->value[$name]); + } + + return false; + } + /** * Determine if an item exists at an offset. * diff --git a/tests/Support/SupportOptionalTest.php b/tests/Support/SupportOptionalTest.php new file mode 100644 index 000000000000..26bdd4e32a73 --- /dev/null +++ b/tests/Support/SupportOptionalTest.php @@ -0,0 +1,91 @@ +item = $expected; + + $optional = new Optional($targetObj); + + $this->assertEquals($expected, $optional->item); + } + + public function testGetNotExistItemOnObject() + { + $targetObj = new \stdClass; + + $optional = new Optional($targetObj); + + $this->assertNull($optional->item); + } + + public function testIssetExistItemOnObject() + { + $targetObj = new \stdClass; + $targetObj->item = ''; + + $optional = new Optional($targetObj); + + $this->assertTrue(isset($optional->item)); + } + + public function testIssetNotExistItemOnObject() + { + $targetObj = new \stdClass; + + $optional = new Optional($targetObj); + + $this->assertFalse(isset($optional->item)); + } + + public function testGetExistItemOnArray() + { + $expected = 'test'; + + $targetArr = [ + 'item' => $expected, + ]; + + $optional = new Optional($targetArr); + + $this->assertEquals($expected, $optional['item']); + } + + public function testGetNotExistItemOnArray() + { + $targetObj = []; + + $optional = new Optional($targetObj); + + $this->assertNull($optional['item']); + } + + public function testIssetExistItemOnArray() + { + $targetArr = [ + 'item' => '', + ]; + + $optional = new Optional($targetArr); + + $this->assertTrue(isset($optional['item'])); + } + + public function testIssetNotExistItemOnArray() + { + $targetArr = []; + + $optional = new Optional($targetArr); + + $this->assertFalse(isset($optional['item'])); + } +}