✏️ 正在编辑: DbTable.php
路径:
/srv/systems_dir/biblioteca_yuppie/library/Yuppie/DbTable.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php abstract class Yuppie_DbTable extends Zend_Db_Table_Abstract implements Countable { protected $_primary = 'id'; protected $_view; public function getPrimaryKey() { return $this->_primary; } public function findById($id) { $key = $this->getPrimaryKey(); if (is_array($key)) { if (count($key) != 1) { throw new Exception( 'can not findByID with array as $_primary'); } $key = current($key); } $row = $this->fetchRow([$key . " = ?" => $id]); return $row ?? null; } public function search($where = null, $order = null, $page = null, $limit = null, $range = null, $fromView = false) { return $this->findAll(array( 'where' => $where, 'order' => $order, 'page' => $page, 'limit' => $limit, 'range' => $range, 'fromView' => $fromView )); } public function _filtrarExcluidos(&$where, $fromView = false) { $cols = $this->_getCols(); if( in_array('excluido', $cols) ){ if( !$where || is_string($where) ){ $where = (array) $where; } $tableName = $fromView ? $this->_view : $this->_name; $where[] = "{$tableName}.excluido <> 1"; } } /** * Verifica se a restrição contém referência a alguma tabela relacionada * e adiciona um LEFT JOIN ao select * * @param string $cond * @param Zend_Db_Table_Select $select */ public function _verifyReference($cond, &$select) { if( strstr($cond, '.') ){ $condParts = explode('.', $cond); $alias = substr($condParts[0], strrpos($condParts[0], ' ')); $joinExists = key_exists($alias, $select->getPart(Zend_Db_Select::FROM)); if( !$joinExists && isset($this->_referenceMap[$alias])){ $ref = $this->_referenceMap[$alias]; $dbtable = new $ref['refTableClass']; $wheres = array(); foreach ( $ref['refColumns'] as $key => $column ) { $wheres[] = "$alias.$column = $this->_name.{$ref['columns'][$key]}"; } $joinOn = implode(' AND ', $wheres); $select->setIntegrityCheck(false); $select->joinLeft(array( $alias => $dbtable->info('name') ), $joinOn, array()); } } } /** * Adiciona as restrições ao select * * @param Zend_Db_Table_Select $select * @param mixed $where */ public function _setWhere(&$select, $where = null) { if( $where ){ if( is_array($where) ){ $listTable = array(); foreach ( $where as $cond => $value ) { if( is_numeric($cond) ){ $this->_verifyReference($value, $select); $select->where($value); } else { $table = current(explode('.', $cond)); if( !in_array($table, $listTable) ){ $this->_verifyReference($cond, $select); } $listTable[] = $table; $select->where($cond, $value, (is_numeric($value) ? Zend_Db::INT_TYPE: null)); } } } else { // Se for um string $this->_verifyReference($where, $select); $select->where($where); } } } /** * Retorna uma lista de objetos Yuppie_Model * Caso receba uma $option['page'], retorna um Zend_Paginator * * @param array $options * @return array|Zend_Paginator */ public function findAll($options = null) { $page = isset($options['page']) && $options['page'] && is_numeric($options['page']) ? $options['page'] : null; $range = isset($options['range']) && $options['range'] && is_numeric($options['range']) ? $options['range'] : null; $limit = isset($options['limit']) && $options['limit'] && is_numeric($options['limit']) ? $options['limit'] : null; $where = isset($options['where']) && $options['where'] ? $options['where'] : null; $order = isset($options['order']) && $options['order'] ? $options['order'] : null; $group = isset($options['group']) && $options['group'] ? $options['group'] : null; $getSelect = isset($options['select']) && $options['select'] ? $options['select'] : null; $columns = isset($options['columns']) && $options['columns'] ? $options['columns'] : null; $fromView = isset($options['fromView']) && $options['fromView'] && $this->_view; $joins = isset($options['joins']) && is_array($options['joins']) ? $options['joins'] : null; if( $where && is_array($where) ){ foreach ( $where as $cond => $value ) { if( !is_numeric($cond) && !strstr($cond, '?') ){ unset($where[$cond]); if( $value ){ $where["{$cond} LIKE ?"] = $value; } } } } $this->_filtrarExcluidos($where, $fromView); if( $page || $range || $getSelect || $columns || $fromView || $joins ){ $select = $this->select(); $cols = $columns ? '' : '*'; $tableName = $this->_name; if( $fromView ){ $tableName = $this->_view; $select->setIntegrityCheck(false); } $select->from($tableName, $cols); if( $joins ){ $select->setIntegrityCheck(false); foreach ( $joins as $join ) { $joinType = isset($join['type']) && in_array($join['type'], array( 'inner', 'left', 'right', 'full', 'cross', 'natural' )) ? $join['type'] : 'inner'; $joinMethod = 'join' . ucfirst($joinType); $select->$joinMethod($join['table'], $join['on'], $join['cols']); } } $this->_setWhere($select, $where); if( $order ){ $select->order($order); } if( $group ){ $select->group($group); } if( $limit == 1 ){ $select->limit(1); $limit = null; } if( $columns ){ $select->columns($columns); $getSelect = true; } if( $getSelect ){ return $select; } if( $page || $limit || $range ){ return $this->_getPaginator($select, $page, $limit, $range, $fromView); } return $this->getAdapter()->fetchAll($select, null, Zend_Db::FETCH_OBJ); } return $this->fetchAll($where, $order, $limit); } public function findOne($options) { $options['limit'] = 1; $results = $this->findAll($options); return $results->count() > 0 ? $results->current() : array(); } protected function _getPaginator(Zend_Db_Select $select, $page = null, $limit = null, $range = null, $fromView = false) { if( $fromView ){ $paginator = Zend_Paginator::factory($select); } else { $adapter = new Yuppie_Paginator($select, $this->getRowClass()); $paginator = new Zend_Paginator($adapter); } if( $page && is_numeric($page) ){ $paginator->setCurrentPageNumber($page); } if( $limit && is_numeric($limit) ){ $paginator->setItemCountPerPage($limit); } if( $range && is_numeric($range) ){ $paginator->setPageRange($range); } return $paginator; } public function fetchPairs($field, $where = null, $order = null, $key = null, $limit = null) { if( !$key ){ $key = $this->getPrimaryKey(); if( is_array($key) ){ if( count($key) != 1 ){ throw new Exception( 'can not fetchPairs with array as $_primary'); } $key = current($key); } } $select = $this->select() ->from($this->_name, array( $key, $field )); if( $limit ){ $select->limit($limit); } $this->_filtrarExcluidos($where); $this->_setWhere($select, $where); $select->order($order ? $order : $field); return $this->getAdapter()->fetchPairs($select); } public function count($where = null) { $select = $this->select()->from($this->_name, array( 'count' => 'COUNT(*)' )); if( $where ){ foreach ( (array) $where as $cond => $bind ) { if( is_numeric($cond) ){ $select->where($bind); } else if( $bind ){ $select->where($cond, $bind); } else { return 0; } } } return $this->getAdapter()->fetchOne($select); } public function insert(array $data) { $result = parent::insert($data); if ($result) { $data['id'] = $result; Yuppie_Log::update($this->_name, [], $data); } return $result; } public function update(array $data, $where) { $primary = is_array($this->getPrimaryKey()) ? @current($this->getPrimaryKey()) : $this->getPrimaryKey(); if( isset($data[$primary]) && Yuppie_Log::getDbTable() ){ $oldData = $this->findById($data[$primary]); } $result = parent::update($data, $where); if( isset($oldData) && $oldData && $result ){ Yuppie_Log::update($this->_name, $oldData->toArray(), $data); } return $result; } public function delete($where) { $cols = $this->_getCols(); $data = []; $primary = is_array($this->getPrimaryKey()) ? current($this->getPrimaryKey()) : $this->getPrimaryKey(); if (empty($primary)) { throw new Yuppie_Exception("Chave primária não definida."); } if (in_array('excluido', $cols)) { $data = $this->search($where); $result = parent::update(["{$this->_name}.excluido" => 1], $where); $dados = is_object($data) ? $data->toArray() : $data; if (!empty($dados) && $result) { foreach ($dados as $oldData) { $oldData = is_array($oldData) ? $oldData : get_object_vars($oldData); if (!empty($oldData[$primary])) { Yuppie_Log::delete($this->_name, $oldData[$primary]); } } } return $result; } $oldData = $this->search($where); $oldData = is_object($oldData) ? $oldData->toArray(): $oldData; $result = parent::delete($where); if ($result) { Yuppie_Log::delete($this->_name, $oldData[$primary]); } return $result; } public function _cascadeDelete($parentTableClassname, array $primaryKey) { $this->_setupMetadata(); $rowsAffected = 0; foreach ($this->_getReferenceMapNormalized() as $map) { if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) { switch ($map[self::ON_DELETE]) { case self::CASCADE: $where = array(); for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) { $col = $this->_db->foldCase($map[self::COLUMNS][$i]); $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]); $type = $this->_metadata[$col]['DATA_TYPE']; $where[] = $this->_db->quoteInto( $this->_db->quoteIdentifier($col, true) . ' = ?', $primaryKey[$refCol], $type); } foreach($this->search($where) as $child){ $row = $this->fetchRow("id = $child->id"); $rowsAffected += $row->delete(); } break; default: // no action break; } } } return $rowsAffected; } public function fetchRow($where = null, $order = null, $offset = null) { $cols = $this->_getCols(); if( in_array('excluido', $cols) ){ if( ($where instanceof Zend_Db_Table_Select ) ){ //se tiver um join, espera-se que todos os parãmetros //de busca já foram passados. if( count($where->getPart(Zend_Db_Table_Select::FROM)) <= 1 ){ $strWhere = "{$this->_name}.excluido<>1"; foreach ( $where->getPart(Zend_Db_Table_Select::WHERE) as $w ) { if( strstr($w, "excluido") ){ continue; } if( substr($w, 0, 3) == "AND" ){ $strWhere .= " " . $w; }else{ $strWhere .= " AND " . $w; } } // $where->reset(Zend_Db_Table_Select::WHERE); $where->where($strWhere); } } elseif( is_array($where) ){ $strWhere = "{$this->_name}.excluido<>1"; foreach( $where as $key => $w ){ if( is_string(($key)) ){ $strWhere .= " AND " . str_replace("?", "'{$w}'", $key); }else{ $strWhere .= " AND " . $w; } } $where = $strWhere; } elseif($where != null) { $where = $where .= " AND {$this->_name}.excluido<>1"; }else{ $where = "{$this->_name}.excluido<>1"; } } return parent::fetchRow($where, $order, $offset); } public function closeConnection() { $this->getAdapter()->closeConnection(); } }
💾 保存文件
← 返回文件管理器