public function __construct($table, AdapterInterface $adapter, $features = null, ResultSetInterface $resultSetPrototype = null) { if (!(is_string($table) || $table instanceof TableIdentifier)) { throw new \InvalidArgumentException('Table name must be a string or an instance of Zend\\Db\\Sql\\TableIdentifier'); } $this->table = $table; $this->adapter = $adapter; if ($features !== null) { if ($features instanceof AbstractFeature) { $features = array($features); } if (is_array($features)) { $this->featureSet = new FeatureSet($features); } elseif ($features instanceof FeatureSet) { $this->featureSet = $features; } else { throw new \InvalidArgumentException('TableGateway expects $feature to be an instance of an AbstractFeature or a FeatureSet, or an array of AbstractFeatures'); } } else { $this->featureSet = new FeatureSet(); } $resources = preg_replace('/(?<!^)([A-Z])/', '-\\1', explode("\\", get_class($resultSetPrototype->getArrayObjectPrototype()))[2]); $this->tableName = strtolower(str_replace("-", "_", $resources)); $this->resultSetPrototype = $resultSetPrototype ?: new ResultSet(); $this->initialize(); }
/** * Updates record with given key value * if no key value given, value of ID key is assumed * if no key given and no ID defined, exception is thrown * @param $tableName * @param array $record * @param null $uniqueKey * @return mixed * @throws \Exception */ public function updateRecords($tableName, array $record, $uniqueKey = null) { $tableName = '{' . $tableName . '}'; if (empty($uniqueKey)) { if (!isset($record['id'])) { throw new \Exception('Invalid data given to updateRecords method. ' . ' You must specify unique key or provide record ID'); } $uniqueKey = 'id'; } if (!isset($record[$uniqueKey])) { throw new \Exception('Invalid unique key given'); } if (empty($record[$uniqueKey])) { throw new \Exception('Unique key is empty'); } $fields = []; $keys = []; $uniqueKeyValue = $record[$uniqueKey]; // do not update unique key unset($record[$uniqueKey]); foreach ($record as $key => $field) { if ($key != $uniqueKey) { $fields[] = $field; $keys[] = $key . ' = ? '; } } $keys = implode(',', $keys); $fields[] = $uniqueKeyValue; $query = "update {$tableName} set {$keys} where {$uniqueKey} = ?"; $this->executeRawQuery($query, $fields)->count(); $this->clearTableCache($tableName); return $this->result->getAffectedRows(); }
/** * @return mixed */ public function model() { return clone $this->resultSetPrototype->getArrayObjectPrototype(); }
/** * @param ResultSetInterface $results * @param bool $one * @return \Zend\Db\ResultSet\ResultSet|bool */ protected function hydrate($results, $one = false) { $result = new HydratingResultSet($this->hydrator, $this->entityPrototype); $hydro = $result->initialize($results->toArray()); return $one ? $hydro->current() : $hydro; }