Exemplo n.º 1
0
 public function save(\Api\Entity\Post $post)
 {
     $hydrator = $this->getHydrator();
     $action = null;
     $postData = array('title' => $post->getTitle(), 'description' => $post->getDescription());
     if ($post->getId()) {
         $action = new Update('posts');
         $action->set($postData);
         $action->where(array('id = ?' => $post->getId()));
     } else {
         $postData['author_id'] = $post->getAuthorId();
         $action = new Insert('posts');
         $action->values($postData);
     }
     $sql = new Sql($this->getAdaptor());
     $statement = $sql->prepareStatementForSqlObject($action);
     $result = $statement->execute();
     if ($result instanceof ResultInterface) {
         if ($pk = $result->getGeneratedValue()) {
             $post->setId($pk);
         }
         return $this->getPost($post->getId());
     }
     throw new \Exception('something went wrong.Please try again later');
 }
Exemplo n.º 2
0
 public function updateRow($id, $updateArray)
 {
     $update = new Update($this->getTable());
     $update->set($updateArray);
     $update->where->equalTo('id', $id);
     return $this->updateWith($update);
 }
 public function setRequest($id)
 {
     if ($id == $this->user_id) {
         return true;
     }
     $user = $this->getUserById($id);
     if (is_array($user)) {
         if ($user["friendship"] == -1) {
             //insert
             $insert = new Insert('fg_friends');
             $newData = array('user_one' => $this->user_id, 'user_two' => $id, 'state' => '0');
             $insert->values($newData);
             $statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($insert);
             $resultSet = $statement->execute();
         } else {
             if (!$user["i_am_adder"] && $user["friendship"] == 0) {
                 //update
                 $update = new Update('fg_friends');
                 $newData = array('state' => '1');
                 $update->set($newData);
                 $update->where(array('user_one' => $id, 'user_two' => $this->user_id));
                 $statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($update);
                 $resultSet = $statement->execute();
             }
         }
         return true;
     }
     return false;
 }
Exemplo n.º 4
0
 /**
  * {@inheritDoc}
  */
 public function save(PostInterface $postObject)
 {
     $postData = $this->hydrator->extract($postObject);
     unset($postData['id']);
     // Neither Insert nor Update needs the ID in the array
     if ($postObject->getId()) {
         // ID present, it's an Update
         $action = new Update('post');
         $action->set($postData);
         $action->where(array('id = ?' => $postObject->getId()));
     } else {
         // ID NOT present, it's an Insert
         $action = new Insert('post');
         $action->values($postData);
     }
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepareStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         if ($newId = $result->getGeneratedValue()) {
             // When a value has been generated, set it on the object
             $postObject->setId($newId);
         }
         return $postObject;
     }
     throw new \Exception("Database error");
 }
 public function deleteOtherFeedPosts($feedId, array $postIds)
 {
     $Update = new Update(self::$_tableName);
     $Update->set([STATUS_COLUMN_NAME => 0]);
     $Update->where->addPredicate(new NotIn('foreign_id', $postIds))->equalTo('feed', $feedId);
     $affectedRows = $this->updateWith($Update);
     return $affectedRows;
 }
 /**
  * @param Update $update
  */
 public function preUpdate(Update $update)
 {
     $metaColumns = $this->tableGateway->getColumns();
     if (count($metaColumns)) {
         $metaColumns = array_flip($metaColumns);
         $set = $update->getRawState('set');
         $set = array_intersect_key($set, $metaColumns);
         $update->set($set);
     }
 }
Exemplo n.º 7
0
 /**
  * 
  * @param string $userID
  * @return User
  */
 public function updateUser(User $userObject)
 {
     $postData = $this->hydrator->extract($userObject);
     $action = new Update('user');
     $action->set($postData);
     $action->where(array('userID = ?' => $userObject->getUserID()));
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepareStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         //             if ($newId = $result->getGeneratedValue()) {
         //                 // When a value has been generated, set it on the object
         //                 $postObject->setId($newId);
         //             }
         return true;
     }
 }
Exemplo n.º 8
0
 public function update(\Api\Entity\User $user)
 {
     $hydrator = $this->getHydrator();
     $postData = array('display_name' => $user->getDisplayName(), 'password' => $user->getPassword());
     $update = new Update('user');
     $update->set($postData);
     $update->where(array('user_id = ?' => $user->getUserId()));
     $sql = new Sql($this->getAdaptor());
     $statement = $sql->prepareStatementForSqlObject($update);
     $result = $statement->execute();
     if ($result instanceof ResultInterface) {
         if ($pk = $result->getGeneratedValue()) {
             $user->setUserId($pk);
         }
         return $this->getUser($user->getUserId());
     }
     throw new \Exception('something went wrong.Please try again later');
 }
Exemplo n.º 9
0
 /**
  * @throws Exception\RecordNotSavedException
  */
 public function update(array $columnsValuesPairs)
 {
     $update = new ZfSql\Update($this->tableName);
     $update->set($columnsValuesPairs);
     $adapter = $this->sql->getAdapter();
     if ($this->select->where) {
         $update->where($this->select->where);
     }
     $sqlString = $this->sql->getSqlStringForSqlObject($update);
     try {
         $result = $adapter->query($sqlString, $adapter::QUERY_MODE_EXECUTE);
     } catch (AdapterException\ExceptionInterface $e) {
         throw new Exception\RecordNotSavedException($e->getMessage(), 0, $e);
     }
     if (!$result->count()) {
         throw new Exception\RecordNotSavedException("No rows were affected");
     }
     return true;
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function save(PostInterface $postObject)
 {
     $postData = $this->hydrator->extract($postObject);
     unset($postData['id']);
     if ($postObject->getId()) {
         $action = new Update('posts');
         $action->set($postData);
         $action->where(['id = ?' => $postObject->getId()]);
     } else {
         $action = new Insert('posts');
         $action->values($postData);
     }
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepareStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         if ($newId = $result->getGeneratedValue()) {
             $postObject->setId($newId);
         }
         return $postObject;
     }
     throw new \Exception("Database error.");
 }
Exemplo n.º 11
0
 /**
  * @param Route $model
  *
  * @return Route
  * @throws \Exception
  */
 public function save(Route $model) : Route
 {
     $modelData = $this->hydrator->extract($model);
     if ($model->getId()) {
         $action = new Update($this->table);
         $action->set($modelData);
         $action->where(['id = ?' => $model->getId()]);
     } else {
         $action = new Insert($this->table);
         $action->values($modelData);
     }
     $sql = new Sql($this->dbAdapter);
     $statement = $sql->prepareStatementForSqlObject($action);
     $result = $statement->execute();
     if (!$result instanceof ResultInterface) {
         throw new \Exception('Database Error');
     }
     if ($newId = $result->getGeneratedValue()) {
         $model->setId($newId);
     }
     return $model;
 }
 public function updateDefaultByName($user_id, $table, $data)
 {
     $update = new Update($this->table);
     unset($data['id']);
     unset($data['title']);
     unset($data['table_name']);
     unset($data['user']);
     if (!isset($data) || !is_array($data)) {
         $data = array();
     }
     $update->set($data)->where->equalTo('table_name', $table)->equalTo('user', $user_id)->isNull('title');
     $this->updateWith($update);
 }
Exemplo n.º 13
0
 /**
  * @covers Zend\Db\Sql\Update::set
  */
 public function testSet()
 {
     $this->update->set(array('foo' => 'bar'));
     $this->assertEquals(array('foo' => 'bar'), $this->readAttribute($this->update, 'set'));
 }
Exemplo n.º 14
0
 public function update_token_status($tokenKey = null)
 {
     if ($tokenKey) {
         $sql = new Sql($this->adapter);
         $update = new Update($this->token);
         $update->set(array('status' => 0));
         $update->where(array("token" => $tokenKey));
         $selectString = $sql->getSqlStringForSqlObject($update);
         $results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
     }
 }
Exemplo n.º 15
0
 /**
  * Update super admin details
  *
  * @access public
  * @author Arvind Singh
  * @param array $data
  *            // Data
  * @param array $where
  *            // Conditions
  *            
  * @return integer
  */
 public function updateSuperAdmin($data, $where)
 {
     $sql = new Sql($this->getAdapter());
     $update = new Update($this->table);
     $update->set($data);
     $update->where($where);
     $statement = $sql->prepareStatementForSqlObject($update);
     $results = $statement->execute();
     $affectedRows = $results->getAffectedRows();
     return $affectedRows;
 }
