Skip to content

Instantly share code, notes, and snippets.

@gpassarelli
Last active September 28, 2015 16:35
Show Gist options
  • Save gpassarelli/7cd9271f639e0761a491 to your computer and use it in GitHub Desktop.
Save gpassarelli/7cd9271f639e0761a491 to your computer and use it in GitHub Desktop.
Doctrine Fill Class Attributes
/**
* Assign entity properties using an array
*
* @param array $attributes assoc array of values to assign
* @return null
*/
public function fromArray(array $attributes)
{
foreach ($attributes as $name => $value) {
if (property_exists($this, $name)) {
$methodName = $this->_getSetterName($name);
if ($methodName) {
$this->{$methodName}($value);
} else {
$this->$name = $value;
}
}
}
}
/**
* Get property setter method name (if exists)
*
* @param string $propertyName entity property name
* @return false|string
*/
protected function _getSetterName($propertyName)
{
$prefixes = array('add', 'set');
foreach ($prefixes as $prefix) {
if(function_exists('camel_case')){
$methodName = sprintf('%s%s', $prefix, ucfirst(camel_case($propertyName)));
} else {
$methodName = sprintf('%s%s', $prefix, ucfirst(strtolower($propertyName)));
}
if (method_exists($this, $methodName)) {
return $methodName;
}
}
return false;
}
/**
* Prepare attributes for entity
* replace foreign keys with entity instances
*
* @param array $attributes entity attributes
* @return array modified attributes values
*/
public function prepareAttributes(array $attributes)
{
foreach ($attributes as $fieldName => &$fieldValue) {
if (!$this->getClassMetadata()->hasAssociation($fieldName)) {
continue;
}
$association = $this->getClassMetadata()
->getAssociationMapping($fieldName);
if (is_null($fieldValue)) {
continue;
}
$fieldValue = $this->getEntityManager()
->getReference($association['targetEntity'], $fieldValue);
unset($fieldValue);
}
return $attributes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment