Skip to content

Instantly share code, notes, and snippets.

@marcojetson
Last active October 19, 2016 13:17
Show Gist options
  • Save marcojetson/b5e022fbb1b799b12364c299029b2f2a to your computer and use it in GitHub Desktop.
Save marcojetson/b5e022fbb1b799b12364c299029b2f2a to your computer and use it in GitHub Desktop.
Array support for Phalcon forms
<?php
class Form extends \Phalcon\Forms\Form
{
/**
* @inheritdoc
*/
public function bind(array $data, $entity, $whitelist = null)
{
foreach ($this->getElements() as $element) {
$name = $element->getName();
preg_match('/^(\w+)(?:\[(\w+)\])?$/', $name, $keys);
array_shift($keys);
if (sizeof($keys) === 2) {
$method = 'get' . Text::camelize($keys[0]);
$target = method_exists($entity, $method) ? $entity->$method() : $entity->$keys[0];
$property = $keys[1];
} else {
$target = $entity;
$property = $keys[0];
}
$value = \igorw\get_in($data, $keys);
$data[$name] = $value;
if ($value === null || ($whitelist !== null && in_array($name, $whitelist))) {
// data not provided or it's whitelisted
continue;
}
$filters = $element->getFilters();
if ($filters) {
/** @var FilterInterface $filter */
$filter = $filter ?: $this->getDI()->getShared('filter');
$value = $filter->sanitize($value, $filters);
}
$method = 'set' . Text::camelize($property);
if (method_exists($target, $method)) {
// setter available
$target->$method($value);
} else {
$target->$property = $value;
}
}
$this->_data = $data;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment