| 1 |
<?php |
| 2 |
namespace Dropbox; |
| 3 |
|
| 4 |
/** |
| 5 |
* This class contains methods to load an AppInfo and AccessToken from a JSON file. |
| 6 |
* This can help simplify simple scripts (such as the example programs that come with the |
| 7 |
* SDK) but is probably not useful in typical Dropbox API apps. |
| 8 |
* |
| 9 |
*/ |
| 10 |
final class AuthInfo |
| 11 |
{ |
| 12 |
/** |
| 13 |
* Loads a JSON file containing authorization information for your app. 'php authorize.php' |
| 14 |
* in the examples directory for details about what this file should look like. |
| 15 |
* |
| 16 |
* @param string $path |
| 17 |
* Path to a JSON file |
| 18 |
* @return array |
| 19 |
* A <code>list(string $accessToken, Host $host)</code>. |
| 20 |
* |
| 21 |
* @throws AuthInfoLoadException |
| 22 |
*/ |
| 23 |
static function loadFromJsonFile($path) |
| 24 |
{ |
| 25 |
if (!file_exists($path)) { |
| 26 |
throw new AuthInfoLoadException("File doesn't exist: \"$path\""); |
| 27 |
} |
| 28 |
|
| 29 |
$str = Util::stripUtf8Bom(file_get_contents($path)); |
| 30 |
$jsonArr = json_decode($str, true, 10); |
| 31 |
|
| 32 |
if (is_null($jsonArr)) { |
| 33 |
throw new AuthInfoLoadException("JSON parse error: \"$path\""); |
| 34 |
} |
| 35 |
|
| 36 |
return self::loadFromJson($jsonArr); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Parses a JSON object to build an AuthInfo object. If you would like to load this from a file, |
| 41 |
* please use the @see loadFromJsonFile method. |
| 42 |
* |
| 43 |
* @param array $jsonArr |
| 44 |
* A parsed JSON object, typcally the result of json_decode(..., true). |
| 45 |
* @return array |
| 46 |
* A <code>list(string $accessToken, Host $host)</code>. |
| 47 |
* |
| 48 |
* @throws AuthInfoLoadException |
| 49 |
*/ |
| 50 |
private static function loadFromJson($jsonArr) |
| 51 |
{ |
| 52 |
if (!is_array($jsonArr)) { |
| 53 |
throw new AuthInfoLoadException("Expecting JSON object, found something else"); |
| 54 |
} |
| 55 |
|
| 56 |
// Check access_token |
| 57 |
if (!array_key_exists('access_token', $jsonArr)) { |
| 58 |
throw new AuthInfoLoadException("Missing field \"access_token\""); |
| 59 |
} |
| 60 |
|
| 61 |
$accessToken = $jsonArr['access_token']; |
| 62 |
if (!is_string($accessToken)) { |
| 63 |
throw new AuthInfoLoadException("Expecting field \"access_token\" to be a string"); |
| 64 |
} |
| 65 |
|
| 66 |
// Check for the optional 'host' field |
| 67 |
if (!array_key_exists('host', $jsonArr)) { |
| 68 |
$host = null; |
| 69 |
} |
| 70 |
else { |
| 71 |
$baseHost = $jsonArr["host"]; |
| 72 |
if (!is_string($baseHost)) { |
| 73 |
throw new AuthInfoLoadException("Optional field \"host\" must be a string"); |
| 74 |
} |
| 75 |
|
| 76 |
$api = "api-$baseHost"; |
| 77 |
$content = "api-content-$baseHost"; |
| 78 |
$web = "meta-$baseHost"; |
| 79 |
|
| 80 |
$host = new Host($api, $content, $web); |
| 81 |
} |
| 82 |
|
| 83 |
return array($accessToken, $host); |
| 84 |
} |
| 85 |
} |
| 86 |
|