/** * Transform a property to a database column name * * @param string $property the name of the property * @return string the column name */ public function propertyToColumn($property) { if ($property === 'name') { return 'category'; } elseif ($property === 'owner') { return 'uid'; } else { return parent::propertyToColumn($property); } }
/** * Updates an entry in the db from an entity * @throws \InvalidArgumentException if entity has no id * @param Entity $entity the entity that should be created */ public function update(Entity $entity) { // if entity wasn't changed it makes no sense to run a db query $properties = $entity->getUpdatedFields(); if (count($properties) === 0) { return $entity; } // entity needs an id $id = $entity->getId(); if ($id === null) { throw new \InvalidArgumentException('Entity which should be updated has no id'); } // get updated fields to save, fields have to be set using a setter to // be saved // dont update the id field unset($properties['id']); $columns = ''; $params = array(); // build the fields $i = 0; foreach ($properties as $property => $updated) { $column = $entity->propertyToColumn($property); $getter = 'get' . ucfirst($property); $columns .= '`' . $column . '` = ?'; // only append colon if there are more entries if ($i < count($properties) - 1) { $columns .= ','; } array_push($params, $entity->{$getter}()); $i++; } $sql = 'UPDATE `' . $this->tableName . '` SET ' . $columns . ' WHERE `id` = ?'; array_push($params, $id); $this->execute($sql, $params); }