Exemplo n.º 16
0
 /**
  * This method basically replaces all occurrences of $from->id (UserRow id) in tables
  * comments, user_resource, user_list & search with $into->id in user_id column.
  *
  * @param UserRow $from
  * @param UserRow $into
  * @throws AuthException
  * @return void
  */
 public function mergeUserInAllTables(UserRow $from, UserRow $into)
 {
     if (empty($into->id) || empty($from->id)) {
         throw new AuthException("Cannot merge two UserRows without knowlegde of both UserRow ids");
     }
     $this->mergeUserRows($from, $into);
     /**
      * Table names which contain user_id as a relation to user.id foreign key
      */
     $tablesToUpdateUserId = ["comments", "user_resource", "user_list", "search"];
     // This will prevent autocommit to Db
     $this->getDbConnection()->beginTransaction();
     foreach ($tablesToUpdateUserId as $table) {
         $update = new Update($table);
         $update->set(['user_id' => $into->id]);
         $update->where(['user_id' => $from->id]);
         $this->executeAnyZendSQLUpdate($update);
     }
     // Now commit whole transaction
     $this->getDbConnection()->commit();
     // Perform User deletion
     $from->delete();
 }
 public function updateBookmark($payload)
 {
     $update = new Update($this->table);
     $update->set($payload);
     $this->updateWith($update);
 }
Exemplo n.º 18
0
 /**
  * {@inheritDoc}
  */
 public function setRefreshToken($refreshToken, $clientId, $userId, $expires, $scope = null)
 {
     $expires = date('Y-m-d H:i:s', $expires);
     if ($this->getRefreshToken($refreshToken)) {
         $update = new Update($this->config['refresh_token_table']);
         $update->set(array('client_id' => $clientId, 'user_id' => $userId, 'expires' => $expires, 'scope' => $scope))->where(array('refresh_token' => $refreshToken));
         return $this->execute($update);
     } else {
         $insert = new Insert($this->config['refresh_token_table']);
         $insert->values(array('refresh_token' => $refreshToken, 'client_id' => $clientId, 'user_id' => $userId, 'expires' => $expires, 'scope' => $scope));
         return $this->execute($insert);
     }
 }
 public function markAsRead($messageIds, $uid)
 {
     $update = new Update($this->getTable());
     $update->set(['read' => 1])->where->in('message_id', $messageIds)->and->where->equalTo('recipient', $uid);
     return $this->updateWith($update);
 }
Exemplo n.º 20
0
 public function updateProduct($productData)
 {
     $id = $productData['id'];
     if (!empty($id)) {
         $action = new Update('products');
         $action->set($productData);
         $action->where(array('id=?' => $id));
     }
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepareStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         if ($newId = $result->getGeneratedValue()) {
             return $newId;
         }
         return true;
     }
     throw new \Exception('Database Error');
 }
 public function updatePrivilege($attributes)
 {
     $attributes = $this->verifyPrivilege($attributes);
     $data = $this->getFillableFields($attributes);
     $update = new Update($this->getTable());
     $update->where->equalTo('id', $attributes['id']);
     $update->set($data);
     $this->updateWith($update);
     return $this->fetchById($attributes['id']);
 }
Exemplo n.º 22
0
 public function addOrUpdateRecordByArray(array $recordData, $tableName = null)
 {
     $tableName = is_null($tableName) ? $this->table : $tableName;
     foreach ($recordData as $columnName => $columnValue) {
         if (is_array($columnValue)) {
             // $table = is_null($tableName) ? $this->table : $tableName;
             throw new SuppliedArrayAsColumnValue('Attempting to write an array as the value for column `' . $tableName . '`.`' . $columnName . '.');
         }
     }
     $columns = TableSchema::getAllNonAliasTableColumns($tableName);
     $recordData = SchemaManager::parseRecordValuesByType($recordData, $columns);
     $TableGateway = $this->makeTable($tableName);
     $rowExists = isset($recordData[$TableGateway->primaryKeyFieldName]);
     if ($rowExists) {
         $Update = new Update($tableName);
         $Update->set($recordData);
         $Update->where([$TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]]);
         $TableGateway->updateWith($Update);
         $this->runHook('postUpdate', [$TableGateway, $recordData, $this->adapter, null]);
     } else {
         $d = $this->applyHook('table.insert:before', [$tableName, $recordData]);
         $TableGateway->insert($d);
         $recordData[$TableGateway->primaryKeyFieldName] = $TableGateway->getLastInsertValue();
         if ($tableName == 'directus_files') {
             $Files = new \Directus\Files\Files();
             $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION);
             $thumbnailPath = 'thumbs/THUMB_' . $recordData['name'];
             if ($Files->exists($thumbnailPath)) {
                 $Files->rename($thumbnailPath, 'thumbs/' . $recordData[$this->primaryKeyFieldName] . '.' . $ext);
             }
             $updateArray = [];
             if ($Files->getSettings('file_naming') == 'file_id') {
                 $Files->rename($recordData['name'], str_pad($recordData[$this->primaryKeyFieldName], 11, '0', STR_PAD_LEFT) . '.' . $ext);
                 $updateArray['name'] = str_pad($recordData[$this->primaryKeyFieldName], 11, '0', STR_PAD_LEFT) . '.' . $ext;
                 $recordData['name'] = $updateArray['name'];
             }
             if (!empty($updateArray)) {
                 $Update = new Update($tableName);
                 $Update->set($updateArray);
                 $Update->where([$TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]]);
                 $TableGateway->updateWith($Update);
             }
         }
         $this->runHook('postInsert', [$TableGateway, $recordData, $this->adapter, null]);
     }
     $columns = TableSchema::getAllNonAliasTableColumnNames($tableName);
     $recordData = $TableGateway->fetchAll(function ($select) use($recordData, $columns, $TableGateway) {
         $select->columns($columns)->limit(1);
         $select->where->equalTo($TableGateway->primaryKeyFieldName, $recordData[$TableGateway->primaryKeyFieldName]);
     })->current();
     return $recordData;
 }
Exemplo n.º 23
0
 /**
  * Set config value
  *
  * @param string $source       Source
  * @param array  $destinations Destinations
  *
  * @return boolean
  */
 public function setValue($source, array $destinations)
 {
     if (is_numeric($source)) {
         $row = $this->fetchRow($this->select(array('id' => $source)));
         if (empty($row)) {
             return false;
         }
         $sourceId = $row['id'];
     } else {
         $row = $this->fetchRow($this->select(array('source' => $source)));
         if (!empty($row)) {
             $sourceId = $row['id'];
         } else {
             $this->insert(array('source' => $source));
             $sourceId = $this->getLastInsertId();
         }
     }
     foreach ($destinations as $destination) {
         if (empty($destination['locale']) or empty($destination['value'])) {
             continue;
         }
         $select = new Select();
         $select->from('core_translate_locale');
         $select->where->equalTo('locale', $destination['locale']);
         $select->where->equalTo('core_translate_id', $sourceId);
         $row = $this->fetchRow($select);
         if (!empty($row)) {
             $destination['dst_id'] = $row['id'];
         }
         if (!empty($destination['dst_id'])) {
             $update = new Update('core_translate_locale');
             $update->set(array('destination' => $destination['value'], 'locale' => $destination['locale']));
             $update->where->equalTo('id', $destination['dst_id']);
             $this->execute($update);
         } else {
             $insert = new Insert();
             $insert->into('core_translate_locale')->values(array('destination' => $destination['value'], 'locale' => $destination['locale'], 'core_translate_id' => $sourceId));
             $this->execute($insert);
         }
     }
     return true;
 }
