Skip to content

Instantly share code, notes, and snippets.

@MrTrick
Created November 2, 2012 04:40
Show Gist options
  • Save MrTrick/3998746 to your computer and use it in GitHub Desktop.
Save MrTrick/3998746 to your computer and use it in GitHub Desktop.
Backbone save issue
///////////////////////////////////////////////////////////////////////////////////
// Generate People
$sync = new BLAH_Sync_Person(array('client'=>$ldap_client));
foreach(file('people.csv') as $line) {
list($name, $gender) = explode("\t",trim($line));
$attrs = array();
//Personal
$_names = explode(' ', $name);
$attrs['title'] = ($gender==BLAH_Person::GENDER_MALE) ? 'Mr' : 'Ms';
$attrs['surname'] = array_pop($_names);
$attrs['given_name'] = array_shift($_names);
if ($_names) $attrs['middle_name'] = trim(implode(' ', $_names),'.');
$attrs['gender'] = (int)$gender;
//Contact
$attrs['phone'] = array( sprintf('0499 %03d %03d', rand(0,999), rand(0,999)) );
$attrs['phone_primary'] = $attrs['phone'][0];
$attrs['email'] = array( str_replace(array('.',' '),array('','.'),$name).'@personal.example.com' );
$attrs['email_primary'] = $attrs['email'][0];
//Common
//TODO: Make a note/log about generating the data. Maybe belongs in a 'log' array.
//$attrs['notes'] = array( (stdClass)array('author'=>, ) )
$person = new BLAH_Person($attrs);
//Show some debug output
echo $person->toJSON()."\n";
echo "------------------------------------\n";
print_r($person->validate($person->attributes(), array('missing'=>true)));
echo "------------------------------------\n";
//Try to save the file
$res = $person->save(null, array(
'sync'=>$sync,
'error'=>function() { echo "ERROR: ".json_encode(func_get_args())."\n"; },
'success'=>function() { echo "SUCCESS: ".json_encode(func_get_args())."\n"; }
));
exit; //Debugging, exit after the first person
}
/**
* Validate the given attributes according to the '$validation' rules and '$access_control' policies.
* Return any errors in a map by attribute.
* If no errors are found, the response will be empty.
*
* By default, missing attributes are not considered to be an error.
*
* Options:
* - missing : If set, return errors for missing attributes that have a rule 'required'=>true
*
* @param array $attrs
* @param array $options
* @return array empty if no errors exist, error message(s) if errors exist
*/
public function validate(array $attrs, array $options=array()) {
$errors = array();
//Which values have changed?
$changes = $this->changedAttributes($attrs);
if (!$changes) $changes = array();
$changes_allowed = $this->canWrite($changes, $options); //And which are allowed to be changed
//Do all fields need to be validated, or just the changes?
$to_validate = ($this->_previously_validated) ? $changes : $attrs;
//Check all fields against the rules
foreach($to_validate as $attr=>$val) {
//If no rule exists, the attribute is invalid
if (!isset(static::$validation[$attr])) { $errors[$attr] = "Unknown attribute"; continue; }
//If that attribute has changed - check protections/permissions
if (array_key_exists($attr, $changes)) {
//Protections
$error = $this->_validate_protection($val, $attr, $attrs);
if ($error) { $errors[$attr] = $error; continue; }
//Permissions - check that the user can write to that attribute
if (!$changes_allowed[$attr]) { $errors[$attr] = 'Forbidden'; continue; }
}
//Check whether the attribute itself is valid
if ($val !== null) {
$error = $this->_validate_attribute($val, $attr, $attrs);
if ($error) { $errors[$attr] = $error; continue; }
}
}
//If missing attributes should be reported, check.
if (!empty($options['missing'])) {
//Which attributes are missing?
$missing = array();
foreach(static::$validation as $attr=>$rule)
$missing[$attr] = (!isset($attrs[$attr]) or (!empty($rule['multi']) and $attrs[$attr]===array()));
//Which missing attributes are required?
foreach(static::$validation as $attr=>$rule) if ($missing[$attr]) {
if (!empty($rule['required']))
$errors[$attr] = "Required";
elseif(!empty($rule['requiredif']) and !$missing[ $rule['requiredif'] ] )
$errors[$attr] = "Required if '{$rule['requiredif']}' set";
}
}
//Remember if the model is valid
if (!$errors) $this->_previously_validated = true;
return $errors;
}
{"title":"Mr","surname":"Willis","given_name":"Bruce","gender":1,"phone":["0499 535 964"],"phone_primary":"0499 535 964","email":["[email protected]"],"email_primary":"[email protected]"}
------------------------------------
Array
(
)
------------------------------------
ERROR: [{},{"id":"Cannot modify - readonly"},{"sync":{},"error":{},"success":{}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment