53 lines
1.1 KiB
PHP

<?php
namespace App\Entity\Traits;
trait GetterSetter
{
/**
* Returns the getter name for a field
*
* @param string $field
* @return string
*/
protected function getterName($field)
{
return sprintf('get%s', ucfirst(
str_replace(' ', '', ucwords(str_replace('_', ' ', $field)))
));
}
/**
* Returns the setter name for a field
*
* @param string $field
* @return string
*/
protected function setterName($field)
{
return sprintf('set%s', ucfirst(
str_replace(' ', '', ucwords(str_replace('_', ' ', $field)))
));
}
/**
* Populate entity with the given data.
* The set* method will be used to set the data.
*
* @param array $data
* @return boolean
*/
public function populate(array $data = [])
{
foreach ($data as $field => $value) {
$setter = $this->setterName($field);
if (method_exists($this, $setter)) {
$this->{$setter}($value);
}
}
return true;
}
}