Exemplo n.º 24
0
 public function addOrUpdateRecordByArray(array $recordData, $tableName = null)
 {
     foreach ($recordData as $columnName => $columnValue) {
         if (is_array($columnValue)) {
             $table = is_null($tableName) ? $this->table : $tableName;
             throw new SuppliedArrayAsColumnValue("Attempting to write an array as the value for column `{$table}`.`{$columnName}`.");
         }
     }
     $tableName = is_null($tableName) ? $this->table : $tableName;
     $TableGateway = new self($this->acl, $tableName, $this->adapter);
     $rowExists = isset($recordData[$TableGateway->primaryKeyFieldName]);
     if ($rowExists) {
         $Update = new Update($tableName);
         $Update->set($recordData);
         $Update->where(array($TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]));
         $TableGateway->updateWith($Update);
         Hooks::runHook('postUpdate', array($TableGateway, $recordData, $this->adapter, $this->acl));
     } else {
         $d = $recordData;
         unset($d['data']);
         $TableGateway->insert($d);
         $recordData[$TableGateway->primaryKeyFieldName] = $TableGateway->getLastInsertValue();
         if ($tableName == "directus_files") {
             $Files = new \Directus\Files\Files();
             $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION);
             $thumbnailPath = 'thumbs/THUMB_' . $recordData['name'];
             if ($Files->exists($thumbnailPath)) {
                 $Files->rename($thumbnailPath, 'thumbs/' . $recordData[$this->primaryKeyFieldName] . '.' . $ext);
             }
             $updateArray = array();
             if ($Files->getSettings('file_naming') == 'file_id') {
                 $Files->rename($recordData['name'], str_pad($recordData[$this->primaryKeyFieldName], 11, "0", STR_PAD_LEFT) . '.' . $ext);
                 $updateArray['name'] = str_pad($recordData[$this->primaryKeyFieldName], 11, "0", STR_PAD_LEFT) . '.' . $ext;
                 $recordData['name'] = $updateArray['name'];
             }
             if (!empty($updateArray)) {
                 $Update = new Update($tableName);
                 $Update->set($updateArray);
                 $Update->where(array($TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]));
                 $TableGateway->updateWith($Update);
             }
         }
         Hooks::runHook('postInsert', array($TableGateway, $recordData, $this->adapter, $this->acl));
     }
     $columns = TableSchema::getAllNonAliasTableColumnNames($tableName);
     $recordData = $TableGateway->fetchAll(function ($select) use($recordData, $columns, $TableGateway) {
         $select->columns($columns)->limit(1);
         $select->where->equalTo($TableGateway->primaryKeyFieldName, $recordData[$TableGateway->primaryKeyFieldName]);
     })->current();
     return $recordData;
 }
 public function updatePrivilege($attributes)
 {
     $attributes = $this->verifyPrivilege($attributes);
     $update = new Update($this->getTable());
     $update->where->equalTo('id', $attributes['id']);
     $update->set(array('permissions' => $attributes['permissions'], 'read_field_blacklist' => $attributes['read_field_blacklist'], 'write_field_blacklist' => $attributes['write_field_blacklist']));
     $this->updateWith($update);
     return $this->fetchById($attributes['id']);
 }
Exemplo n.º 26
0
 public function index07Action()
 {
     $table = "user";
     $adapter = $this->getServiceLocator()->get("db_books");
     $tableGateway = new TableGateway($table, $adapter);
     $updateObj = new Update("user");
     $updateObj->set(array("name" => "mentos"))->where->greaterThan("id", "5");
     $tableGateway->updateWith($updateObj);
     return false;
 }
