/** * Extracts nested validation errors * * @param EntityInterface $entity Entity to extract * * @return array */ protected function _getErrors(EntityInterface $entity) { $errors = $entity->errors(); foreach ($entity->visibleProperties() as $property) { $v = $entity[$property]; if ($v instanceof EntityInterface) { $errors[$property] = $this->_getErrors($v); } elseif (is_array($v)) { foreach ($v as $key => $varValue) { if ($varValue instanceof EntityInterface) { $errors[$property][$key] = $this->_getErrors($varValue); } } } } return Hash::filter($errors); }
/** * Merges `$data` into `$entity` and recursively does the same for each one of * the association names passed in `$options`. When merging associations, if an * entity is not present in the parent entity for a given association, a new one * will be created. * * When merging HasMany or BelongsToMany associations, all the entities in the * `$data` array will appear, those that can be matched by primary key will get * the data merged, but those that cannot, will be discarded. `ids` option can be used * to determine whether the association must use the `_ids` format. * * ### Options: * * - associated: Associations listed here will be marshalled as well. * - validate: Whether or not to validate data before hydrating the entities. Can * also be set to a string to use a specific validator. Defaults to true/default. * - fieldList: A whitelist of fields to be assigned to the entity. If not present * the accessible fields list in the entity will be used. * - accessibleFields: A list of fields to allow or deny in entity accessible fields. * * The above options can be used in each nested `associated` array. In addition to the above * options you can also use the `onlyIds` option for HasMany and BelongsToMany associations. * When true this option restricts the request data to only be read from `_ids`. * * ``` * $result = $marshaller->merge($entity, $data, [ * 'associated' => ['Tags' => ['onlyIds' => true]] * ]); * ``` * * @param \Cake\Datasource\EntityInterface $entity the entity that will get the * data merged in * @param array $data key value list of fields to be merged into the entity * @param array $options List of options. * @return \Cake\Datasource\EntityInterface */ public function merge(EntityInterface $entity, array $data, array $options = []) { list($data, $options) = $this->_prepareDataAndOptions($data, $options); $propertyMap = $this->_buildPropertyMap($options); $isNew = $entity->isNew(); $keys = []; if (!$isNew) { $keys = $entity->extract((array) $this->_table->primaryKey()); } if (isset($options['accessibleFields'])) { foreach ((array) $options['accessibleFields'] as $key => $value) { $entity->accessible($key, $value); } } $errors = $this->_validate($data + $keys, $options, $isNew); $schema = $this->_table->schema(); $properties = $marshalledAssocs = []; foreach ($data as $key => $value) { if (!empty($errors[$key])) { if ($entity instanceof InvalidPropertyInterface) { $entity->invalid($key, $value); } continue; } $columnType = $schema->columnType($key); $original = $entity->get($key); if (isset($propertyMap[$key])) { $assoc = $propertyMap[$key]['association']; $value = $this->_mergeAssociation($original, $assoc, $value, $propertyMap[$key]); $marshalledAssocs[$key] = true; } elseif ($columnType) { $converter = Type::build($columnType); $value = $converter->marshal($value); $isObject = is_object($value); if (!$isObject && $original === $value || $isObject && $original == $value) { continue; } } $properties[$key] = $value; } if (!isset($options['fieldList'])) { $entity->set($properties); $entity->errors($errors); foreach (array_keys($marshalledAssocs) as $field) { if ($properties[$field] instanceof EntityInterface) { $entity->dirty($field, $properties[$field]->dirty()); } } return $entity; } foreach ((array) $options['fieldList'] as $field) { if (array_key_exists($field, $properties)) { $entity->set($field, $properties[$field]); if ($properties[$field] instanceof EntityInterface && isset($marshalledAssocs[$field])) { $entity->dirty($field, $properties[$field]->dirty()); } } } $entity->errors($errors); return $entity; }
/** * Persists an entity based on the fields that are marked as dirty and * returns the same entity after a successful save or false in case * of any error. * * Triggers the `Model.beforeSave` and `Model.afterSave` events. * * ## Options * * - `checkRules` Defaults to true. Check deletion rules before deleting the record. * * @param \Cake\Datasource\EntityInterface $entity The entity to be saved * @param array $options An array of options to be used for the event * @return \Cake\Datasource\EntityInterface|bool */ public function save(EntityInterface $entity, $options = []) { $options += ['checkRules' => true]; $options = new ArrayObject($options); $event = $this->dispatchEvent('Model.beforeSave', ['entity' => $entity, 'options' => $options]); if ($event->isStopped()) { return $event->result; } if ($entity->errors()) { return false; } $mode = $entity->isNew() ? RulesChecker::CREATE : RulesChecker::UPDATE; if ($options['checkRules'] && !$this->checkRules($entity, $mode, $options)) { return false; } $type = $this->connection()->getIndex()->getType($this->name()); $id = $entity->id ?: null; $data = $entity->toArray(); unset($data[$id]); $doc = new ElasticaDocument($id, $data); $doc->setAutoPopulate(true); $result = $type->addDocument($doc); $entity->id = $doc->getId(); $entity->_version = $doc->getVersion(); $entity->isNew(false); $entity->source($this->name()); $entity->clean(); $this->dispatchEvent('Model.afterSave', ['entity' => $entity, 'options' => $options]); return $entity; }
/** * {@inheritDoc} * * ### Options * * The options array accepts the following keys: * * - atomic: Whether to execute the save and callbacks inside a database * transaction (default: true) * - checkRules: Whether or not to check the rules on entity before saving, if the checking * fails, it will abort the save operation. (default:true) * - associated: If true it will save all associated entities as they are found * in the passed `$entity` whenever the property defined for the association * is marked as dirty. Associated records are saved recursively unless told * otherwise. If an array, it will be interpreted as the list of associations * to be saved. It is possible to provide different options for saving on associated * table objects using this key by making the custom options the array value. * If false no associated records will be saved. (default: true) * - checkExisting: Whether or not to check if the entity already exists, assuming that the * entity is marked as not new, and the primary key has been set. * * ### Events * * When saving, this method will trigger four events: * * - Model.beforeRules: Will be triggered right before any rule checking is done * for the passed entity if the `checkRules` key in $options is not set to false. * Listeners will receive as arguments the entity, options array and the operation type. * If the event is stopped the rules check result will be set to the result of the event itself. * - Model.afterRules: Will be triggered right after the `checkRules()` method is * called for the entity. Listeners will receive as arguments the entity, * options array, the result of checking the rules and the operation type. * If the event is stopped the checking result will be set to the result of * the event itself. * - Model.beforeSave: Will be triggered just before the list of fields to be * persisted is calculated. It receives both the entity and the options as * arguments. The options array is passed as an ArrayObject, so any changes in * it will be reflected in every listener and remembered at the end of the event * so it can be used for the rest of the save operation. Returning false in any * of the listeners will abort the saving process. If the event is stopped * using the event API, the event object's `result` property will be returned. * This can be useful when having your own saving strategy implemented inside a * listener. * - Model.afterSave: Will be triggered after a successful insert or save, * listeners will receive the entity and the options array as arguments. The type * of operation performed (insert or update) can be determined by checking the * entity's method `isNew`, true meaning an insert and false an update. * - Model.afterSaveCommit: Will be triggered after the transaction is commited * for atomic save, listeners will receive the entity and the options array * as arguments. * * This method will determine whether the passed entity needs to be * inserted or updated in the database. It does that by checking the `isNew` * method on the entity. If the entity to be saved returns a non-empty value from * its `errors()` method, it will not be saved. * * ### Saving on associated tables * * This method will by default persist entities belonging to associated tables, * whenever a dirty property matching the name of the property name set for an * association in this table. It is possible to control what associations will * be saved and to pass additional option for saving them. * * ``` * // Only save the comments association * $articles->save($entity, ['associated' => ['Comments']); * * // Save the company, the employees and related addresses for each of them. * // For employees do not check the entity rules * $companies->save($entity, [ * 'associated' => [ * 'Employees' => [ * 'associated' => ['Addresses'], * 'checkRules' => false * ] * ] * ]); * * // Save no associations * $articles->save($entity, ['associated' => false]); * ``` * */ public function save(EntityInterface $entity, $options = []) { $options = new ArrayObject($options + ['atomic' => true, 'associated' => true, 'checkRules' => true, 'checkExisting' => true, '_primary' => true]); if ($entity->errors()) { return false; } if ($entity->isNew() === false && !$entity->dirty()) { return $entity; } $connection = $this->connection(); if ($options['atomic']) { $success = $connection->transactional(function () use($entity, $options) { return $this->_processSave($entity, $options); }); } else { $success = $this->_processSave($entity, $options); } if ($success) { if (!$connection->inTransaction() && ($options['atomic'] || !$options['atomic'] && $options['_primary'])) { $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options')); } if ($options['atomic'] || $options['_primary']) { $entity->isNew(false); $entity->source($this->registryAlias()); } } return $success; }
/** * Merges `$data` into `$document`. * * ### Options: * * * fieldList: A whitelist of fields to be assigned to the entity. If not present * the accessible fields list in the entity will be used. * * @param \Cake\Datasource\EntityInterface $entity the entity that will get the * data merged in * @param array $data key value list of fields to be merged into the entity * @param array $options List of options. * @return \Cake\Datasource\EntityInterface */ public function merge(EntityInterface $entity, array $data, array $options = []) { list($data, $options) = $this->_prepareDataAndOptions($data, $options); $errors = $this->_validate($data, $options, $entity->isNew()); $entity->errors($errors); foreach (array_keys($errors) as $badKey) { unset($data[$badKey]); } foreach ($this->type->embedded() as $embed) { $property = $embed->property(); if (in_array($embed->alias(), $options['associated']) && isset($data[$property])) { $data[$property] = $this->mergeNested($embed, $entity->{$property}, $data[$property]); } } if (!isset($options['fieldList'])) { $entity->set($data); return $entity; } foreach ((array) $options['fieldList'] as $field) { if (array_key_exists($field, $data)) { $entity->set($field, $data[$field]); } } return $entity; }
/** * Merges `$data` into `$entity`. * * ### Options: * * * validate: Whether or not to validate data before hydrating the entities. Can * also be set to a string to use a specific validator. Defaults to true/default. * * fieldList: A whitelist of fields to be assigned to the entity. If not present * the accessible fields list in the entity will be used. * * accessibleFields: A list of fields to allow or deny in entity accessible fields. * * @param \Cake\Datasource\EntityInterface $entity the entity that will get the * data merged in * @param array $data key value list of fields to be merged into the entity * @param array $options List of options. * @return \Cake\Datasource\EntityInterface */ public function merge(EntityInterface $entity, array $data, array $options = []) { list($data, $options) = $this->_prepareDataAndOptions($data, $options); $isNew = $entity->isNew(); $keys = []; if (!$isNew) { $keys = $entity->extract((array) $this->_endpoint->primaryKey()); } if (isset($options['accessibleFields'])) { foreach ((array) $options['accessibleFields'] as $key => $value) { $entity->accessible($key, $value); } } $errors = $this->_validate($data + $keys, $options, $isNew); $properties = []; foreach ($data as $key => $value) { if (!empty($errors[$key])) { continue; } $properties[$key] = $value; } if (!isset($options['fieldList'])) { $entity->set($properties); $entity->errors($errors); return $entity; } foreach ((array) $options['fieldList'] as $field) { if (array_key_exists($field, $properties)) { $entity->set($field, $properties[$field]); } } $entity->errors($errors); return $entity; }
/** * Changes the password for an user. * * @param \Cake\Datasource\EntityInterface $entity User entity * @return boolean */ public function changePassword(EntityInterface $entity) { if ($entity->errors()) { return false; } $entity->password = $this->hashPassword($entity->password); if ($this->_table->save($entity)) { return true; } return false; }
/** * {@inheritDoc} * * ### Options * * The options array can receive the following keys: * * - atomic: Whether to execute the save and callbacks inside a database * transaction (default: true) * - checkRules: Whether or not to check the rules on entity before saving, if the checking * fails, it will abort the save operation. (default:true) * - associated: If true it will save all associated entities as they are found * in the passed `$entity` whenever the property defined for the association * is marked as dirty. Associated records are saved recursively unless told * otherwise. If an array, it will be interpreted as the list of associations * to be saved. It is possible to provide different options for saving on associated * table objects using this key by making the custom options the array value. * If false no associated records will be saved. (default: true) * - checkExisting: Whether or not to check if the entity already exists, assuming that the * entity is marked as not new, and the primary key has been set. * * ### Events * * When saving, this method will trigger four events: * * - Model.beforeRules: Will be triggered right before any rule checking is done * for the passed entity if the `checkRules` key in $options is not set to false. * Listeners will receive as arguments the entity, options array and the operation type. * If the event is stopped the checking result will be set to the result of the event itself. * - Model.afterRules: Will be triggered right after the `checkRules()` method is * called for the entity. Listeners will receive as arguments the entity, * options array, the result of checking the rules and the operation type. * If the event is stopped the checking result will be set to the result of * the event itself. * - Model.beforeSave: Will be triggered just before the list of fields to be * persisted is calculated. It receives both the entity and the options as * arguments. The options array is passed as an ArrayObject, so any changes in * it will be reflected in every listener and remembered at the end of the event * so it can be used for the rest of the save operation. Returning false in any * of the listeners will abort the saving process. If the event is stopped * using the event API, the event object's `result` property will be returned. * This can be useful when having your own saving strategy implemented inside a * listener. * - Model.afterSave: Will be triggered after a successful insert or save, * listeners will receive the entity and the options array as arguments. The type * of operation performed (insert or update) can be determined by checking the * entity's method `isNew`, true meaning an insert and false an update. * * This method will determine whether the passed entity needs to be * inserted or updated in the database. It does that by checking the `isNew` * method on the entity. If the entity to be saved returns a non-empty value from * its `errors()` method, it will not be saved. * * ### Saving on associated tables * * This method will by default persist entities belonging to associated tables, * whenever a dirty property matching the name of the property name set for an * association in this table. It is possible to control what associations will * be saved and to pass additional option for saving them. * * ``` * // Only save the comments association * $articles->save($entity, ['associated' => ['Comments']); * * // Save the company, the employees and related addresses for each of them. * // For employees do not check the entity rules * $companies->save($entity, [ * 'associated' => [ * 'Employees' => [ * 'associated' => ['Addresses'], * 'checkRules' => false * ] * ] * ]); * * // Save no associations * $articles->save($entity, ['associated' => false]); * ``` * */ public function save(EntityInterface $entity, $options = []) { $options = new ArrayObject($options + ['atomic' => true, 'associated' => true, 'checkRules' => true, 'checkExisting' => true]); if ($entity->errors()) { return false; } if ($entity->isNew() === false && !$entity->dirty()) { return $entity; } if ($options['atomic']) { $connection = $this->connection(); $success = $connection->transactional(function () use($entity, $options) { return $this->_processSave($entity, $options); }); } else { $success = $this->_processSave($entity, $options); } return $success; }