ikkez/f3-cortex

Fluid Mode With Arrays

Opened this issue · 0 comments

Hi,
I'm building a DB in fluid mode from a JSON object.
In my model, the only $fieldConf entry is the ID field, any other column is added at runtime. But not the field that is an array.
It crashes here:

elseif (strlen($val)>10 && strtotime($val)) $type = $schema::DT_DATETIME;

Unfortunately, I can't use a custom setter/getter onset('unknown_fieldname', ...) in the model, since I don't know the name of the field.

Is there an elegant way to set this up to save and retrieve objects in fluid mode?

Edit:

For now I solved it with a custom cortex method that takes in the dataset and creates onset and onget hooks on the fly.

CSV Model

namespace Model;

class Csv extends Base
{
	protected
		$db = 'TemplateDB', // F3 hive key of a valid DB object
		$table = 'csv',     // the DB table to work on
		$fluid = true,
		$fieldConf = [
			'checklistID' => [
				'type' => 'VARCHAR128',
				'index' => true,
				'unique' => true,
				'belongs-to-one' => ['\Model\Checklists', 'checklistID']
			],
		];

	public function setupFluidHooks($fields)
	{
		foreach ((array)$fields as $key => $field) {
			if (is_array($field)) {
				$this->onset($key, function ($self, $val) {
					return json_encode($val);
				});
				$this->onget($key, function ($self, $val) {
					return json_decode($val, true);
				});
			}
		}
	}
}
public function checklistsToDatabase(array $csv, string $checklistID, string $templateID): \Model\Csv
{
	\Model\Csv::setup();

	$csvModel = new \Model\Csv();
	$csvModel->load(['checklistID = ?', $checklistID]);
	$csvModel->setupFluidHooks($csv);
	$csvModel->copyFrom($csv);
	$csvModel->save();
	return $csvModel;
}

This was the least intrusive, but maybe there is a better way?