Created
July 30, 2013 16:24
-
-
Save marceloandrader/6114486 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DI_Field_Template extends DI_Field implements ArrayAccess | |
{ | |
protected $template; | |
protected $fields = []; | |
protected $defaultTemplate = 'template'; | |
protected $uuid = '_tpl_'; | |
public function __construct(DI_Field $template, $uuid = '_tpl_') | |
{ | |
parent::__construct($template->id); | |
$this->template = $template; | |
$this->uuid = $uuid; | |
$template->parent = $this; | |
} | |
public function offsetExists($key) | |
{ | |
return isset($this->fields[$key]); | |
} | |
public function offsetGet($key) | |
{ | |
return $this->fields[$key]; | |
} | |
public function offsetSet($key, $val) | |
{ | |
$this->addRecord($key, $val); | |
} | |
public function offsetUnset($key) | |
{ | |
unset($this->fields[$key]); | |
} | |
public function addRecord($uuid, $value) | |
{ | |
$field = clone $this->template; | |
$field->parent = $this; | |
if ($value !== null) | |
$field->setValue($value); | |
$this->fields[$uuid] = $field; | |
} | |
public function addRecords($records) | |
{ | |
foreach ($records as $key => $val) | |
$this->addRecord($key, $val); | |
} | |
protected function getTemplate() | |
{ | |
return $this->template; | |
} | |
protected function getFields() | |
{ | |
return $this->fields; | |
} | |
protected function getValue() | |
{ | |
$values = []; | |
foreach ($this->fields as $uuid => $field) | |
{ | |
$values[$uuid] = $field->value; | |
} | |
return $values; | |
} | |
protected function getSaneValue() | |
{ | |
$values = []; | |
foreach ($this->fields as $uuid => $field) | |
{ | |
$values[$uuid] = $field->saneValue; | |
} | |
return $values; | |
} | |
protected function setValue($values) | |
{ | |
if (is_array($values)) | |
{ | |
foreach ($values as $key => $val) | |
{ | |
if (!isset($this->fields[$key])) | |
{ | |
$this->addRecord($key, $val); | |
} | |
else | |
{ | |
$this->fields[$key]->setValue($val); | |
} | |
} | |
} | |
} | |
public function transformName(DI_Field $field, $name) | |
{ | |
if ($field === $this->template) | |
{ | |
$uuid = $this->uuid; | |
} | |
else | |
{ | |
$uuid = '_undefined_'; | |
foreach ($this->fields as $key => $val) | |
{ | |
if ($val === $field) | |
{ | |
$uuid = $key; | |
break; | |
} | |
} | |
} | |
preg_match('/^([^[]+)(.*)$/', $name, $matches); | |
$name = $this->id.'['.$uuid.']'.$matches[2]; | |
return $this->parent ? $this->parent->transformName($this, $name) : $name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment