✏️ 正在编辑: DbTable.php
路径:
/srv/systems_dir/yuppiecred-lidernegocios/library/Core/DbTable.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php use Carbon\Carbon; use Modules\Core\Dto\DtoAbstract; use Modules\Core\Collection\DtoCollectionFactory; use Doctrine\Common\Collections\ArrayCollection; class Core_DbTable extends Zend_Db_Table_Abstract { protected $_primary = 'id'; public function getPrimaryKey() { return $this->_primary; } public function delete($where) { $this->closeConnection(); $info = $this->info(); $cols = $info['cols']; if (in_array("excluido", $cols)) { return $this->update(array('excluido' => 1), $where); } else { return parent::delete($where); } } public function closeConnection() { $this->getAdapter()->closeConnection(); } public function fetchRow($where = null, $order = null, $offset = null) { $info = $this->info(); $cols = $info['cols']; if( in_array("excluido", $cols) ){ if( ($where instanceof Zend_Db_Table_Select ) ){ $strWhere = "{$this->_name}.excluido<>1"; foreach ( $where->getPart(Zend_Db_Table_Select::WHERE) as $w ) { $strWhere .= " AND " . $w; } $where->where($strWhere); } elseif( is_array($where) ){ $where[] = "{$this->_name}.excluido<>1"; } elseif( $where != null ){ $where = "{$where} AND {$this->_name}.excluido<>1"; } else { $where = "{$this->_name}.excluido<>1"; } } return parent::fetchRow($where, $order, $offset); } public function fetchAll($where = null, $order = null, $count = null, $offset = null) { $info = $this->info(); $cols = $info['cols']; if( in_array("excluido", $cols) ){ if( ($where instanceof Zend_Db_Table_Select ) ){ $strWhere = "{$this->_name}.excluido<>1"; foreach ( $where->getPart(Zend_Db_Table_Select::WHERE) as $w ) { $strWhere .= ' AND ' . $w; } $where->where($strWhere); } elseif( is_array($where) ){ $where[] = "{$this->_name}.excluido<>1"; } elseif( $where != null ){ $where .= " AND {$this->_name}.excluido<>1"; } else { $where = "{$this->_name}.excluido<>1"; } } return parent::fetchAll($where, $order, $count, $offset); } public function update(array $data, $where) { $result = parent::update($data, $where); if( $result > 0 ){ $log = new Model_DbTable_Log(); $log->save($this, $data, $where, $this->_primary[1]); } return $result; } public function insert(array $data) { $id = parent::insert($data); //grava inserção no log if( $id > 0 ){ $log = new Model_DbTable_Log(); $log->save($this, $data, 'insert', $id); } return $id; } public function fetchPairs($field, $where = null, $order = null, $key = null) { if( !$key ){ $key = $this->getPrimaryKey(); if( is_array($key) ){ if( count($key) != 1 ){ throw new Yuppie_Exception( 'can not fetchPairs with array as $_primary'); } $key = current($key); } } $select = $this->select() ->from($this->_name, array( $key, $field )); if( is_array($where) ){ $where[] = "{$this->_name}.excluido <> 1"; foreach( $where as $cond => $value ){ if( is_numeric($cond) ){ $select->where($value); }else{ $select->where($cond, $value); } } }elseif($where != null){ $select->where($where); } $select->where("{$this->_name}.excluido <> 1"); $select->order($order ? $order : $field); return $this->getAdapter()->fetchPairs($select); } /** * Insere valores em massa no banco de dados * * @param array $data Array de objetos a serem inseridos no banco, * com os valores indexados de acordo com as colunas da tabela * @param mixed String|array $restritores Indices das linhas no array $data que * serão aplicados como restrição do insert como WHERE NOT EXISTS. As restrições serão * aplicadas a cada linha, caso algum valor do restritor seja nulo na linha, * ela não será inserida. * @return int Contagem de valores inseridos */ public function insertMultipleValues(array $data, $restritores = array()) { $this->closeConnection(); if (!$data) { return; } $cols = array_keys(current($data)); $insertAliases = array(); foreach ($cols as $column) { $insertAliases[] = "? AS `$column`"; } $rowCount = 0; $tableName = $this->getAdapter()->quoteIdentifier($this->_name); $strCols = implode('`,`', $cols); $binds = implode(', ', $insertAliases); $query = "INSERT INTO $tableName (`$strCols`) SELECT tmp.* FROM (SELECT $binds) AS tmp"; if(count($restritores)){ $restritores = is_array($restritores) ? $restritores : array($restritores); $restricoes = array(); foreach ($restritores as $campo){ $restricoes[] = "`$campo` = ?"; } $whereBinds = implode(" AND ", $restricoes); $strRestritores = implode('`,`', $restritores); $query .=" WHERE NOT EXISTS (SELECT `$strRestritores` FROM $tableName WHERE $whereBinds ) LIMIT 1"; } $rowCount = 0; $inserted = 0; try { $stmt = $this->getAdapter()->prepare($query); $stmt->getAdapter()->beginTransaction(); foreach ($data as $row) { $valoresRestritores = array(); foreach ($restritores as $campo){ $valoresRestritores[] = $row[$campo]; } if(count($restritores) != count($valoresRestritores)){ continue; } $bindValues = array_merge(array_values($row), $valoresRestritores); $stmt->execute($bindValues); $inserted += $stmt->rowCount(); $rowCount++; if($rowCount % 1000 == 0 || $rowCount >= count($data)){ $stmt->getAdapter()->commit(); $stmt->getAdapter()->beginTransaction(); } } } catch (Zend_Db_Statement_Exception $exc) { $stmt->getAdapter()->rollBack(); throw new Core_Exception('Falha ao realizar a importação'); } $this->closeConnection(); return $inserted; } /** * Atualiza valores em massa no banco de dados * * @param array $data Array de objetos a serem inseridos no banco, * com os valores indexados de acordo com as colunas da tabela * @param mixed String|array $restritores Indices das linhas no array $data que * serão aplicados como restrição do update no WHERE. As restrições serão * aplicadas a cada linha, caso algum valor do restritor seja nulo na linha, * ela não será atualizada. * @return int Contagem de valores atualizados */ public function updateMultipleValues(array $data, $restritores) { $this->closeConnection(); if (!$data) { return; } if(!is_array($restritores)){ $restritores = array($restritores); } $restricoes = array(); foreach ($restritores as $campo){ $restricoes[] = "`$campo` = ?"; } $cols = array(); foreach (array_keys(current($data)) as $column){ $cols[] = "`$column` = COALESCE(?, `$column`)"; } $whereBinds = implode(" AND ", $restricoes); $setBinds = implode(', ', $cols); $tableName = $this->getAdapter()->quoteIdentifier($this->_name); $query = "UPDATE $tableName SET $setBinds WHERE $whereBinds"; $rowCount = 0; $updated = 0; try { $stmt = $this->getAdapter()->prepare($query); $stmt->getAdapter()->beginTransaction(); foreach ($data as $row) { $valoresRestritores = array(); foreach ($restritores as $campo){ $valoresRestritores[] = $row[$campo]; } if(count($restritores) != count(array_filter($valoresRestritores))){ continue; } $bindValues = array_merge(array_values($row), $valoresRestritores); $stmt->execute($bindValues); $updated += $stmt->rowCount(); $rowCount++; if($rowCount % 1000 == 0 || $rowCount == count($data)){ $stmt->getAdapter()->commit(); $stmt->getAdapter()->beginTransaction(); } } } catch (Zend_Db_Statement_Exception $exc) { $stmt->getAdapter()->rollBack(); throw new Core_Exception('Falha ao realizar a importação'); } $this->closeConnection(); return $updated; } /** * Consulta multiplos valores e indexa pela chave informada * * @param string $key Coluna que será o índice do array * @param array $fields Campos que serão indexados pela coluna informada * @param string $where Condicionais da consulta * @param string $order * * @return array Retorna multiplos arrays indexados pela chave informada */ public function fetchCols($key, array $fields, $where = null, $order = null) { array_unshift($fields, $key); $select = $this->select() ->from($this->_name, $fields); $select->where($where); $select->order($order ? $order : current($fields)); $stmt = $this->getAdapter()->query($select); $data = array(); while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) { $index = $row[0]; unset($row[0]); $data["$index"] = array_values($row); } return $data; } public function fetchColumns($key, array $fields, $where = null, $order = null) { $select = $this->select() ->from($this->_name, $fields); if( is_array($where) ){ $where[] = "{$this->_name}.excluido <> 1"; foreach( $where as $cond => $value ){ if( is_numeric($cond) ){ $select->where($value); }else{ $select->where($cond, $value); } } }elseif($where != null){ $select->where($where); } $select->where("{$this->_name}.excluido <> 1"); $select->order($order ? $order : current($fields)); $stmt = $this->getAdapter()->query($select); return $stmt->fetchAll(Zend_Db::FETCH_ASSOC); } /** * @param Zend_Db_Select $sql * @param string $dto * @return ArrayCollection */ public function fetchCollection(Zend_Db_Select $sql, string $dto): ArrayCollection { return DtoCollectionFactory::createFromArray($dto, $this->getAdapter()->fetchAll($sql) ?? []); } /** * @param Zend_Db_Select $sql * @param string $dto * @return DtoAbstract */ public function fetchDto(Zend_Db_Select $sql, string $dto): DtoAbstract { $row = $this->getAdapter()->fetchRow($sql); return new $dto(!empty($row) ? $row : []); } /** * @param DtoAbstract $dto * @return DtoAbstract */ public function saveFromDto(DtoAbstract $dto): DtoAbstract { if ($dto->getId()) { $this->update($dto->toArray(), 'id = ' . $dto->getId()); return $dto; } $data = $this->createRow($dto->toArray(true)); $dto->setId($data->save()); return $dto; } /** * @param Zend_Db_Select $sql * @param bool|null $all * * @return array|mixed|null */ public function fetchOrNull(Zend_Db_Select $sql, ?bool $all = true) { if ($all) { $data = $this->getAdapter()->fetchAll($sql); return !empty($data) ? $data : []; } $data = $this->getAdapter()->fetchRow($sql); return $data ? $data : null; } /** * @param Carbon $date * @return int */ public function daysToFriday(Carbon $date): int { return ( ($date->isSunday() ? 2 : 0) + ($date->isSaturday() ? 1 : 0) ) * -1; } /** * @param bool|null $holidays * @return Carbon */ public function weekDay(?bool $holidays = false): Carbon { $date = Carbon::now(); return $date->addDays($holidays ? 0 : $this->daysToFriday($date)); } /** * @var string $where * @var string $order * @var string $count * @var string $offset */ public function fetchAllDirect( $where = null, string $order = null, string $count = null, string $offset = null ) { return parent::fetchAll($where, $order, $count, $offset); } public function info($key = null) { return parent::info($key); } }
💾 保存文件
← 返回文件管理器