/** * Method that renders Entity values through Field Handler Factory. * * @param Cake\ORM\Entity $entity Entity instance * @param Cake\ORM\Table|string $table Table instance * @param array $fields Fields to prettify * @return void */ protected function _prettify(Entity $entity, $table, array $fields = []) { if (!$this->__fhf instanceof FieldHandlerFactory) { $this->__fhf = new FieldHandlerFactory(); } if (empty($fields)) { $fields = array_keys($entity->toArray()); } foreach ($fields as $field) { // handle belongsTo associated data if ($entity->{$field} instanceof Entity) { $tableName = $table->association($entity->{$field}->source())->className(); $this->_prettify($entity->{$field}, $tableName); } // handle hasMany associated data if (is_array($entity->{$field})) { if (empty($entity->{$field})) { continue; } foreach ($entity->{$field} as $associatedEntity) { if (!$associatedEntity instanceof Entity) { continue; } $tableName = $table->association($associatedEntity->source())->className(); $this->_prettify($associatedEntity, $tableName); } } $renderOptions = ['entity' => $entity]; $entity->{$field} = $this->__fhf->renderValue($table instanceof Table ? $table->registryAlias() : $table, $field, $entity->{$field}, $renderOptions); } }
public function __construct(Table $table, Entity $entity, $field, array $settings) { $this->setRoot(TMP . 'ProfferTests'); $this->setTable($table->alias()); $this->setField($field); $this->setSeed('proffer_test'); if (isset($settings['thumbnailSizes'])) { $this->setPrefixes($settings['thumbnailSizes']); } $this->setFilename($entity->get($field)); }
/** * Generate unique slug by field. * * @param Entity $entity * @return mixed|string */ protected function _generateUniqueSlug(Entity $entity) { $conditions = []; $slug = $entity->get($this->_config['slug'], ''); if ($this->_config['unique']) { $conditions[$this->_config['slug'] . ' LIKE'] = $slug . '%'; } if ($id = $entity->get('id', false)) { $conditions[$this->_table->primaryKey() . ' !='] = $id; } if (empty($slug)) { $slug = $entity->get($this->_config['field'], 'Title'); } if ($this->_config['translate']) { $Slug = new Slug(); $slug = $Slug->create($slug); } $duplicates = $this->_table->find()->where($conditions)->toArray(); if (!empty($duplicates)) { $duplicates = $this->_extractSlug($duplicates); if (!in_array($slug, $duplicates)) { return $slug; } $index = 1; $startSlug = $slug; while ($index > 0) { if (!in_array($startSlug . $this->_config['separator'] . $index, $duplicates)) { $slug = $startSlug . $this->_config['separator'] . $index; $index = -1; } $index++; } } return $slug; }
/** * Check if there is some files to upload and modify the entity before * it is saved. * * At the end, for each files to upload, unset their "virtual" property. * * @param Event $event The beforeSave event that was fired. * @param Entity $entity The entity that is going to be saved. * * @throws \LogicException When the path configuration is not set. * @throws \ErrorException When the function to get the upload path failed. * * @return void */ public function beforeSave(Event $event, Entity $entity) { $config = $this->_config; foreach ($config['fields'] as $field => $fieldOption) { $data = $entity->toArray(); $virtualField = $field . $config['suffix']; if (!isset($data[$virtualField]) || !is_array($data[$virtualField])) { continue; } $file = $entity->get($virtualField); if ((int) $file['error'] === UPLOAD_ERR_NO_FILE) { continue; } if (!isset($fieldOption['path'])) { throw new \LogicException(__('The path for the {0} field is required.', $field)); } if (isset($fieldOption['prefix']) && (is_bool($fieldOption['prefix']) || is_string($fieldOption['prefix']))) { $this->_prefix = $fieldOption['prefix']; } $extension = (new File($file['name'], false))->ext(); $uploadPath = $this->_getUploadPath($entity, $fieldOption['path'], $extension); if (!$uploadPath) { throw new \ErrorException(__('Error to get the uploadPath.')); } $folder = new Folder($this->_config['root']); $folder->create($this->_config['root'] . dirname($uploadPath)); if ($this->_moveFile($entity, $file['tmp_name'], $uploadPath, $field, $fieldOption)) { if (!$this->_prefix) { $this->_prefix = ''; } $entity->set($field, $this->_prefix . $uploadPath); } $entity->unsetProperty($virtualField); } }
/** * 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'); }
/** * Validates a single entity by getting the correct validator object from * the table and traverses associations passed in $options to validate them * as well. * * @param \Cake\ORM\Entity $entity The entity to be validated * @param array|\ArrayObject $options options for validation, including an optional key of * associations to also be validated. * @return bool true if all validations passed, false otherwise */ public function one(Entity $entity, $options = []) { $valid = true; $types = [Association::ONE_TO_ONE, Association::MANY_TO_ONE]; $propertyMap = $this->_buildPropertyMap($options); $options = new ArrayObject($options); foreach ($propertyMap as $key => $assoc) { $value = $entity->get($key); $association = $assoc['association']; if (!$value) { continue; } $isOne = in_array($association->type(), $types); if ($isOne && !$value instanceof Entity) { $valid = false; continue; } $validator = $association->target()->entityValidator(); if ($isOne) { $valid = $validator->one($value, $assoc['options']) && $valid; } else { $valid = $validator->many($value, $assoc['options']) && $valid; } } if (!isset($options['validate'])) { $options['validate'] = true; } return $this->_processValidation($entity, $options) && $valid; }
/** * 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; }
public function getFilePath(Entity $entity, $path, $extension) { $id = $entity->get('id'); $path = trim($path, '/'); $replace = ['%id1000' => ceil($id / 1000), '%id100' => ceil($id / 100), '%id' => $id, '%y' => date('y'), '%m' => date('m')]; $path = strtr($path, $replace) . '.' . $extension; return $path; }
/** * Get resource attributes. * * @param \Cake\ORM\Entity $resource Entity resource * @return array */ public function getAttributes($resource) { if ($resource->has($this->idField)) { $hidden = array_merge($resource->hiddenProperties(), [$this->idField]); $resource->hiddenProperties($hidden); } return $resource->toArray(); }
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); }
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; } }
/** * 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; }
/** * Constructor * * @param \Cake\ORM\Entity $entity Entity * @param int $code code to report to client */ public function __construct(Entity $entity, $code = 422) { $this->_validationErrors = array_filter((array) $entity->errors()); $flat = Hash::flatten($this->_validationErrors); $errorCount = $this->_validationErrorCount = count($flat); $this->message = __dn('crud', 'A validation error occurred', '{0} validation errors occurred', $errorCount, [$errorCount]); parent::__construct($this->message, $code); }
/** * Render ajax toggle element. * * @param array|string $url * @param array $data * @param Entity|\Cake\ORM\Entity $entity * @return string */ public function toggle($entity, $url = [], array $data = []) { if (empty($url)) { $url = ['action' => 'toggle', 'prefix' => $this->request->param('prefix'), 'plugin' => $this->request->param('plugin'), 'controller' => $this->request->param('controller'), (int) $entity->get('id'), (int) $entity->get('status')]; } $data = Hash::merge(['url' => $url, 'entity' => $entity], $data); return $this->_View->element(__FUNCTION__, $data); }
/** * 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 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'])); }
/** * 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(); } } }
/** * 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')); }
/** * 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 } }
/** * {@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 deleteOldUpload(Entity $entity, $field) { $file = $entity->get($field); if (empty($file)) { return true; } if (file_exists(WWW_ROOT . $file)) { unlink(WWW_ROOT . $file); } }
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 } } } } }
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); }
/** * @param Entity $page * * @return \Symfony\Component\Form\Form * @throws \Rad\DependencyInjection\Exception\ServiceNotFoundException */ public static function getForm($page = null) { $data = null; if ($page) { $data = $page->toArray(); } $action = $page ? Container::get('router')->generateUrl(['pages', $data['slug']]) : Container::get('router')->generateUrl(['pages']); $formFactory = Forms::createFormFactory(); $options = ['action' => $action, 'method' => $page ? 'PUT' : 'POST']; return $formFactory->createBuilder('form', $data, $options)->add('title', 'text', ['required' => true, 'attr' => ['class' => 'form-control']])->add('slug', 'text', ['required' => true, 'attr' => ['class' => 'form-control']])->add('body', 'textarea', ['required' => true, 'attr' => ['class' => 'form-control wysiwyg']])->add('submit', 'submit')->getForm(); }
/** * * @param \Cake\Event\Event $event * @param \Cake\ORM\Entity $entity * @param \ArrayObject $options * @return void */ public function afterSave(Event $event, Entity $entity, \ArrayObject $options) { if (!empty($entity->thumb->name)) { $file = $entity->thumb; $mediaId = $entity->media_id; if ($mediaId != 0) { $entity->Media->delete($mediaId); } $entity->Media->save(['ref_id' => $entity->id, 'ref' => $entity->name, 'file' => $file]); $entity->saveField('media_id', $entity->Media->id); } }
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); } }
/** * Generates an image tag that handle multiple sizes and rendered with picturefill * * ``` * $options = [ * 'sizes' => '(min-width: 40em) 80vw, 100vw' * 'srcset' => [375, 480, 780] * ] * ``` * * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved * @param array $options picturefill options * @return string */ public function picturefill(Entity $entity, array $options) { $srcset = ''; foreach ($options['srcset'] as $size) { $src = $entity->getUrl(['w' => $size]); $src .= " " . $size . "w"; $srcset[] = $src; } $options['srcset'] = implode(" ,", $srcset); $picturefill = $this->Html->image($entity->getUrl($options), $options); $selfLoad = $this->Require->module('picturefill'); return $picturefill . $selfLoad; }
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; } } }
/** * 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; }
public function afterSave(Event $event, Entity $entity, $options) { $config = $this->_config; foreach ($config['fields'] as $fieldKey => $fieldValue) { $filePath = $entity->get($fieldKey); if (!empty($filePath)) { foreach ($fieldValue as $fieldTypeKey => $fieldTypeValue) { $type = $fieldTypeValue['type']; $this->{$type}($fieldTypeValue, $filePath); } } } }