+
+ public function export()
+ {
+ return $this->datetime->format($this->storageFormat);
+ }
+}
+
+class JSonFieldFormatter implements PlDBTableFieldFormatter, ArrayAccess
+{
+ private $data;
+
+ public function __construct(PlDBTableField $field, $data)
+ {
+ if (strpos($field->type, 'text') === false) {
+ throw new PlDBBadValueException($data, $field, 'json formatting requires a text field');
+ }
+
+ if (is_string($data)) {
+ $this->data = json_decode($data, true);
+ } else if (is_object($data)) {
+ if ($data instanceof PlExportable) {
+ $this->data = $data->export();
+ } else {
+ $this->data = json_decode(json_encode($data), true);
+ }
+ } else if (is_array($data)) {
+ $this->data = $data;
+ }
+
+ if (is_null($this->data)) {
+ throw new PlDBBadValueException($data, $field, 'cannot interpret data as json: ' . $data);
+ }
+ }
+
+ public function format()
+ {
+ return XDB::escape(json_encode($this->data));
+ }
+
+ public function export()
+ {
+ return $this->data;
+ }
+
+ public function offsetExists($offset)
+ {
+ return isset($this->data[$offset]);
+ }
+
+ public function offsetGet($offset)
+ {
+ return $this->data[$offset];
+ }
+
+ public function offsetSet($offset, $value)
+ {
+ $this->data[$offset] = $value;
+ }
+
+ public function offsetUnset($offset)
+ {
+ unset($this->data[$offset]);
+ }