diff --git a/src/Models/Model.php b/src/Models/Model.php index 1eb9a3f..5ddc042 100644 --- a/src/Models/Model.php +++ b/src/Models/Model.php @@ -124,6 +124,31 @@ public function getOriginal( string $key = null ) { return $key ? $this->original[ $key ] : $this->original; } + /** + * Whether the property is set or not. This is different from isset() because this considers a `null` value as + * being set. Defaults are considered set as well. + * + * @unreleased + * + * @return boolean + */ + public function isSet( string $key ): bool { + return array_key_exists( $key, $this->attributes ) || $this->hasDefault( $key ); + } + + /** + * Check if there is a default value for a property. + * + * @unreleased + * + * @param string $key Property name. + * + * @return bool + */ + protected function hasDefault( string $key ): bool { + return is_array( $this->properties[ $key ] ) && array_key_exists( 1, $this->properties[ $key ] ); + } + /** * Returns the default value for a property if one is provided, otherwise null. * @@ -134,9 +159,11 @@ public function getOriginal( string $key = null ) { * @return mixed|null */ protected function getPropertyDefault( string $key ) { - return is_array( $this->properties[ $key ] ) && isset( $this->properties[ $key ][1] ) - ? $this->properties[ $key ][1] - : null; + if ( $this->hasDefault( $key ) ) { + return $this->properties[ $key ][1]; + } + + return null; } /** @@ -149,7 +176,9 @@ protected function getPropertyDefault( string $key ) { protected function getPropertyDefaults() : array { $defaults = []; foreach ( array_keys( $this->properties ) as $property ) { - $defaults[ $property ] = $this->getPropertyDefault( $property ); + if ( $this->hasDefault( $property ) ) { + $defaults[ $property ] = $this->getPropertyDefault( $property ); + } } return $defaults; diff --git a/tests/wpunit/ModelTest.php b/tests/wpunit/ModelTest.php index b8e05c8..1adf2e4 100644 --- a/tests/wpunit/ModelTest.php +++ b/tests/wpunit/ModelTest.php @@ -277,6 +277,25 @@ public function testShouldSetMultipleAttributes() { $this->assertEquals( 'Skywalker', $model->lastName ); } + /** + * @unreleased + * + * @return void + */ + public function testIsSet() { + $model = new MockModel(); + + // This has a default so we should see as set. + $this->assertTrue( $model->isSet( 'firstName' ) ); + + // No default, and hasn't been set so show false. + $this->assertFalse( $model->isSet( 'lastName' ) ); + + // Now we set it, so it should be true - even though we set it to null. + $model->lastName = null; + $this->assertTrue( $model->isSet( 'lastName' ) ); + } + /** * @since 1.0.0 *