Exemplo n.º 27
0
 public function addOrUpdateRecordByArray(array $recordData, $tableName = null)
 {
     foreach ($recordData as $columnName => $columnValue) {
         if (is_array($columnValue)) {
             $table = is_null($tableName) ? $this->table : $tableName;
             throw new SuppliedArrayAsColumnValue("Attempting to write an array as the value for column `{$table}`.`{$columnName}`.");
         }
     }
     $tableName = is_null($tableName) ? $this->table : $tableName;
     $rowExists = isset($recordData['id']);
     $TableGateway = new self($this->acl, $tableName, $this->adapter);
     if ($rowExists) {
         $Update = new Update($tableName);
         $Update->set($recordData);
         $Update->where(array('id' => $recordData['id']));
         $TableGateway->updateWith($Update);
         Hooks::runHook('postUpdate', array($TableGateway, $recordData, $this->adapter, $this->acl));
     } else {
         //If we are adding a new directus_files Item, We need to do that logic
         if ($tableName == "directus_files") {
             $Storage = new \Directus\Files\Storage\Storage();
             //If trying to save to temp, force to default
             if (!isset($recordData['storage_adapter']) || $recordData['storage_adapter'] == '' || $Storage->storageAdaptersByRole['TEMP']['id'] == $recordData['storage_adapter']) {
                 $recordData['storage_adapter'] = $Storage->storageAdaptersByRole['DEFAULT']['id'];
             }
             //Save Temp Thumbnail name for use after files record save
             $info = pathinfo($recordData['name']);
             if (in_array($info['extension'], $this->imagickExtensions)) {
                 $thumbnailName = "THUMB_" . $info['filename'] . '.jpg';
             } else {
                 $thumbnailName = "THUMB_" . $recordData['name'];
             }
             //If we are using files ID, Dont save until after insert
             if ($Storage->getFilesSettings()['file_file_naming'] != "file_id") {
                 //Save the file in TEMP Storage Adapter to Designated StorageAdapter
                 $recordData['name'] = $Storage->saveFile($recordData['name'], $recordData['storage_adapter']);
             }
         }
         $TableGateway->insert($recordData);
         $recordData['id'] = $TableGateway->getLastInsertValue();
         if ($tableName == "directus_files") {
             $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION);
             $updateArray = array();
             //If using file_id saving, then update record and set name to id
             if ($Storage->getFilesSettings()['file_file_naming'] == "file_id") {
                 $newName = $Storage->saveFile($recordData['name'], $recordData['storage_adapter'], str_pad($recordData['id'], 11, "0", STR_PAD_LEFT) . '.' . $ext);
                 $updateArray['name'] = str_pad($recordData['id'], 11, "0", STR_PAD_LEFT) . '.' . $ext;
                 $recordData['name'] = $updateArray['name'];
             }
             //If we are using file_id titles, then set title to id
             if ($Storage->getFilesSettings()['file_title_naming'] == "file_id") {
                 $updateArray['title'] = str_pad($recordData['id'], 11, "0", STR_PAD_LEFT);
                 $recordData['title'] = $updateArray['title'];
             }
             if (!empty($updateArray)) {
                 $Update = new Update($tableName);
                 $Update->set($updateArray);
                 $Update->where(array('id' => $recordData['id']));
                 $TableGateway->updateWith($Update);
             }
             //Save Temp Thumbnail to Thumbnail SA using file id: $params['id']
             $tempLocation = $Storage->storageAdaptersByRole['TEMP']['destination'];
             if (file_exists($tempLocation . $thumbnailName)) {
                 $thumbnailDestination = $Storage->storageAdaptersByRole['THUMBNAIL']['destination'];
                 if (in_array($ext, $this->imagickExtensions)) {
                     $ext = 'jpg';
                 }
                 $Storage->ThumbnailStorage->acceptFile($tempLocation . $thumbnailName, $recordData['id'] . "." . $ext, $thumbnailDestination);
                 unlink($tempLocation . $thumbnailName);
             }
         }
         Hooks::runHook('postInsert', array($TableGateway, $recordData, $this->adapter, $this->acl));
     }
     $columns = TableSchema::getAllNonAliasTableColumnNames($tableName);
     $recordData = $TableGateway->fetchAll(function ($select) use($recordData, $columns) {
         $select->columns($columns)->limit(1);
         $select->where->equalTo('id', $recordData['id']);
     })->current();
     return $recordData;
 }
