Ejemplo n.º 1
0
 public function testSetWhere()
 {
     $push = new LeanPush(array("alert" => "Hello world!"));
     $query = new LeanQuery("_Installation");
     $date = new DateTime();
     $query->lessThan("updatedAt", $date);
     $push->setWhere($query);
     $out = $push->encode();
     $this->assertEquals(array("updatedAt" => array('$lt' => LeanClient::encode($date))), $out["where"]);
 }
Ejemplo n.º 2
0
 public function testOperationEncode()
 {
     $op = new SetOperation("name", "alice");
     $this->assertEquals($op->encode(), "alice");
     $op = new SetOperation("score", 70.0);
     $this->assertEquals($op->encode(), 70.0);
     $date = new DateTime();
     $op = new SetOperation("released", $date);
     $out = $op->encode();
     $this->assertEquals($out['__type'], "Date");
     $this->assertEquals($out['iso'], LeanClient::formatDate($date));
 }
Ejemplo n.º 3
0
 public static function setUpBeforeClass()
 {
     LeanClient::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY"));
     LeanClient::useRegion(getenv("LC_API_REGION"));
     LeanClient::setStorage(new SessionStorage());
     // Try to make a default user so we can login
     $user = new LeanUser();
     $user->setUsername("alice");
     $user->setPassword("blabla");
     try {
         $user->signUp();
     } catch (CloudException $ex) {
         // skip
     }
 }
Ejemplo n.º 4
0
 private function request($url, $method, $data = null)
 {
     $appUrl = "http://" . getenv("LC_APP_HOST") . ":" . getenv("LC_APP_PORT");
     $url = $appUrl . $url;
     $headers = LeanClient::buildHeaders(null, true);
     $headers["Content-Type"] = "application/json;charset=utf-8";
     $headers["Origin"] = getenv("LC_APP_HOST");
     // emulate CORS
     $h = array_map(function ($k, $v) {
         return "{$k}: {$v}";
     }, array_keys($headers), $headers);
     $req = curl_init($url);
     curl_setopt($req, CURLOPT_HTTPHEADER, $h);
     curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
     if ($method == "POST") {
         curl_setopt($req, CURLOPT_POST, 1);
         curl_setopt($req, CURLOPT_POSTFIELDS, json_encode($data));
     } else {
         // GET
         if ($data) {
             curl_setopt($req, CURLOPT_URL, $url . "?" . http_build_query($data));
         }
     }
     $resp = curl_exec($req);
     $errno = curl_errno($req);
     curl_close($req);
     if ($errno > 0) {
         throw new \RuntimeException("CURL connection error {$errno}: {$url}");
     }
     $data = json_decode($resp, true);
     if (isset($data["error"])) {
         $code = isset($data["code"]) ? $data["code"] : -1;
         throw new CloudException("{$code} {$data['error']}", $code);
     }
     return $data;
 }
Ejemplo n.º 5
0
 public function testUserLogin()
 {
     $data = array("username" => "testuser", "password" => "5akf#a?^G", "phone" => "18612340000");
     $resp = LeanClient::post("/users", $data);
     $this->assertNotEmpty($resp["objectId"]);
     $this->assertNotEmpty($resp["sessionToken"]);
     $id = $resp["objectId"];
     $resp = LeanClient::get("/users/me", array("session_token" => $resp["sessionToken"]));
     $this->assertNotEmpty($resp["objectId"]);
     LeanClient::delete("/users/{$id}", $resp["sessionToken"]);
     // Raise 211: Could not find user.
     $this->setExpectedException("LeanCloud\\CloudException", null, 211);
     $resp = LeanClient::get("/users/me", array("session_token" => "non-existent-token"));
 }
Ejemplo n.º 6
0
 /**
  * Delete objects in batch.
  *
  * @param array $objects Array of LeanObjects to destroy
  * @return bool
  */
 public static function destroyAll($objects)
 {
     $batch = array();
     foreach ($objects as $obj) {
         if (!$obj->getObjectId()) {
             throw new \ErrorException("Cannot destroy object without ID");
         }
         // Remove duplicate objects by ID
         $batch[$obj->getObjectId()] = $obj;
     }
     if (empty($batch)) {
         return;
     }
     $requests = array();
     $objects = array();
     foreach ($batch as $obj) {
         $requests[] = array("path" => "/1.1/classes/{$obj->getClassName()}" . "/{$obj->getObjectId()}", "method" => "DELETE");
         $objects[] = $obj;
     }
     $response = LeanClient::batch($requests);
     $errors = array();
     foreach ($objects as $i => $obj) {
         if (isset($response[$i]["error"])) {
             $errors[] = array("request" => $requests[$i], "error" => $response[$i]["error"]);
         }
     }
     if (count($errors) > 0) {
         throw new \LeanException("Batch requests error: " . json_encode($errors));
     }
 }
