Google\Cloud\Datastore\Operation::allocateIds PHP Method

allocateIds() public method

Keys MUST be in an incomplete state (i.e. including a kind but not an ID or name in their final pathElement). This method will execute a service request.
See also: https://cloud.google.com/datastore/reference/rest/v1/projects/allocateIds allocateIds
public allocateIds ( array $keys, array $options = [] ) : Key[]
$keys array The incomplete keys.
$options array [optional] Configuration Options.
return Key[]
    public function allocateIds(array $keys, array $options = [])
    {
        // Validate the given keys. First check types, then state of each.
        // The API will throw a 400 if the key is named, but it's an easy
        // check we can handle before going to the API to save a request.
        // @todo replace with json schema
        $this->validateBatch($keys, Key::class, function ($key) {
            if ($key->state() !== Key::STATE_INCOMPLETE) {
                throw new InvalidArgumentException(sprintf('Given $key is in an invalid state. Can only allocate IDs for incomplete keys. ' . 'Given path was %s', (string) $key));
            }
        });
        $res = $this->connection->allocateIds(['projectId' => $this->projectId, 'keys' => $keys] + $options);
        if (isset($res['keys'])) {
            foreach ($res['keys'] as $index => $key) {
                if (!isset($keys[$index])) {
                    continue;
                }
                $end = end($key['path']);
                $id = $end['id'];
                $keys[$index]->setLastElementIdentifier($id);
            }
        }
        return $keys;
    }

Usage Example

 /**
  * Allocate available IDs to a set of keys
  *
  * Keys MUST be in an incomplete state (i.e. including a kind but not an ID
  * or name in their final pathElement).
  *
  * This method will execute a service request.
  *
  * Example:
  * ```
  * $keys = [
  *     $datastore->key('Person'),
  *     $datastore->key('Person')
  * ];
  *
  * $keysWithAllocatedIds = $datastore->allocateIds($keys);
  * ```
  *
  * @see https://cloud.google.com/datastore/reference/rest/v1/projects/allocateIds allocateIds
  *
  * @param Key[] $keys The incomplete keys.
  * @param array $options [optional] Configuration options.
  * @return Key[]
  */
 public function allocateIds(array $keys, array $options = [])
 {
     return $this->operation->allocateIds($keys, $options);
 }