Skip to content

Commit

Permalink
Bug fix for fetching set of defaults, to avoid always adding a null t…
Browse files Browse the repository at this point in the history
…o fields that have no default defined.
  • Loading branch information
stratease committed May 3, 2024
1 parent 1e364cc commit fb609c0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@ public function getOriginal( string $key = null ) {
return $key ? $this->original[ $key ] : $this->original;
}

/**
* Check if there is a default value for a property.
*
* @since TBD
*
* @param string $key Property name.
*
* @return bool
*/
public 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.
*
Expand All @@ -134,9 +147,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;
}

/**
Expand All @@ -149,7 +164,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;
Expand Down
12 changes: 12 additions & 0 deletions tests/wpunit/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,18 @@ public function testShouldSetMultipleAttributes() {
$this->assertEquals( 'Skywalker', $model->lastName );
}

/**
* @since TBD
*
* @return void
*/
public function testHasDefaultValue() {
$model = new MockModel();
$this->assertTrue( $model->hasDefault( 'firstName' ) );
$this->assertTrue( $model->hasDefault( 'emails' ) );
$this->assertFalse( $model->hasDefault( 'lastName' ) );
}

/**
* @since 1.0.0
*
Expand Down

0 comments on commit fb609c0

Please sign in to comment.