Ejemplo n.º 7
0
 public function testDecodeFile()
 {
     $type = array("__type" => "File", "objectId" => "abc101", "name" => "favicon.ico", "url" => "https://leancloud.cn/favicon.ico");
     $val = LeanClient::decode($type);
     $this->assertTrue($val instanceof LeanFile);
     $this->assertEquals($type["objectId"], $val->getObjectId());
     $this->assertEquals($type["name"], $val->getName());
     $this->assertEquals($type["url"], $val->getUrl());
 }
Ejemplo n.º 8
0
 public function testDecodeBytes()
 {
     $type = array("__type" => "Bytes", "base64" => base64_encode("Hello"));
     $val = LeanClient::decode($type);
     $this->assertTrue($val instanceof LeanBytes);
     $this->assertEquals(array(72, 101, 108, 108, 111), $val->getByteArray());
 }
Ejemplo n.º 9
0
 /**
  * Count number of objects by the query
  *
  * @return int
  */
 public function count()
 {
     $params = $this->encode();
     $params["limit"] = 0;
     $params["count"] = 1;
     $resp = LeanClient::get("/classes/{$this->getClassName()}", $params);
     return $resp["count"];
 }
Ejemplo n.º 10
0
 /**
  * Encode to JSON represented operation
  *
  * @return array
  */
 public function encode()
 {
     return array("__op" => $this->getOpType(), "objects" => LeanClient::encode($this->value));
 }
Ejemplo n.º 11
0
<?php

