/** * 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); }
/** * get appropriate fields with files * move uploaded file and set path to entity field, but only if a file was selected * * @param Entity $entity */ public function uploadFile(Entity $entity) { $config = $this->config(); if (!is_array($config['field'])) { $field = $entity->get($config['field']); if (empty($field['tmp_name'])) { $entity->unsetProperty($config['field']); } else { if ($entity->get($config['field']) != $entity->getOriginal($config['field'])) { $originalFilePath = $entity->getOriginal($config['field']); $this->_delete($originalFilePath); } $filePath = $this->_moveFile($field); $entity->set($config['field'], $filePath); } } else { foreach ($config['field'] as $value) { $field = $entity->get($value); if (empty($field['tmp_name'])) { $entity->unsetProperty($config['field']); } else { if ($entity->get($config['field']) != $entity->getOriginal($config['field'])) { $originalFilePath = $entity->getOriginal($config['field']); $this->_delete($originalFilePath); } $filePath = $this->_moveFile($field); $entity->set($config['field'], $filePath); } } } }
/** * {@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']); }
/** * Modifies the entity before it is saved so that uploaded file data is persisted * in the database too. * * @param \Cake\Event\Event $event The beforeSave event that was fired * @param \Cake\ORM\Entity $entity The entity that is going to be saved * @param \ArrayObject $options the options passed to the save method * @return void|false */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { foreach ($this->config() as $field => $settings) { if (Hash::get((array) $entity->get($field), 'error') !== UPLOAD_ERR_OK) { if (Hash::get($settings, 'restoreValueOnFailure', true)) { $entity->set($field, $entity->getOriginal($field)); $entity->dirty($field, false); } continue; } $data = $entity->get($field); $path = $this->getPathProcessor($entity, $data, $field, $settings); $basepath = $path->basepath(); $filename = $path->filename(); $data['name'] = $filename; $files = $this->constructFiles($entity, $data, $field, $settings, $basepath); $writer = $this->getWriter($entity, $data, $field, $settings); $success = $writer->write($files); if ((new Collection($success))->contains(false)) { return false; } $entity->set($field, $filename); $entity->set(Hash::get($settings, 'fields.dir', 'dir'), $basepath); $entity->set(Hash::get($settings, 'fields.size', 'size'), $data['size']); $entity->set(Hash::get($settings, 'fields.type', 'type'), $data['type']); } }
public function slug(Entity $entity) { $config = $this->config(); if (!($value = $entity->get($config['slug']))) { $value = $entity->get($config['field']); } $entity->set($config['slug'], Inflector::slug($value, $config['replacement'])); }
public function beforeSave(Event $event, Entity $entity) { $config = $this->config(); $value = $entity->get($config['field']); $id = isset($entity->id) ? $entity->id : 0; $slug = $this->createSLug(strtolower(Inflector::slug($value, $config['replacement'])), 0, $id); $entity->set($config['slug'], $slug); }
/** * beforeSave event * * @param \Cake\Event\Event $event Event. * @param \Cake\ORM\Entity $entity Entity. * @param array $options Options. * @return void */ public function beforeSave($event, $entity, $options) { $entity->set('cakeadmin', true); $newPassword = $entity->get('new_password'); if (!empty($newPassword)) { $entity->set('password', $entity->new_password); // set for password-changes } }
/** * 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 transformState(Entity $entity) { $states = $this->getStates(); $field = $this->config('field'); $state = $this->config('defaultState'); if (array_key_exists($entity->{$field}, $states)) { $state = $entity->{$field}; } $state = $states[$state]; $entity->set($this->config('field'), $state); }
public function beforeSave(Event $event, Entity $entity) { // create short link if one does not yet exist if (empty($entity->id)) { $link = $this->makeShortLink(); $Jobs = TableRegistry::get('Jobs'); while ($Jobs->find('all')->where(['short_link' => $link])->count() > 0) { $link = $this->makeShortLink(); } $entity->set('short_link', $link); } }
/** * Before Saving the entity, slug it. * @param Event $event * @param Entity $entity * @return void */ public function afterSave(Event $event, Entity $entity, $options) { $config = $this->config(); # load the config built by the instantiated behavior $original = $entity->get($config['field']); # manually store $original - wasn't working for some reason otherwise $entity->set($config['field'], $this->_generateSlug($entity)); # set the slug # if the slug is actually different than before - save it if ($entity->dirty() && $original != $entity->get($config['field'])) { $this->_table->save($entity); } }
/** * Before save * Transforma o valor de BRL para o formato SQL antes de salvar a entidade * no banco de dados * * @param Event $event Instância do evento * @param Entity $entity Instância da entidade a ser salva pelo ORM * @return bool * @access public */ public function beforeSave(Event $event, Entity $entity) { foreach ($this->_table->schema()->columns() as $campo) { $valor = $entity->get($campo); if (!empty($valor) && $this->_table->schema()->columnType($campo) === "float") { if (!is_string($valor) || preg_match('/^[0-9]+(\\.[0-9]+)?$/', $valor)) { continue; } $entity->set($campo, str_replace(['.', ','], ['', '.'], $valor)); } } return true; }
/** * Save also related model data * * @param \Cake\Event\Event * @param \Cake\ORM\Entity; * @return void */ public function beforeSave(Event $event, Entity $entity) { foreach ($this->config('fields') as $field => $mapped) { list($mappedTable, $mappedField) = explode('.', $mapped); if (!isset($this->_table->{$mappedTable}) || $this->_table->{$mappedTable}->isOwningSide($this->_table)) { throw new Exception(sprintf('Incorrect definition of related data to persist for %s', $mapped)); } // get related entity $related = $this->_table->{$mappedTable}->get($entity->get($this->_table->{$mappedTable}->foreignKey())); // set field value $entity->set($field, $related->get($mappedField)); } }
/** * beforeSave method * * @param Event $event The event * @param Entity $entity The entity * @param ArrayObject $options Array of options * @param ProfferPathInterface $path Inject an instance of ProfferPath * @return true * @throws Exception */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options, ProfferPathInterface $path = null) { foreach ($this->config() as $field => $settings) { if ($entity->has($field) && is_array($entity->get($field)) && $entity->get($field)['error'] === UPLOAD_ERR_OK) { // Allow path to be injected or set in config if (!empty($settings['pathClass'])) { $path = new $settings['pathClass']($this->_table, $entity, $field, $settings); } elseif (!isset($path)) { $path = new ProfferPath($this->_table, $entity, $field, $settings); } $event = new Event('Proffer.afterPath', $entity, ['path' => $path]); $this->_table->eventManager()->dispatch($event); if (!empty($event->result)) { $path = $event->result; } $path->createPathFolder(); if ($this->moveUploadedFile($entity->get($field)['tmp_name'], $path->fullPath())) { $entity->set($field, $path->getFilename()); $entity->set($settings['dir'], $path->getSeed()); // Only generate thumbnails for image uploads if (getimagesize($path->fullPath()) !== false && isset($settings['thumbnailSizes'])) { // Allow the transformation class to be injected if (!empty($settings['transformClass'])) { $imageTransform = new $settings['transformClass']($this->_table, $path); } else { $imageTransform = new ImageTransform($this->_table, $path); } $imageTransform->processThumbnails($settings); } } else { throw new Exception('Cannot upload file'); } } unset($path); } return true; }
public function matchUser(Entity $entity) { if (!empty($entity->user_id)) { return true; } $netId = $entity->net_id; if (empty($netId)) { return false; } $userId = TableRegistry::get('Users')->findOrCreateByNetId($netId); if (empty($userId)) { return false; } $entity->set('user_id', $userId); return true; }
public function slug(Entity $entity) { $config = $this->config(); $value = $entity->get($config['field']); $baseSlug = Inflector::slug(strtolower($value), $config['replacement']); //Append "-1", "-2", etc. if slug already exists $counter = 0; do { $slug = $baseSlug; if ($counter > 0) { $slug .= $config['replacement'] . $counter; } $counter++; $existing = $this->_table->find('slug', ['slug' => $slug])->first(); } while (!empty($existing)); $entity->set($config['slug'], $slug); }
public function testSpecialEnabledCallable() { $entityAction = new EntityAction('label', 'class', function ($e) { return ['controller' => 'Test', 'action' => 'test']; }, null, function (Entity $entity) { if ($entity->get('property') == 'enabled') { return true; } else { return false; } }); $entity = new Entity(); $entity->set('property', 'enabled'); $this->assertTrue($entityAction->isEnabled($entity)); $entity->set('property', 'disabled'); $this->assertFalse($entityAction->isEnabled($entity)); }
public function makeLink(Entity $entity) { if (!empty($entity->link)) { if (!empty($entity->params['link_options'])) { $link_options = (array) $entity->params['link_options']; if (isset($link_options[0])) { $id = $link_options[0]; unset($link_options[0]); $link_options[$id] = ''; } $entity->link = Router::url(['controller' => 'pages', 'action' => 'alerts']); } } else { $params = $entity->params; $params['link_options'] = array(); $entity->set('params', $params); } }
public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { $uploadedImages = $entities = []; $alias = $this->_table->registryAlias(); foreach ($entity->uploads as $image) { $uploadeImage = null; if (!empty($image['tmp_name'])) { $uploadeImage = $this->_upload($image['name'], $image['tmp_name']); } if (!empty($uploadeImage)) { $uploadedImages[] = $uploadeImage + ['model' => $this->_table->registryAlias()]; } } if (!empty($uploadedImages)) { foreach ($uploadedImages as $image) { $entities[] = $this->_uploadsTable->newEntity($image); } } $entity->set('uploads', $entities); }
/** * Decodes the fields of an array/entity (if the value itself was encoded) * * @param \Cake\ORM\Entity $entity * @param string $type Type (input/output) * @return void */ public function processItems(Entity $entity, $type = 'input') { $fields = $this->_config['fields']; foreach ($fields as $field => $map) { if (is_numeric($field)) { $field = $map; $map = []; } else { $map = (array) $map; } $val = $entity->get($field); if (!$val && !is_numeric($val)) { continue; } if (!$map) { $map = $this->_config[$type]; } if (!$map) { continue; } $entity->set($field, $this->_process($val, $map)); } }
/** * Tests that setitng an empty property name does nothing * * @expectedException \InvalidArgumentException * @dataProvider emptyNamesProvider * @return void */ public function testSetEmptyPropertyName($property) { $entity = new Entity(); $entity->set($property, 'bar'); }
/** * 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); }
/** * Takes an entity from the source table and looks if there is a field * matching the property name for this association. The found entity will be * saved on the target table for this association by passing supplied * `$options` * * @param \Cake\ORM\Entity $entity an entity from the source table * @param array|\ArrayObject $options options to be passed to the save method in * the target table * @return bool|Entity false if $entity could not be saved, otherwise it returns * the saved entity * @see Table::save() * @throws \InvalidArgumentException when the association data cannot be traversed. */ public function save(Entity $entity, array $options = []) { $targetEntities = $entity->get($this->property()); if (empty($targetEntities)) { return $entity; } if (!is_array($targetEntities) && !$targetEntities instanceof \Traversable) { $name = $this->property(); $message = sprintf('Could not save %s, it cannot be traversed', $name); throw new \InvalidArgumentException($message); } $properties = array_combine((array) $this->foreignKey(), $entity->extract((array) $this->source()->primaryKey())); $target = $this->target(); $original = $targetEntities; foreach ($targetEntities as $k => $targetEntity) { if (!$targetEntity instanceof Entity) { break; } if (!empty($options['atomic'])) { $targetEntity = clone $targetEntity; } $targetEntity->set($properties, ['guard' => false]); if ($target->save($targetEntity, $options)) { $targetEntities[$k] = $targetEntity; continue; } if (!empty($options['atomic'])) { $original[$k]->errors($targetEntity->errors()); $entity->set($this->property(), $original); return false; } } $entity->set($this->property(), $targetEntities); return $entity; }
/** * Helper method used to generated multiple translated field entities * out of the data found in the `_translations` property in the passed * entity. The result will be put into its `_i18n` property * * @param \Cake\ORM\Entity $entity Entity * @return void */ protected function _bundleTranslatedFields($entity) { $translations = (array) $entity->get('_translations'); if (empty($translations) && !$entity->dirty('_translations')) { return; } $primaryKey = (array) $this->_table->primaryKey(); $key = $entity->get(current($primaryKey)); foreach ($translations as $lang => $translation) { if (!$translation->id) { $update = ['id' => $key, 'locale' => $lang]; $translation->set($update, ['setter' => false]); } } $entity->set('_i18n', $translations); }
/** * Sets entity's order and updates order of other records when necessary. * * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that is going to be saved. * @param \ArrayObject $options The options passed to the save method. * * @return void */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { $config = $this->config(); $newOrder = null; $newScope = []; // If scope are specified and data for all scope fields is not // provided we cannot calculate new order if ($config['scope']) { $newScope = $entity->extract($config['scope']); if (count($newScope) !== count($config['scope'])) { return; } // Modify where clauses when NULL values are used foreach ($newScope as $field => $value) { if (is_null($value)) { $newScope[$field . ' IS'] = $value; unset($newScope[$field]); } } } $orderField = $config['order']; $newOrder = $entity->get($orderField); // Adding if ($entity->isNew()) { // Order not specified if ($newOrder === null) { // Insert at end of list $entity->set($orderField, $this->_getHighestOrder($newScope) + 1); // Order specified } else { // Increment order of records it's inserted before $this->_sync([$orderField => $this->_getUpdateExpression('+')], [$orderField . ' >=' => $newOrder], $newScope); } // Editing } else { // No action if no new order or scope specified if ($newOrder === null && !$newScope) { return; } list($oldOrder, $oldScope) = $this->_getOldValues($entity); // No action if new and old scope and order same if ($newOrder == $oldOrder && $newScope == $oldScope) { return; } // If changing scope if ($newScope && $newScope != $oldScope) { // Decrement records in old scope with higher order than moved record old order $this->_sync([$orderField => $this->_getUpdateExpression('-')], [$orderField . ' >' => $oldOrder], $oldScope); // Order not specified if ($newOrder === null) { // Insert at end of new scope $entity->set($orderField, $this->_getHighestOrder($newScope) + 1); // Order specified } else { // Increment records in new scope with higher order than moved record new order $this->_sync([$orderField => $this->_getUpdateExpression('+')], [$orderField . ' >=' => $newOrder], $newScope); } // Same scope } else { // If moving up if ($newOrder < $oldOrder) { // Increment order of those in between $this->_sync([$orderField => $this->_getUpdateExpression('+')], [$orderField . ' >=' => $newOrder, $orderField . ' <' => $oldOrder], $newScope); // Moving down } else { // Decrement order of those in between $this->_sync([$orderField => $this->_getUpdateExpression('-')], [$orderField . ' >' => $oldOrder, $orderField . ' <=' => $newOrder], $newScope); } } } }
/** * Update a field, if it hasn't been updated already * * @param \Cake\ORM\Entity $entity Entity instance. * @param string $field Field name * @param bool $refreshTimestamp Whether to refresh timestamp. * @return void */ protected function _updateField(Entity $entity, $field, $refreshTimestamp) { if ($entity->dirty($field)) { return; } $entity->set($field, $this->timestamp(null, $refreshTimestamp)); }
/** * testFormValidationMultiRecord method * * test form error display with multiple records. * * @return void */ public function testFormValidationMultiRecord() { $one = new Entity(); $two = new Entity(); TableRegistry::get('Contacts', ['className' => __NAMESPACE__ . '\\ContactsTable']); $one->set('email', ''); $one->errors('email', ['invalid email']); $two->set('name', ''); $two->errors('name', ['This is wrong']); $this->Form->create([$one, $two], ['context' => ['table' => 'Contacts']]); $result = $this->Form->input('0.email'); $expected = ['div' => ['class' => 'input email error'], 'label' => ['for' => '0-email'], 'Email', '/label', 'input' => ['type' => 'email', 'name' => '0[email]', 'id' => '0-email', 'class' => 'form-error', 'maxlength' => 255, 'value' => ''], ['div' => ['class' => 'error-message']], 'invalid email', '/div', '/div']; $this->assertHtml($expected, $result); $result = $this->Form->input('1.name'); $expected = ['div' => ['class' => 'input text error'], 'label' => ['for' => '1-name'], 'Name', '/label', 'input' => ['type' => 'text', 'name' => '1[name]', 'id' => '1-name', 'class' => 'form-error', 'maxlength' => 255, 'value' => ''], ['div' => ['class' => 'error-message']], 'This is wrong', '/div', '/div']; $this->assertHtml($expected, $result); }
/** * Hashing the password and whitelisting * * @param \Cake\Event\Event $event * @param \Cake\ORM\Entity $entity * @throws \Exception * @return void */ public function beforeSave(Event $event, Entity $entity) { $formField = $this->_config['formField']; $field = $this->_config['field']; if ($entity->get($formField) !== null) { $cost = !empty($this->_config['hashCost']) ? $this->_config['hashCost'] : 10; $options = ['cost' => $cost]; /** @var \Cake\Auth\AbstractPasswordHasher $PasswordHasher */ $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher'], $options); $entity->set($field, $PasswordHasher->hash($entity->get($formField))); if (!$entity->get($field)) { throw new Exception('Empty field'); } $entity->unsetProperty($formField); //$entity->set($formField, null); if ($this->_config['confirm']) { $formFieldRepeat = $this->_config['formFieldRepeat']; $entity->unsetProperty($formFieldRepeat); //unset($Model->data[$table->alias()][$formFieldRepeat]); } if ($this->_config['current']) { $formFieldCurrent = $this->_config['formFieldCurrent']; $entity->unsetProperty($formFieldCurrent); //unset($Model->data[$table->alias()][$formFieldCurrent]); } } }
/** * Ensures that the provided entity contains non-empty values for the left and * right fields * * @param \Cake\ORM\Entity $entity The entity to ensure fields for * @return void */ protected function _ensureFields($entity) { $config = $this->config(); $fields = [$config['left'], $config['right']]; $values = array_filter($entity->extract($fields)); if (count($values) === count($fields)) { return; } $fresh = $this->_table->get($entity->get($this->_getPrimaryKey()), $fields); $entity->set($fresh->extract($fields), ['guard' => false]); foreach ($fields as $field) { $entity->dirty($field, false); } }
/** * Restore original (unencrypted) values after saving to DB * @param Event $event Event object * @param Entity $entity Entity object * @param ArrayObject $options Save options array * @return void */ public function afterSave(Event $event, Entity $entity, ArrayObject $options) { if ($entity->has('_cyphered') && is_array($entity->_cyphered)) { foreach ($entity->_cyphered as $field => $value) { $entity->set($field, $value); $entity->clean(); } unset($entity->_cyphered); } }