Skip to content

Commit dc11ac6

Browse files
committed
Add support for value validation methods
1 parent 76b58e4 commit dc11ac6

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,48 @@ class Breakfast_Model extends Model implements Contracts\ModelCrud {
183183
}
184184
```
185185

186+
## Attribute validation
187+
188+
Sometimes it would be helpful to validate attributes that are set in the model. To do that, you can create `validate_*()`
189+
methods that will execute any time an attribute is set.
190+
191+
Here's an example:
192+
193+
```php
194+
namespace Boomshakalaka\Whatever;
195+
196+
use Boomshakalaka\StellarWP\Models\Model;
197+
198+
class Breakfast_Model extends Model {
199+
/**
200+
* @inheritDoc
201+
*/
202+
protected $properties = [
203+
'id' => 'int',
204+
'name' => 'string',
205+
'price' => 'float',
206+
'num_eggs' => 'int',
207+
'has_bacon' => 'bool',
208+
];
209+
210+
/**
211+
* Validate the name.
212+
*
213+
* @param string $value
214+
*
215+
* @return bool
216+
*/
217+
public function validate_name( $value ): bool {
218+
if ( ! preg_match( '/eggs/i', $value ) ) {
219+
throw new \Exception( 'Breakfasts must have "eggs" in the name!' );
220+
}
221+
222+
return true;
223+
}
224+
}
225+
226+
```
227+
186228
## Data Transfer Objects
187229

188230
Data Transfer Objects (DTOs) are classes that help with the translation of database query results (or other sources of data)

src/Models/Model.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,19 @@ protected function getRelationship( string $key ) {
204204
return null;
205205
}
206206

207+
/**
208+
* Returns true if an attribute exists. Otherwise, false.
209+
*
210+
* @since 1.1.0
211+
*
212+
* @param string $key Attribute name.
213+
*
214+
* @return bool
215+
*/
216+
protected function hasAttribute( string $key ) : bool {
217+
return array_key_exists( $key, $this->attributes );
218+
}
219+
207220
/**
208221
* Checks whether a relationship has already been loaded.
209222
*
@@ -327,6 +340,11 @@ public function setAttribute( string $key, $value ) : ModelInterface {
327340
$this->validatePropertyExists( $key );
328341
$this->validatePropertyType( $key, $value );
329342

343+
$validation_method = 'validate_' . $key;
344+
if ( method_exists( $this, $validation_method ) ) {
345+
$this->$validation_method( $value );
346+
}
347+
330348
$this->attributes[ $key ] = $value;
331349

332350
return $this;

0 commit comments

Comments
 (0)