Skip to content

Instantly share code, notes, and snippets.

@Gisleburt
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gisleburt/46cce27abf7cde67d1c0 to your computer and use it in GitHub Desktop.
Save Gisleburt/46cce27abf7cde67d1c0 to your computer and use it in GitHub Desktop.
Checks each property (eg $property_name) of an object for a validatePropertyName($value) function, and runs it. If it's invalid it adds it to an array of invalid properties and returns it.
<?php
class SomeClass {
const FIELD_MISSING = 'Missing';
const FIELD_INVALID = 'Invalid';
/**
* Checks each field for a validate function for each field of the object and runs it
* Override to change this functionality
* @param array $attributes
* @return array
*/
public function getInvalidProperties() {
$invalidFields = array();
foreach(get_object_vars($this) as $property => $value) {
$validateFunction = 'validate'.str_replace(' ', '', ucwords(str_replace('_', ' ', $property)));
if(method_exists($this, $validateFunction)) {
if(!$this->$validateFunction($value)) {
if($value) {
$invalidFields[$property] = static::FIELD_INVALID;
}
else {
$invalidFields[$property] = static::FIELD_MISSING;
}
}
}
}
return $invalidFields;
}
}
@Gisleburt
Copy link
Author

class Test extends SomeClass {
    $test_value;

    public function validateTestValue($value) {
        $len = strlen($value);
        return $len > 0 && $len < 10;
    }
}

$test = new Test();
$missing = $test->getInvalidProperties();

$test->test_value = 'blahblahblah';
$invalid = $test->getInvalidProperties();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment