public function deletar(Model $Model, $id, $cascade = false) { if ($Model->hasAny(array($Model->primaryKey => $id))) { return $Model->delete($id, $cascade); } throw new NotFoundException($Model->useLogger("Erro: impossível fazer a operação")); }
public function testMultipleUploadSaveReadDelete() { // setup $this->Model->Behaviors->load('Media.Attachable', array()); $this->Model->configureAttachment(array('files' => array('baseDir' => $this->attachmentDir, 'multiple' => true, 'removeOnOverwrite' => true)), true); $data = array($this->Model->alias => array('title' => 'My Upload', 'files_upload' => array($this->upload1, $this->upload2))); // save $this->Model->create(); $result = $this->Model->save($data); $this->assertTrue(isset($this->Model->id)); $this->assertEqual($result[$this->Model->alias]['files_upload'], ''); $this->assertEqual(preg_match('/Upload_File_1_([0-9a-z]+).txt,Upload_File_2_([0-9a-z]+).txt$/', $result[$this->Model->alias]['files']), 1); $this->assertTrue(isset($result['Attachment']['files'][0]['path'])); $this->assertTrue(file_exists($result['Attachment']['files'][0]['path'])); $this->assertTrue(isset($result['Attachment']['files'][1]['path'])); $this->assertTrue(file_exists($result['Attachment']['files'][1]['path'])); // read $modelId = $this->Model->id; $this->Model->create(); $result = $this->Model->read(null, $modelId); $this->assertTrue(isset($result[$this->Model->alias]['files'])); $this->assertTrue(!isset($result[$this->Model->alias]['files_upload'])); $this->assertEqual(preg_match('/Upload_File_1_([0-9a-z]+).txt,Upload_File_2_([0-9a-z]+).txt$/', $result[$this->Model->alias]['files']), 1); $this->assertTrue(isset($result['Attachment']['files'][0]['path'])); $this->assertTrue(file_exists($result['Attachment']['files'][0]['path'])); $this->assertTrue(isset($result['Attachment']['files'][1]['path'])); $this->assertTrue(file_exists($result['Attachment']['files'][1]['path'])); //delete $deleted = $this->Model->delete($this->Model->id); $this->assertTrue($deleted, 'Failed to delete Attachment'); $this->assertTrue(!file_exists($result['Attachment']['files'][0]['path']), 'Attachment not deleted'); $this->assertTrue(!file_exists($result['Attachment']['files'][1]['path']), 'Attachment not deleted'); }
function beforeDelete($cascade) { // Remove the extended data to be tidy. // First get the type id App::Import('Model', 'Type'); $Type = new Type(); $Type->recursive = -1; $type_record = Set::extract('/Type/id', $Type->find('first', array('fields' => array('Type.id'), 'conditions' => array('Type.alias' => $this->model->data['Node']['type'])))); $type_id = $type_record[0]; // Cool, now find all node schemas App::Import('Model', 'NodeSchema.NodeSchema'); $NodeSchema = new NodeSchema(); $NodeSchema->actsAs = array('Containable'); $schemas = $NodeSchema->find('all', array('fields' => array('NodeSchema.table_name'), 'contains' => array('Type' => array('conditions' => array('Type.id' => $type_id))))); // Now loop through and check for records on those tables to remove if (is_array($schemas) && count($schemas) > 0) { foreach ($schemas as $schema) { $table_name = $schema['NodeSchema']['table_name']; $model = new Model(false, $table_name); $model->primaryKey = 'node_id'; // set the primary key to the node_id if ($model->delete($this->model->data['Node']['id'], false)) { return true; } else { // return false; // There was some sort of error deleting the associated data. Do we even need this? It doesn't redirect, it stops. Have to handle the error. } } } return true; }
/** * Callback * * Requires `file` field to be present if a record is created. * * Handles deletion of a record and corresponding file if the `delete` field is * present and has not a value of either `null` or `'0'.` * * Prevents `dirname`, `basename`, `checksum` and `delete` fields to be written to * database. * * Parses contents of the `file` field if present and generates a normalized path * relative to the path set in the `baseDirectory` option. * * @param Model $Model * @return boolean */ function beforeSave(&$Model) { if (!$Model->exists()) { if (!isset($Model->data[$Model->alias]['file'])) { unset($Model->data[$Model->alias]); return true; } } else { if (isset($Model->data[$Model->alias]['delete']) && $Model->data[$Model->alias]['delete'] !== '0') { $Model->delete(); unset($Model->data[$Model->alias]); return true; } } $blacklist = array('dirname', 'basename', 'checksum', 'delete'); $whitelist = array('id', 'file', 'model', 'foreign_key', 'created', 'modified', 'alternative'); foreach ($Model->data[$Model->alias] as $key => $value) { if (in_array($key, $whitelist)) { continue; } if (in_array($key, $blacklist)) { unset($Model->data[$Model->alias][$key]); } } extract($this->settings[$Model->alias]); if (isset($Model->data[$Model->alias]['file'])) { $File = new File($Model->data[$Model->alias]['file']); /* `baseDirectory` may equal the file's directory or use backslashes */ $dirname = substr(str_replace(str_replace('\\', '/', $baseDirectory), null, str_replace('\\', '/', Folder::slashTerm($File->Folder->pwd()))), 0, -1); $result = array('dirname' => $dirname, 'basename' => $File->name); $Model->data[$Model->alias] = array_merge($Model->data[$Model->alias], $result); } return true; }
function delete() { $delete_result = parent::delete(); $task = new Task($this->task_id); $task->update_total_time(); return $delete_result; }
/** * Удаляет текущую запись */ public function destroy() { //Делаем запрос на удаление $this->_model_instance->delete($this->{$this->_pkey}); //Если есть связь с другими таблицами if ($this->_has_many) { foreach ($this->_has_many as $table) { //Строим название модели $model = "Model_" . ucfirst($table); /** * Получаем объект записи * @var $model Model */ $model = new $model(); //Ищем объекты $rows = $model->where(array($this->_table . "_id" => $this->{$this->_pkey}))->row_all(); if ($rows) { /** * @var $row Model_Row */ foreach ($rows as $row) { $row->destroy(); } } } } }
/** * @param int $id * @throws DbalException * @return array */ public function deleteById($id) { if (!intval($id)) { throw new DbalException('Id required'); } return $this->model->delete($this->table, $this->idColum, intval($id)); }
public function delete($id = null, $cascade = true) { $result = parent::delete($id, $cascade); if ($result === false && $this->Behaviors->enabled('SoftDelete')) { return $this->field('deleted', array('deleted' => 1)); } return $result; }
public function delete() { //delete all our tokens db()->execute("\n\t\t\t\tDELETE FROM oauth_token WHERE consumer_id = {$this->id}\n\t\t\t"); //delete all our nonces db()->execute("\n\t\t\t\tDELETE FROM oauth_token_nonce WHERE consumer_id = {$this->id}\n\t\t\t"); parent::delete(); }
public function delete() { if ($this->isHydrated()) { $s3 = new S3(AMAZON_AWS_KEY, AMAZON_AWS_SECRET); $s3->deleteObject($this->get('bucket'), $this->get('path')); } parent::delete(); }
/** * Deletes a server */ public function delete($server_id) { # Deletes invoice upon invoice id global $main; $this->setId($server_id); parent::delete(); $main->addLog("server:delete id #{$id} deleted "); return true; }
/** * Delete a particular item from the model. * @param $params * @return unknown_type */ public function delete($params) { if (User::getPermission($this->permissionPrefix . "_can_delete")) { $data = $this->model->getWithField($this->model->getKeyField(), $params[0]); $this->model->delete($this->model->getKeyField(), $params[0]); User::log("Deleted " . $this->model->name, $data[0]); Application::redirect("{$this->urlPath}?notification=Successfully+deleted+" . strtolower($this->label)); } }
/** * delete() should return self if model does have id */ public function test_delete_returnsSelf_ifModelDoesHaveId() { $client = new Api\Client(); $model = new Model($client); $model->id = 1; $model->delete(); $this->assertNull($model->id); return; }
public static function destroy($id) { //construct query to delete $sql = 'DELETE FROM posts WHERE id = ' . $id; //send that query to the Model class that Posts extends $results = Model::delete($sql); //return results to controller return $results; }
public function delete() { $_where = array("id='{$this->_R['id']}'"); $_service = parent::select(array('first'), array('where' => $_where, 'limit' => '1')); if ($_service[0]->first == 1) { return 0; } else { return parent::delete($_where); } }
/** * Delete a skill profile * @param int $id The skill profile id * @return boolean Whether delete a skill profile */ public function delete($id) { Database::delete( $this->table_rel_profile, array( 'profile_id' => $id ) ); return parent::delete($id); }
public function handleDelete($id) { Model::delete($id, "authorId", "authors"); $array = dibi::query('SELECT workId FROM works WHERE author=%i', $id)->fetchAssoc(); foreach ($array as $val) { FileModel::deleteFiles($val['workId']); } Model::delete($id, "author", "works"); $this->redirect('this'); }
/** * Deletes current record * * @access protected * @return booelan */ function _fixDeleteRecord() { $input = $this->in('Delete record?', 'y,n', $this->_answer); if ($input == 'y') { $this->_Model->delete($this->__dbItem['id']); $this->out('Record deleted'); return true; } return false; }
/** * Delete wiki page, revisions and timeline events. */ public function delete() { foreach ($this->revisions()->fetchAll() as $revision) { $revision->delete(); } $timelineEvents = Timeline::select()->where("owner_type = :ownerType")->andWhere('owner_id = :ownerId')->setParameter(':ownerType', 'WikiPage')->setParameter(':ownerId', $this['id'])->fetchAll(); foreach ($timelineEvents as $event) { $event->delete(); } return parent::delete(); }
public function delete($id = null, $cascade = true) { if ($this->table != 'cake_sessions') { $this->useDbConfig = 'master'; } $status = parent::delete($id, $cascade); if (!isset($_SERVER['FORCEMASTER']) && $this->table != 'cake_sessions') { $this->useDbConfig = 'default'; } return $status; }
/** * {@inheritDoc} */ public function delete($id = null, $cascade = true) { $e = null; if ($this->_stopwatch) { $e = $this->_getStopwatchEvent('delete'); } $result = parent::delete($id, $cascade); if ($e !== null) { $e->stop(); } return $result; }
/** * routineDrop * */ public function routineDrop(Model $model, $id, $conditions = array()) { $conditions["{$model->alias}.{$model->primaryKey}"] = $id; $current = $model->find('first', array('conditions' => $conditions)); if (empty($current)) { throw new NotFoundException(__('Invalid Access')); } // for SoftDeletable $model->set($current); $model->delete($id); $count = $model->find('count', array('conditions' => array("{$model->alias}.{$model->primaryKey}" => $id))); return $count === 0; }
/** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { $this->document->delete(); $this->view->delete(); $this->layout->delete(); $this->documentType->delete(); $this->user->delete(); unset($this->document); unset($this->view); unset($this->layout); unset($this->documentType); unset($this->user); unset($this->object); }
/** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ public function tearDown() { StaticEventManager::resetInstance(); ModuleModel::uninstall(Registry::get('Application')->getServiceManager()->get('CustomModules')->getModule('Blog'), ModuleModel::fromName('Blog')); $this->document->delete(); $this->view->delete(); $this->layout->delete(); $this->documentType->delete(); unset($this->document); unset($this->object); unset($this->view); unset($this->layout); unset($this->documentType); parent::tearDown(); }
/** * Override delete() to use the softDelete() method from behavior * Much better results than using beforeDelete() as you can return true * and use the protected methods for deleting related records * Bring on traits! * @param int $id Record ID to be deleted * @param boolean $cascade Whether to delete related records * @return boolean Whether the delete was successful */ public function delete($id = null, $cascade = true) { if ($this->Behaviors->hasMethod('softDelete')) { if ($cascade) { // Can't call these from behavior as they're protected // Delete related models marked as dependent $this->_deleteDependent($id, $cascade); // Delete HABTM links - Bad idea? // $this->_deleteLinks($id); } return $this->softDelete($id, $cascade); } else { return parent::delete($id, $cascade); } }
/** * Generic delete action * * Triggers the following callbacks * - beforeFind * - recordNotFound * - beforeDelete * - afterDelete * * @param string $id * @return void */ protected function _deleteAction($id = null) { if (empty($id)) { $id = $this->getIdFromRequest(); } $this->_validateId($id); if (!$this->_request->is('delete') && !($this->_request->is('post') && false === $this->config('secureDelete'))) { $subject = $this->_getSubject(compact('id')); $this->_setFlash('invalid_http_request.error'); return $this->_redirect($subject, $this->_controller->referer(array('action' => 'index'))); } $query = array(); $query['conditions'] = array($this->_model->escapeField() => $id); $findMethod = $this->_getFindMethod(null, 'count'); $subject = $this->trigger('beforeFind', compact('id', 'query', 'findMethod')); $query = $subject->query; $count = $this->_model->find($subject->findMethod, $query); if (empty($count)) { $subject = $this->trigger('recordNotFound', compact('id')); $this->_setFlash('find.error'); return $this->_redirect($subject, $this->_controller->referer(array('action' => 'index'))); } $subject = $this->trigger('beforeDelete', compact('id')); if ($subject->stopped) { $this->_setFlash('delete.error'); return $this->_redirect($subject, $this->_controller->referer(array('action' => 'index'))); } if ($this->_model->delete($id)) { $this->_setFlash('delete.success'); $subject = $this->trigger('afterDelete', array('id' => $id, 'success' => true)); } else { $this->_setFlash('delete.error'); $subject = $this->trigger('afterDelete', array('id' => $id, 'success' => false)); } return $this->_redirect($subject, $this->_controller->referer(array('action' => 'index'))); }
/** * 論理削除に対応した拡張版削除メソッド。(p.137) * * 既定のdelete()は * delete($id = null, $cascade = true) * ですが、論理削除を行うかどうかのオプション値を追加するために、 * 第二引数を $option = array() としました。もちろん従来通り * 第二引数に $cascade を送ってもらっても良いように対応しています。 * * #### Options * - cascade: Set to true to delete records that depend on this record * - logicalDelete: 論理削除を行うか。(初期値:false) * * @param type $id 削除対象レコードのID * @param type $option オプション値。または$cascade * @return boolean True on success * @throws FatalErrorException 論理削除を行う指定なのに、論理削除Behaviorの利用宣言がされていない。 */ public function delete($id = null, $option = array()) { // デフォルトオプションに指定オプションを上書き $defaultOpt = array('cascade' => true, 'logicalDelete' => false); if (is_bool($option)) { // 既存の呼び出し方式の場合 $defaultOpt['cascade'] = $option; $option = array(); } $option = array_merge($defaultOpt, $option); // DBアクセス処理呼び出し if ($option['logicalDelete']) { if (function_exists($this, 'logicalDelete')) { // 論理削除 $sts = $this->logicalDelete($id); } else { throw new FatalErrorException('MyDeleterBehaviorが導入されてないのでは?'); } } else { // 物理削除 $sts = parent::delete($id, $option['cascade']); } return $sts; }
/** * Method called on the destruction of a database session. * * @param int $id ID that uniquely identifies session in database * @return bool True for successful delete, false otherwise. */ public function destroy($id) { return $this->_model->delete($id); }
/** * Validates token * * @param string $field action * @param string $token Token * * @return mixed false or user data */ public function verifyToken(Model $Model, $token = null) { if (empty($token)) { throw new InvalidArgumentException('Invalid arguments'); } $Model->Tokenization->deleteAll(array($Model->Tokenization->alias . '.expire < NOW()')); $match = $Model->Tokenization->find('first', array('conditions' => array($Model->Tokenization->alias . '.token' => $token), 'contain' => array($Model->alias))); if (!empty($match)) { $expire = strtotime($match[$Model->Tokenization->alias]['expire']); if ($expire > time()) { return $match[$Model->alias][$Model->primaryKey]; } else { $Model->delete($match[$Model->alias]['id']); } } return false; }
/** * Delete downloads when deleting product collection item * * @return int */ public function delete() { $intId = $this->id; $intAffected = parent::delete(); if ($intAffected) { \Database::getInstance()->query("DELETE FROM tl_iso_product_collection_download WHERE pid={$intId}"); } return $intAffected; }