Example #1
0
 protected function save_callback(array $values, $id = null, array $options = [])
 {
     if ($id) {
         $this->update($values, $id);
         return $id;
     }
     $parent_id = 0;
     if ($this->parent) {
         $parent_id = $this->parent->save_callback($values, $id, $options);
         if (!$parent_id) {
             throw new \Exception("Parent save failed: {$this->parent->name} returning {$parent_id}.");
         }
     }
     $driver_name = $this->connection->driver_name;
     list($filtered, $holders, $identifiers) = $this->filter_values($values);
     // FIXME: ALL THIS NEED REWRITE !
     if ($holders) {
         // faire attention à l'id, si l'on revient du parent qui a inséré, on doit insérer aussi, avec son id
         if ($id) {
             $filtered[] = $id;
             $statement = 'UPDATE `{self}` SET ' . implode(', ', $holders) . ' WHERE `{primary}` = ?';
             $statement = $this->prepare($statement);
             $rc = $statement->execute($filtered);
         } else {
             if ($driver_name == 'mysql') {
                 if ($parent_id && empty($holders[$this->primary])) {
                     $filtered[] = $parent_id;
                     $holders[] = '`{primary}` = ?';
                 }
                 $statement = 'INSERT INTO `{self}` SET ' . implode(', ', $holders);
                 $statement = $this->prepare($statement);
                 $rc = $statement->execute($filtered);
             } else {
                 if ($driver_name == 'sqlite') {
                     $rc = $this->insert($values, $options);
                 }
             }
         }
     } else {
         if ($parent_id && !$id) {
             #
             # a new entry has been created, but we don't have any other fields then the primary key
             #
             if (empty($identifiers[$this->primary])) {
                 $identifiers[] = '`{primary}`';
                 $filtered[] = $parent_id;
             }
             $identifiers = implode(', ', $identifiers);
             $placeholders = implode(', ', array_fill(0, count($filtered), '?'));
             $statement = "INSERT INTO `{self}` ({$identifiers}) VALUES ({$placeholders})";
             $statement = $this->prepare($statement);
             $rc = $statement->execute($filtered);
         } else {
             $rc = true;
         }
     }
     if ($parent_id) {
         return $parent_id;
     }
     if (!$rc) {
         return false;
     }
     if (!$id) {
         $id = $this->connection->lastInsertId();
     }
     return $id;
 }