Cake\ORM\Table::_insert PHP Method

_insert() protected method

Auxiliary function to handle the insert of an entity's data in the table
protected _insert ( Cake\Datasource\EntityInterface $entity, array $data ) : Cake\Datasource\EntityInterface | boolean
$entity Cake\Datasource\EntityInterface the subject entity from were $data was extracted
$data array The actual data that needs to be saved
return Cake\Datasource\EntityInterface | boolean
    protected function _insert($entity, $data)
    {
        $primary = (array) $this->primaryKey();
        if (empty($primary)) {
            $msg = sprintf('Cannot insert row in "%s" table, it has no primary key.', $this->table());
            throw new RuntimeException($msg);
        }
        $keys = array_fill(0, count($primary), null);
        $id = (array) $this->_newId($primary) + $keys;
        // Generate primary keys preferring values in $data.
        $primary = array_combine($primary, $id);
        $primary = array_intersect_key($data, $primary) + $primary;
        $filteredKeys = array_filter($primary, 'strlen');
        $data = $data + $filteredKeys;
        if (count($primary) > 1) {
            $schema = $this->schema();
            foreach ($primary as $k => $v) {
                if (!isset($data[$k]) && empty($schema->column($k)['autoIncrement'])) {
                    $msg = 'Cannot insert row, some of the primary key values are missing. ';
                    $msg .= sprintf('Got (%s), expecting (%s)', implode(', ', $filteredKeys + $entity->extract(array_keys($primary))), implode(', ', array_keys($primary)));
                    throw new RuntimeException($msg);
                }
            }
        }
        $success = false;
        if (empty($data)) {
            return $success;
        }
        $statement = $this->query()->insert(array_keys($data))->values($data)->execute();
        if ($statement->rowCount() !== 0) {
            $success = $entity;
            $entity->set($filteredKeys, ['guard' => false]);
            $schema = $this->schema();
            $driver = $this->connection()->driver();
            foreach ($primary as $key => $v) {
                if (!isset($data[$key])) {
                    $id = $statement->lastInsertId($this->table(), $key);
                    $type = $schema->columnType($key);
                    $entity->set($key, Type::build($type)->toPHP($id, $driver));
                    break;
                }
            }
        }
        $statement->closeCursor();
        return $success;
    }