/** * Save an active record to DB. * @return integer|boolean Either the number of modified/inserted rows or false on failure. */ public function Save($activeRecord) { //global $wpdb; $_wpdb = $this->connection; $copy = $activeRecord; $data = array(); $format = array(); foreach ($this->GetColumns() as $key) { $val = $copy->{$key}; $deffmt = '%s'; if (is_int($copy->{$key})) { $deffmt = '%d'; } if (is_float($copy->{$key})) { $deffmt = '%f'; } if (is_array($copy->{$key}) || is_object($copy->{$key})) { $data[$key] = WSAL_Helpers_DataHelper::JsonEncode($val); } else { $data[$key] = $val; } $format[] = $deffmt; } $result = $_wpdb->replace($this->GetTable(), $data, $format); if ($result !== false) { if ($_wpdb->insert_id) { $copy->setId($_wpdb->insert_id); } } return $result; }
/** * Load object data from variable. * @param array|object $data Data array or object. */ public function LoadData($data) { $copy = get_class($this); $copy = new $copy(); foreach ((array) $data as $key => $val) { if (isset($copy->{$key})) { switch (true) { case is_array($copy->{$key}): case is_object($copy->{$key}): $jsonDecodedVal = WSAL_Helpers_DataHelper::JsonDecode($val); $this->{$key} = $jsonDecodedVal == null ? $val : $jsonDecodedVal; break; case is_int($copy->{$key}): $this->{$key} = (int) $val; break; case is_float($copy->{$key}): $this->{$key} = (double) $val; break; case is_bool($copy->{$key}): $this->{$key} = (bool) $val; break; case is_string($copy->{$key}): $this->{$key} = (string) $val; break; default: throw new Exception('Unsupported type "' . gettype($copy->{$key}) . '"'); } } } return $this; }