/** * save */ public function beforeSave(Event $event, Entity $entity) { $config = $this->config(); $fields = $config['fields']; foreach ($fields as $key => $value) { $historic[$value] = $entity->get($value); } if (!$entity->isNew() && ($historicOld = $this->_table->Historics->find()->where([$this->foreignKey => $entity->id])->toArray())) { $this->_table->Historics->patchEntity($historicOld[0], ['is_active' => 0]); $entity->set('historics', [$this->_table->Historics->newEntity($historic), $historicOld[0]]); } else { $entity->set('historics', [$this->_table->Historics->newEntity($historic)]); } $entity->dirty('historics', true); }
public function beforeSave(Event $event, Entity $entity) { $get_user_id_function = $this->config('get_user_id_function'); if (!empty($get_user_id_function)) { $user_id = call_user_func($get_user_id_function); if ($entity->isNew() && $entity->accessible('created_by')) { $entity->created_by = $user_id; } if (!$entity->isNew() && $entity->accessible('modified_by')) { $entity->modified_by = $user_id; } } }
/** * Returns the basepath for the current field/data combination. * If a `path` is specified in settings, then that will be used as * the replacement pattern * * @return string * @throws LogicException if a replacement is not valid for the current dataset */ public function basepath() { $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}'; $path = Hash::get($this->settings, 'path', $defaultPath); if (strpos($path, '{primaryKey}') !== false) { if ($this->entity->isNew()) { throw new LogicException('{primaryKey} substitution not allowed for new entities'); } if (is_array($this->table->primaryKey())) { throw new LogicException('{primaryKey} substitution not valid for composite primary keys'); } } $replacements = ['{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{relatedModel}' => $this->entity->model, '{table}' => $this->table->table(), '{field}' => $this->field, '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR]; return str_replace(array_keys($replacements), array_values($replacements), $path); }
/** * Before save listener. * Transparently manages setting the lft and rght fields if the parent field is * included in the parameters to be saved. * * @param \Cake\Event\Event the beforeSave event that was fired * @param \Cake\ORM\Entity the entity that is going to be saved * @return void * @throws \RuntimeException if the parent to set for the node is invalid */ public function beforeSave(Event $event, Entity $entity) { $isNew = $entity->isNew(); $config = $this->config(); $parent = $entity->get($config['parent']); $primaryKey = (array) $this->_table->primaryKey(); $dirty = $entity->dirty($config['parent']); if ($isNew && $parent) { if ($entity->get($primaryKey[0]) == $parent) { throw new \RuntimeException("Cannot set a node's parent as itself"); } $parentNode = $this->_getNode($parent); $edge = $parentNode->get($config['right']); $entity->set($config['left'], $edge); $entity->set($config['right'], $edge + 1); $this->_sync(2, '+', ">= {$edge}"); } if ($isNew && !$parent) { $edge = $this->_getMax(); $entity->set($config['left'], $edge + 1); $entity->set($config['right'], $edge + 2); } if (!$isNew && $dirty && $parent) { $this->_setParent($entity, $parent); } if (!$isNew && $dirty && !$parent) { $this->_setAsRoot($entity); } }
/** * Run before a model is saved, used to set up slug for model. * * @param \Cake\Event\Event $event The event that was triggered * @param \Cake\ORM\Entity $entity The entity being saved * @param array $options Array of options for the save operation * @return bool True if save should proceed, false otherwise * @throws \Cake\Error\FatalErrorException When some of the specified columns * in config's "label" is not present in the entity being saved */ public function beforeSave(Event $event, $entity, $options = []) { if (!$this->_enabled) { return true; } $config = $this->config(); $isNew = $entity->isNew(); if ($isNew && in_array($config['on'], ['create', 'both']) || !$isNew && in_array($config['on'], ['update', 'both'])) { if (!is_array($config['label'])) { $config['label'] = [$config['label']]; } foreach ($config['label'] as $field) { if (!$entity->has($field)) { throw new FatalErrorException(__d('cms', 'SluggableBehavior was not able to generate a slug reason: entity\'s property "{0}" not found', $field)); } } $label = ''; foreach ($config['label'] as $field) { $val = $entity->get($field); $label .= !empty($val) ? " {$val}" : ''; } if (!empty($label)) { $slug = $this->_slug($label, $entity); $entity->set($config['slug'], $slug); } } return true; }
/** * After Save Callback * * @param Cake/Event/Event $event The afterSave event that was fired. * @param Cake/ORM/Entity $entity The entity * @param ArrayObject $options Options * @return void */ public function afterSave(Event $event, Entity $entity, ArrayObject $options) { if ($entity->isNew()) { $this->saveDefaultUri($entity); } else { // Change route. if ($entity->dirty()) { $SeoUris = TableRegistry::get('Seo.SeoUris'); $SeoCanonicals = TableRegistry::get('Seo.SeoCanonicals'); $urlsConfig = $this->config('urls'); foreach ($urlsConfig as $key => $url) { $uri = $this->_getUri($entity, $url); $seoUri = $SeoUris->find()->contain(['SeoCanonicals'])->where(['model' => $this->_table->alias(), 'foreign_key' => $entity->id, 'locale' => isset($url['locale']) ? $url['locale'] : null])->first(); if ($seoUri) { $seoUri = $SeoUris->patchEntity($seoUri, ['uri' => $uri], ['associated' => ['SeoCanonicals']]); $SeoUris->save($seoUri); $seoUriCanonical = Router::fullBaseUrl() . $uri; $seoUri->seo_canonical->set('canonical', $seoUriCanonical); $SeoCanonicals->save($seoUri->seo_canonical); } } } } \Cake\Cache\Cache::clear(false, 'seo'); }
/** * AfterSave callback. * * @param \Cake\Event\Event $event The afterSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @param \ArrayObject $options The options passed to the callback. * * @return bool */ public function afterSave(Event $event, Entity $entity, ArrayObject $options) { if ($entity->isNew()) { $comment = new Event('Model.BlogArticlesComments.add', $this, ['comment' => $entity]); $this->eventManager()->dispatch($comment); } return true; }
/** * Called after an entity is saved * @param \Cake\Event\Event $event Event object * @param \Cake\ORM\Entity $entity Entity object * @param \ArrayObject $options Options * @return void * @uses MeCms\Model\Table\AppTable::afterSave() */ public function afterSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options) { //Creates the folder if ($entity->isNew()) { (new Folder())->create(PHOTOS . DS . $entity->id, 0777); } parent::afterSave($event, $entity, $options); }
public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { if ($entity->isNew() && empty($entity->user_id)) { $entity->errors('user_id', ['not_found', 'User not found']); $entity->errors('net_id', ['not_found', 'User not found']); return false; } }
/** * Before save callback. * * @param Event $event * @param Entity $entity * @param \ArrayObject $options * @return bool */ public function beforeSave(Event $event, Entity $entity, \ArrayObject $options) { if ($entity->isNew() || $this->_config['update']) { $uniqueSlug = $this->_generateUniqueSlug($entity); $entity->set($this->_config['slug'], $uniqueSlug); } return true; }
/** * test beforeSave() method when updating an existing entity. * * @return void */ public function testBeforeSaveEditEntity() { $event = new Event('Model.beforeSave'); $entity = new Entity(['id' => 100, 'title' => 'Random String Title', 'slug' => '']); $entity->isNew(false); $this->Behavior->beforeSave($event, $entity); $this->assertTrue(!$entity->has('created_by')); $this->assertEquals(1, $entity->get('modified_by')); }
/** * Every save event triggers a new personal_key. If the entity is new then * check the config if there needs to be an email verification. */ public function beforeSave(Event $event, Entity $entity) { $entity->set('personal_key'); if ($entity->isNew()) { if (Configure::read('Users.send_email_verification')) { $entity->emailVerification(); } } }
public function beforeSave(Event $event, Entity $entity, \ArrayObject $options) { if ($entity->isNew()) { if (!$this->matchUser($entity)) { $entity->errors('net_id', ['not_found', 'User not found']); return false; } } }
/** * {@inheritDoc} */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { if (empty($options['loggedInUser'])) { return; } if ($entity->isNew()) { $entity->set('created_by', $options['loggedInUser']); } $entity->set('modified_by', $options['loggedInUser']); }
public function afterSave(Event $event, Entity $entity) { $job_id = $entity->job_id; $event_id = isset($entity->event_id) ? $entity->event_id : 1; // default to event type 1 (new file upload) // format file list, if applicable $files = ''; if ($this->files) { foreach ($this->files as $file) { $files .= basename($file) . '<br/>'; } } // NEW FILE IS UPLOADED if ($entity->isNew()) { $Activity = TableRegistry::get('Activity'); $activity = $Activity->find('all')->where(['Activity.id' => $entity->id])->contain(['Files', 'Users', 'Creatives', 'Jobs'])->first()->toArray(); //die(print_r($activity)); $Notifications = TableRegistry::get('Notifications'); // set conditions for notification query $conditions = ['OR' => [['Notifications.event_id' => "4"], ['Notifications.job_id' => $job_id, 'OR' => [['Notifications.event_id' => $event_id], ['Notifications.event_id' => "3"]]]]]; if ($notify_users = $Notifications->find('all', ['conditions' => $conditions, 'group' => ['Notifications.user_id'], 'contain' => ['Users']])) { $notify_users = $notify_users->toArray(); $Events = TableRegistry::get('Events'); $event = $Events->get($event_id)->toArray(); $text = $event['email_text']; $text = str_replace("%username%", $activity['user']['first_name'], $text); $text = str_replace("%fileversion%", $activity['file']['version'], $text); $text = str_replace("%filename%", $activity['file']['name'], $text); $text = str_replace("%dimensions%", $activity['file']['width'] && $activity['file']['height'] ? $activity['file']['width'] . 'X' . $activity['file']['height'] : 'N/A', $text); $text = str_replace("%size%", $activity['file']['size'], $text); $text = str_replace("%jobname%", $activity['job']['name'], $text); $text = str_replace("%joblink%", $activity['job']['short_link'] . '#' . $activity['creative']['slug'], $text); $text = str_replace("%creativename%", $activity['creative']['name'], $text); $text = str_replace("%files%", $files, $text); $subject = $event['email_subject']; $subject = str_replace("%filename%", $activity['file']['name'], $subject); $subject = str_replace("%jobname%", $activity['job']['name'], $subject); $subject = str_replace("%username%", $activity['user']['first_name'], $subject); foreach ($notify_users as $user) { $name = $user['user']['first_name']; $email = $user['user']['email']; $body = file_get_contents(WWW_ROOT . DS . 'email/notify.html'); $body = str_replace("%name%", $name, $body); $body = str_replace("%username%", $name, $body); $body = str_replace("%email%", $email, $body); $body = str_replace("%text%", $text, $body); if (AppController::sendEmail(['subject' => $subject, 'body' => $body, 'to' => $email])) { $Notifications->save($Notifications->newEntity(['id' => $user['id']])); } else { // epic fail } } } } }
/** * {@inheritdoc} */ public function beforeSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options) { if ($entity->isNew()) { // populate the created field (TimestampBehavior could not be used, // as sqlite doesn't support datetime comparisons which are needed // on this field. $entity->created = date('YmdHis'); // populate the scraped field, used to calculate the last_run used // in \Gourmet\Dashboard\DashboardWidget\AbstractWidgetWorker::interval() if (empty($entity->scraped)) { $entity->scraped = date('Y-m-d H:i:s'); } } return true; }
/** * There is only one event handler, it can be configured to be called for any event * * @param \Cake\Event\Event $event Event instance. * @param \Cake\ORM\Entity $entity Entity instance. * @throws \UnexpectedValueException if a field's when value is misdefined * @return true (irrespective of the behavior logic, the save will not be prevented) * @throws \UnexpectedValueException When the value for an event is not 'always', 'new' or 'existing' */ public function handleEvent(Event $event, Entity $entity) { $eventName = $event->name(); $events = $this->config('events'); $new = $entity->isNew() !== false; foreach ($events[$eventName] as $field => $when) { if (!in_array($when, ['always', 'new', 'existing'])) { throw new \UnexpectedValueException(sprintf('When should be one of "always", "new" or "existing". The passed value "%s" is invalid', $when)); } if ($when === 'always' || $when === 'new' && $new || $when === 'existing' && !$new) { $this->_updateField($entity, $field); } } return true; }
/** * beforeSave callback * * Prevent saving if the context is not global * * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeSave(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { //save new operation $field = $this->config('foreign_key_field'); if ($entity->isNew()) { // Model is no required to have a foreign_key_field to tenant, // But if one exists we will update it // no overwrite, if foreign_keyfield has an assigned value, do nothing if ($entity->{$field} === null) { $entity->{$field} = MTApp::tenant()->id; } } } return true; }
/** * Injects configured field values into entity if those fields are not dirty. * * @param \Cake\Event\Event $event Event. * @param \Cake\ORM\Entity $entity Entity. * @param \ArrayObject $options Options. * @return void */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { $eventName = $event->name(); $events = $this->config('events'); $new = $entity->isNew() !== false; foreach ($events[$eventName] as $field => $when) { if (!in_array($when, ['always', 'new', 'existing'])) { throw new UnexpectedValueException(sprintf('When should be one of "always", "new" or "existing". The passed value "%s" is invalid', $when)); } if ($entity->dirty($field)) { continue; } if ($when === 'always' || $when === 'new' && $new || $when === 'existing' && !$new) { $entity->set($field, current(Hash::extract((array) $options, $this->config('propertiesMap.' . $field)))); } } }
/** * AfterSave * @param Event $event * @param Entity $entity * @param ArrayObject $options * @return bool */ public function afterSave(Event $event, Entity $entity, \ArrayObject $options) { if ($entity->isNew()) { $ref = $entity->ref; $refId = $entity->ref_id; $table = TableRegistry::get($ref); // Manual countercache, it's more flexible, no need to add complex relation on Comment Model if ($table->hasField('comment_count')) { $refData = $table->get($refId); $newRefData = ['comment_count' => $this->find()->where(['ref' => $ref, 'ref_id' => $refId])->count()]; $refData = $table->patchEntity($refData, $newRefData); $table->save($refData, ['checkRules' => false]); } $this->eventManager()->dispatch(new Event('Plugin.Comments.add', $this)); return true; } }
public function afterSave(Event $event, Entity $entity) { $model = substr(strrchr($entity->source(), '.'), 1); if (!$model) { $model = $entity->source(); } $type_id = self::HISTORIES_CREATE; if (!$entity->isNew()) { $type_id = self::HISTORIES_UPDATE; } $user_id = 0; // Unknow debug($this->request->session()->read('Auth.User.id')); die; $this->Histories = TableRegistry::get('Histories'); $history = $this->Histories->newEntity(['model' => $model, 'foreign_key' => $entity->id, 'type_id' => $type_id, 'user_id' => $user_id, 'created' => new Time()]); $this->Histories->save($history); }
/** * testBeforeSave * * @return void */ public function testBeforeSave() { $table = $this->getMock('Cake\\ORM\\Table'); $this->Behavior = new BlameBehavior($table); $event = new Event('Model.beforeSave'); $entity = new Entity(['name' => 'Foo']); $entity->isNew(false); $options = new ArrayObject(['loggedInUser' => null]); $this->Behavior->beforeSave($event, $entity, $options); $this->assertNull($entity->created_by, 'created_by is expected NOT to be updated'); $this->assertNull($entity->modified_by, 'modified_by is expected NOT to be updated'); $options = new ArrayObject(['loggedInUser' => 5]); $this->Behavior->beforeSave($event, $entity, $options); $this->assertNull($entity->created_by, 'created_by is expected NOT to be updated'); $this->assertSame(5, $entity->modified_by, 'modified_by is expected to be updated'); $entity->isNew(true); $this->Behavior->beforeSave($event, $entity, $options); $this->assertSame(5, $entity->created_by, 'modified_by is expected to be updated'); }
/** * testModifiedPresent * * @return void * @triggers Model.beforeSave */ public function testModifiedPresent() { $table = $this->getMock('Cake\\ORM\\Table'); $this->Behavior = new TimestampBehavior($table); $ts = new \DateTime('2000-01-01'); $this->Behavior->timestamp($ts); $event = new Event('Model.beforeSave'); $existingValue = new \DateTime('2011-11-11'); $entity = new Entity(['name' => 'Foo', 'modified' => $existingValue]); $entity->clean(); $entity->isNew(false); $return = $this->Behavior->handleEvent($event, $entity); $this->assertTrue($return, 'Handle Event is expected to always return true'); $this->assertInstanceOf('Cake\\I18n\\Time', $entity->modified); $this->assertSame($ts->format('c'), $entity->modified->format('c'), 'Modified timestamp is expected to be updated'); }
/** * Test merge with validation and create or update validation rules * * @return void */ public function testMergeWithCreate() { $data = ['title' => 'My title', 'author_id' => 'foo']; $marshall = new Marshaller($this->articles); $entity = new Entity(['title' => 'Foo', 'body' => 'My Content', 'author_id' => 1]); $entity->accessible('*', true); $entity->isNew(true); $entity->clean(); $this->articles->validator()->requirePresence('thing', 'update')->add('author_id', 'numeric', ['rule' => 'numeric', 'on' => 'update']); $expected = clone $entity; $result = $marshall->merge($expected, $data, []); $this->assertEmpty($result->errors('author_id')); $this->assertEmpty($result->errors('thing')); $entity->clean(); $entity->isNew(false); $result = $marshall->merge($entity, $data, []); $this->assertNotEmpty($result->errors('author_id')); $this->assertNotEmpty($result->errors('thing')); }
/** * After save listener. * * Manages updating level of descendents of currently saved entity. * * @param \Cake\Event\Event $event The beforeSave event that was fired * @param \Cake\ORM\Entity $entity the entity that is going to be saved * @return void */ public function afterSave(Event $event, Entity $entity) { if (!$this->_config['level'] || $entity->isNew()) { return; } $this->_setChildrenLevel($entity); }
/** * beforeSave callback * * Allow insert of tenant records if in tenant context * Allow insert of tenant records if in tenant context * Prevent update of records that are global * Prevent update if the record belongs to another tenant * * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeSave(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { //save new operation $field = $this->config('foreign_key_field'); //insert operation if ($entity->isNew()) { //blind overwrite, preventing user from providing explicit value $entity->{$field} = MTApp::tenant()->id; } else { //update operation //prevent tenant from updating global records if he is not the owner of the global tenant if ($entity->{$field} == $this->config('global_value') && MTapp::tenant()->id != $this->config('global_value')) { throw new DataScopeViolationException('Tenant cannot update global records'); } //paranoid check of ownership if ($entity->{$field} != MTApp::tenant()->id) { //current tenant is NOT owner throw new DataScopeViolationException('Tenant->id:' . MTApp::tenant()->id . ' does not own ' . $this->_table->alias() . '->id:' . $entity->id); } } // end if } return true; }
/** * Throws an exception should any of the passed entities is not persisted. * * @param \Cake\ORM\Entity $sourceEntity the row belonging to the `source` side * of this association * @param array $targetEntities list of entities belonging to the `target` side * of this association * @return bool * @throws \InvalidArgumentException */ protected function _checkPersistenceStatus($sourceEntity, array $targetEntities) { if ($sourceEntity->isNew()) { $error = 'Source entity needs to be persisted before proceeding'; throw new InvalidArgumentException($error); } foreach ($targetEntities as $entity) { if ($entity->isNew()) { $error = 'Cannot link not persisted entities'; throw new InvalidArgumentException($error); } } return true; }
/** * Provides empty values * * @return void */ public function testIsDirtyFromClone() { $entity = new Entity(['a' => 1, 'b' => 2], ['markNew' => false, 'markClean' => true]); $this->assertFalse($entity->isNew()); $this->assertFalse($entity->dirty()); $cloned = clone $entity; $cloned->isNew(true); $this->assertTrue($cloned->dirty()); $this->assertTrue($cloned->dirty('a')); $this->assertTrue($cloned->dirty('b')); }
/** * Implementation of the beforesave event, handles uploading / saving and overwriting of image records * @param \Cake\Event\Event $event [description] * @param \Cake\ORM\Entity $entity [description] * @param ArrayObject $options [description] * @return void */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { $fields = $this->config('fields'); $alias = $this->_table->registryAlias(); $newOptions = [$this->_imagesTable->alias() => ['validate' => false]]; $options['associated'] = $newOptions + $options['associated']; $entities = []; foreach ($fields as $_fieldName => $fieldType) { $uploadedImages = []; $field = $entity->{$_fieldName}; $field = $fieldType == 'one' ? [$field] : $field; if (!$field) { continue; } foreach ($field as $index => $image) { $uploadeImage = null; if (!empty($image['tmp_name'])) { // server based file uploads $uploadeImage = $this->_upload($image['name'], $image['tmp_name'], false); } elseif (is_string($image)) { // any other 'path' based uploads $uploadeImage = $this->_upload($image, $image, true); } if (!empty($uploadeImage)) { $uploadedImages[$index] = $uploadeImage + ['field_index' => $index, 'model' => $alias, 'field' => $_fieldName]; } } if (!empty($uploadedImages)) { if (!$entity->isNew()) { $imagesTableAlias = $this->_imagesTable->alias(); $preexisting = $this->_imagesTable->find()->where(['model' => $alias, 'field' => $_fieldName, 'foreign_key' => $entity->{$this->_table->primaryKey()}])->order(['field_index' => 'ASC']); foreach ($preexisting as $image) { if (isset($uploadedImages[$image->field_index])) { $entities[$image->field_index] = $this->_imagesTable->patchEntity($image, $uploadedImages[$image->field_index]); } elseif ($fieldType == 'one') { $this->_imagesTable->delete($image); } } } $new = array_diff_key($uploadedImages, $entities); foreach ($new as $image) { $entities[] = $this->_imagesTable->newEntity($image); } } $entity->dirty($_fieldName, false); } $entity->set('_images', $entities); }
/** * beforeSave callback * * Prevent saving if the context is not global * * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that was saved. * @return void */ public function beforeSave(Event $event, Entity $entity, $options) { if (MTApp::getContext() == 'tenant') { //save new operation $field = $this->config('foreign_key_field'); if ($entity->isNew()) { //blind overwrite, preventing user from providing explicit value $entity->{$field} = MTApp::tenant()->id; } else { //update operation //paranoid check of ownership if ($entity->{$field} != MTApp::tenant()->id) { //current tenant is NOT owner throw new DataScopeViolationException('Tenant->id:' . MTApp::tenant()->id . ' does not own ' . $this->_table->alias() . '->id:' . $entity->id); } } // end if } else { throw new DataScopeViolationException('Tenant Scoped accessed globally'); } return true; }