require_once "src/autoload.php";
use LeanCloud\LeanClient;
use LeanCloud\Engine\LeanEngine;
use LeanCloud\Engine\Cloud;
LeanClient::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY"));
// define a function
Cloud::define("hello", function () {
    return "hello";
});
// define function with named params
Cloud::define("sayHello", function ($params, $user) {
    return "hello {$params['name']}";
});
Cloud::define("getMeta", function ($params, $user, $meta) {
    return array("remoteAddress" => $meta["remoteAddress"]);
});
Cloud::define("updateObject", function ($params, $user) {
    $obj = $params["object"];
    $obj->set("__testKey", 42);
    return $obj;
});
Cloud::onLogin(function ($user) {
    return;
});
Cloud::onInsight(function ($job) {
    return;
});
Cloud::onVerified("sms", function ($user) {
    return;
 /**
  * Initialize LeanCloud application id and key
  *
  * @return void
  */
 public function register()
 {
     LeanClient::initialize(config('services.leancloud.id'), config('services.leancloud.key'), config('services.leancloud.masterKey'));
 }
Ejemplo n.º 13
0
 * A simple Slim based sample application
 *
 * See Slim documentation:
 * http://www.slimframework.com/docs/
 */
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use LeanCloud\LeanClient;
use LeanCloud\Storage\CookieStorage;
use LeanCloud\Engine\SlimEngine;
$app = new \Slim\App();
// 禁用 Slim 默认的 handler,使得错误栈被日志捕捉
unset($app->getContainer()['errorHandler']);
LeanClient::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY"));
// 将 sessionToken 持久化到 cookie 中,以支持多实例共享会话
LeanClient::setStorage(new CookieStorage());
SlimEngine::enableHttpsRedirect();
$app->add(new SlimEngine());
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, {$name}");
    return $response;
});
// compute a random integer between min and max
$app->post('/randomInt', function (Request $request, Response $response) {
    // parse min and max from request body
    $body = $request->getBody();
    $json = json_decode($body, true);
    // or simply
    // $json = $request->getParsedBody();
    $val = rand($json["min"], $json["max"]);
Ejemplo n.º 14
0
 /**
  * Delete file on cloud
  *
  * @throws CloudException
  */
 public function destroy()
 {
     if (!$this->getObjectId()) {
         return false;
     }
     LeanClient::delete("/files/{$this->getObjectId()}");
 }
Ejemplo n.º 15
0
 public function testDecodeGeoPoint()
 {
     $type = array('__type' => 'GeoPoint', 'latitude' => 39.9, 'longitude' => 116.4);
     $val = LeanClient::decode($type, null);
     $this->assertTrue($val instanceof GeoPoint);
     $this->assertEquals(39.9, $val->getLatitude());
     $this->assertEquals(116.4, $val->getLongitude());
 }
Ejemplo n.º 16
0
 public function testEncodeCircularObjectAsPointer()
 {
     $a = new LeanObject("TestObject", "id001");
     $b = new LeanObject("TestObject", "id002");
     $c = new LeanObject("TestObject", "id003");
     $a->set("name", "A");
     $b->set("name", "B");
     $c->set("name", "C");
     $a->addIn("likes", $b);
     $b->addIn("likes", $c);
     $c->addIn("likes", $a);
     $jsonA = LeanClient::encode($a, "toFullJSON");
     $jsonB = $jsonA["likes"][0];
     $jsonC = $jsonB["likes"][0];
     $this->assertEquals("Object", $jsonA["__type"]);
     $this->assertEquals("Object", $jsonB["__type"]);
     $this->assertEquals("Object", $jsonC["__type"]);
     $this->assertEquals("Pointer", $jsonC["likes"][0]["__type"]);
 }
Ejemplo n.º 17
0
 /**
  * Verify mobile phone by SMS code
  *
  * @param string $smsCode
  */
 public static function verifyMobilePhone($smsCode)
 {
     LeanClient::post("/verifyMobilePhone/{$smsCode}", null);
 }
Ejemplo n.º 18
0
 public function testBatchGetNotFound()
 {
     $obj = array("name" => "alice");
     $resp = LeanClient::post("/classes/TestObject", $obj);
     $this->assertNotEmpty($resp["objectId"]);
     $req[] = array("path" => "/1.1/classes/TestObject/{$resp['objectId']}", "method" => "GET");
     $req[] = array("path" => "/1.1/classes/TestObject/nonexistent_id", "method" => "GET");
     $resp2 = LeanClient::batch($req);
     $this->assertNotEmpty($resp2[0]["success"]);
     $this->assertEmpty($resp2[1]["success"]);
     // empty when not found
     LeanClient::delete("/classes/TestObject/{$resp['objectId']}");
 }
Ejemplo n.º 19
0
 /**
  * Encode to JSON represented operation
  *
  * @return array
  */
 public function encode()
 {
     return LeanClient::encode($this->value);
 }
Ejemplo n.º 20
0
 /**
  * Issue a batch request
  *
  * @param array  $requests     Array of requests in batch op
  * @param string $sessionToken Session token of a LeanUser
  * @param array  $headers      Optional headers
  * @param bool   $useMasterkey Use master key or not, optional
  * @return array              JSON decoded associated array
  * @see ::request
  */
 public static function batch($requests, $sessionToken = null, $headers = array(), $useMasterKey = false)
 {
     $response = LeanClient::post("/batch", array("requests" => $requests), $sessionToken, $headers, $useMasterKey);
     if (count($requests) != count($response)) {
         throw new CloudException("Number of resquest and response " . "mismatch in batch operation!");
     }
     return $response;
 }
Ejemplo n.º 21
0
 /**
  * Dispatch onLogin hook
  *
  * @param array $body JSON decoded body params
  */
 private function dispatchOnLogin($body)
 {
     $userObj = LeanClient::decode($body["object"], null);
     $meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
     try {
         Cloud::runOnLogin($userObj, $meta);
     } catch (FunctionError $err) {
         $this->renderError($err->getMessage(), $err->getCode());
     }
     $this->renderJSON(array("result" => "ok"));
 }
Ejemplo n.º 22
0
 public static function setUpBeforeClass()
 {
     LeanClient::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY"));
     LeanClient::useRegion(getenv("LC_API_REGION"));
 }
Ejemplo n.º 23
0
 /**
  * Doing a CQL query to retrive objects
  *
  * It returns an array that contains:
  *
  * * className - Class name of the query
  * * results   - List of objects
  * * count     - Number of objects when it's a count query
  *
  * @param string $cql     CQL statement
  * @param array  $pvalues Positional values to replace in CQL
  * @return array
  * @link https://leancloud.cn/docs/cql_guide.html
  */
 public static function doCloudQuery($cql, $pvalues = array())
 {
     $data = array("cql" => $cql);
     if (!empty($pvalues)) {
         $data["pvalues"] = json_encode(LeanClient::encode($pvalues));
     }
     $resp = LeanClient::get('/cloudQuery', $data);
     $objects = array();
     foreach ($resp["results"] as $val) {
         $obj = LeanObject::create($resp["className"], $val["objectId"]);
         $obj->mergeAfterFetch($val);
         $objects[] = $obj;
     }
     $resp["results"] = $objects;
     return $resp;
 }