Google\Cloud\Datastore\DatastoreSessionHandler::write PHP Method

write() public method

Write the session data to Cloud Datastore.
public write ( $id, $data )
    public function write($id, $data)
    {
        try {
            $key = $this->datastore->key($this->kind, $id, ['namespaceId' => $this->namespaceId]);
            $entity = $this->datastore->entity($key, ['data' => $data, 't' => time()]);
            $this->transaction->upsert($entity);
            $this->transaction->commit();
        } catch (Exception $e) {
            trigger_error(sprintf('Datastore upsert failed: %s', $e->getMessage()), E_USER_WARNING);
            return false;
        }
        return true;
    }

Usage Example

 /**
  * @expectedException PHPUnit_Framework_Error_Warning
  */
 public function testWriteWithException()
 {
     $data = 'sessiondata';
     $key = new Key('projectid');
     $key->pathElement(self::KIND, 'sessionid');
     $entity = new Entity($key, ['data' => $data]);
     $this->transaction->upsert($entity)->shouldBeCalledTimes(1);
     $this->transaction->commit()->shouldBeCalledTimes(1)->willThrow(new Exception());
     $this->datastore->transaction()->shouldBeCalledTimes(1)->willReturn($this->transaction->reveal());
     $this->datastore->key(self::KIND, 'sessionid', ['namespaceId' => self::NAMESPACE_ID])->shouldBeCalledTimes(1)->willReturn($key);
     $that = $this;
     $this->datastore->entity($key, Argument::type('array'))->will(function ($args) use($that, $key, $entity) {
         $that->assertEquals($key, $args[0]);
         $that->assertEquals('sessiondata', $args[1]['data']);
         $that->assertInternalType('int', $args[1]['t']);
         $that->assertTrue(time() >= $args[1]['t']);
         // 2 seconds grace period should be enough
         $that->assertTrue(time() - $args[1]['t'] <= 2);
         return $entity;
     });
     $datastoreSessionHandler = new DatastoreSessionHandler($this->datastore->reveal());
     $datastoreSessionHandler->open(self::NAMESPACE_ID, self::KIND);
     $ret = $datastoreSessionHandler->write('sessionid', $data);
     $this->assertEquals(false, $ret);
 }