/** * beforeSave * Accomplishes the following if remote sync is enabled: * - Sets the primary key to be saved + any fields passed that are in the actual API schema * - Saves the information to the API * - Sets the remote ID to the ID for this local model * - Sets the braintree_merchant_id key for this model to the current merchantId being used * * @return bool */ public function beforeSave() { if (empty($this->id) && $this->autoPK) { $uuid = String::uuid(); $this->id = $this->data[$this->alias][$this->primaryKey] = $uuid; } if ($this->remote_sync) { $remote_model_name = $this->_getRemoteModelName(); if (!isset($this->{$remote_model_name})) { $this->{$remote_model_name} = ClassRegistry::init('Braintree.' . $remote_model_name); } if (!empty($this->id)) { $this->{$remote_model_name}->id = $this->id; } $whitelisted_fields = $this->{$remote_model_name}->_schema; if ($this->primaryKey != 'id') { $whitelisted_fields = array_merge(array($this->primaryKey => array()), $whitelisted_fields); } foreach ($whitelisted_fields as $field => $schema) { if (!empty($this->data[$this->alias][$field])) { $remote_data[$remote_model_name][$field] = $this->data[$this->alias][$field]; } } $success = $this->{$remote_model_name}->save($remote_data); if (!empty($this->{$remote_model_name}->id)) { $this->id = $this->{$remote_model_name}->id; $this->data[$this->alias][$this->primaryKey] = $this->id; $this->{$remote_model_name}->create(false); $this->{$remote_model_name}->id = null; } if (!$success) { return false; } } if (!empty($this->_schema['braintree_merchant_id'])) { $merchantId = BraintreeConfig::get('merchantId'); if (empty($merchantId)) { return false; } $this->data[$this->alias]['braintree_merchant_id'] = $merchantId; } return true; }