Exemplo n.º 28
0
 public function addOrUpdateRecordByArray(array $recordData, $tableName = null)
 {
     foreach ($recordData as $columnName => $columnValue) {
         if (is_array($columnValue)) {
             $table = is_null($tableName) ? $this->table : $tableName;
             throw new SuppliedArrayAsColumnValue("Attempting to write an array as the value for column `{$table}`.`{$columnName}`.");
         }
     }
     $tableName = is_null($tableName) ? $this->table : $tableName;
     $rowExists = isset($recordData['id']);
     $TableGateway = new self($this->acl, $tableName, $this->adapter);
     if ($rowExists) {
         $Update = new Update($tableName);
         $Update->set($recordData);
         $Update->where(array('id' => $recordData['id']));
         $TableGateway->updateWith($Update);
         Hooks::runHook('postUpdate', array($TableGateway, $recordData, $this->adapter, $this->acl));
     } else {
         //If we are adding a new directus_files Item, We need to do that logic
         // @todo: clean up/refactor saving file process
         if ($tableName == "directus_files") {
             $Storage = new \Directus\Files\Storage\Storage();
             //If trying to save to temp, force to default
             if (!isset($recordData['storage_adapter']) || $recordData['storage_adapter'] == '' || $Storage->storageAdaptersByRole['TEMP']['id'] == $recordData['storage_adapter']) {
                 $recordData['storage_adapter'] = $Storage->storageAdaptersByRole['DEFAULT']['id'];
             }
             $StorageAdapters = new DirectusStorageAdaptersTableGateway($this->acl, $this->adapter);
             //If desired Storage Adapter Exists...
             $filesAdapter = $StorageAdapters->fetchOneById($recordData['storage_adapter']);
             //Save Temp Thumbnail name for use after files record save
             // @todo: make file name format sanatize by default
             // same as uniqueName by the adapter
             // replacing space with underscore
             $originalFile = $recordData['file_name'];
             // we do not need it part of our records Data
             unset($recordData['file_name']);
             $recordData['name'] = str_replace(' ', '_', $recordData['name']);
             $info = pathinfo($recordData['name']);
             if (in_array($info['extension'], $this->imagickExtensions)) {
                 $thumbnailName = "THUMB_" . $info['filename'] . '.jpg';
             } else {
                 $thumbnailName = "THUMB_" . $recordData['name'];
             }
             //If we are using files ID, Dont save until after insert
             if ($Storage->getFilesSettings()['file_naming'] == "file_name") {
                 //Save the file in TEMP Storage Adapter to Designated StorageAdapter
                 $recordData['name'] = $Storage->saveFile($recordData['name'], $recordData['storage_adapter']);
                 // $fileData = $Storage->saveData($recordData['data'], $recordData['name'], $filesAdapter['destination']);
                 // $recordData['name'] = $fileData['name'];
             } else {
                 if ($Storage->getFilesSettings()['file_naming'] == "file_hash") {
                     //Save the file in TEMP Storage Adapter to Designated StorageAdapter
                     $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION);
                     $fileHashName = md5(microtime() . $recordData['name']);
                     $newName = $Storage->saveFile($recordData['name'], $recordData['storage_adapter'], $fileHashName . '.' . $ext);
                     $updateArray['name'] = $fileHashName . '.' . $ext;
                     $recordData['name'] = $updateArray['name'];
                 }
             }
         }
         $d = $recordData;
         unset($d['data']);
         $TableGateway->insert($d);
         $recordData['id'] = $TableGateway->getLastInsertValue();
         if ($tableName == "directus_files") {
             $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION);
             $updateArray = array();
             //If using file_id saving, then update record and set name to id
             if ($Storage->getFilesSettings()['file_naming'] == "file_id") {
                 $newName = $Storage->saveFile($recordData['name'], $recordData['storage_adapter'], str_pad($recordData['id'], 11, "0", STR_PAD_LEFT) . '.' . $ext);
                 $updateArray['name'] = str_pad($recordData['id'], 11, "0", STR_PAD_LEFT) . '.' . $ext;
                 $recordData['name'] = $updateArray['name'];
             }
             // @todo: do not make this file create twice.
             // file should be copied to temp and then work from there.
             // but is copied on "media" also on "temp" then copied back to "media"
             if (file_exists($filesAdapter['destination'] . $originalFile)) {
                 unlink($filesAdapter['destination'] . $originalFile);
             }
             if (!empty($updateArray)) {
                 $Update = new Update($tableName);
                 $Update->set($updateArray);
                 $Update->where(array('id' => $recordData['id']));
                 $TableGateway->updateWith($Update);
             }
             //Save Temp Thumbnail to Thumbnail SA using file id: $params['id']
             $tempLocation = $Storage->storageAdaptersByRole['TEMP']['destination'];
             if (file_exists($tempLocation . $thumbnailName)) {
                 $thumbnailDestination = $Storage->storageAdaptersByRole['THUMBNAIL']['destination'];
                 if (in_array($ext, $this->imagickExtensions)) {
                     $ext = 'jpg';
                 }
                 $Storage->ThumbnailStorage->acceptFile($tempLocation . $thumbnailName, $recordData['id'] . "." . $ext, $thumbnailDestination);
                 unlink($tempLocation . $thumbnailName);
             }
         }
         Hooks::runHook('postInsert', array($TableGateway, $recordData, $this->adapter, $this->acl));
     }
     $columns = TableSchema::getAllNonAliasTableColumnNames($tableName);
     $recordData = $TableGateway->fetchAll(function ($select) use($recordData, $columns) {
         $select->columns($columns)->limit(1);
         $select->where->equalTo('id', $recordData['id']);
     })->current();
     return $recordData;
 }