├── .editorconfig ├── .gitignore ├── .php_cs ├── .scrutinizer.yml ├── .styleci.yml ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── phpunit.xml ├── src └── Dropbox │ ├── Authentication │ ├── DropboxAuthHelper.php │ └── OAuth2Client.php │ ├── Dropbox.php │ ├── DropboxApp.php │ ├── DropboxClient.php │ ├── DropboxFile.php │ ├── DropboxRequest.php │ ├── DropboxResponse.php │ ├── DropboxResponseToFile.php │ ├── Exceptions │ └── DropboxClientException.php │ ├── Http │ ├── Clients │ │ ├── DropboxGuzzleHttpClient.php │ │ ├── DropboxHttpClientFactory.php │ │ └── DropboxHttpClientInterface.php │ ├── DropboxRawResponse.php │ ├── RequestBodyInterface.php │ ├── RequestBodyJsonEncoded.php │ └── RequestBodyStream.php │ ├── Models │ ├── AccessToken.php │ ├── Account.php │ ├── AccountList.php │ ├── BaseModel.php │ ├── CopyReference.php │ ├── DeletedMetadata.php │ ├── File.php │ ├── FileMetadata.php │ ├── FileSharingInfo.php │ ├── FolderMetadata.php │ ├── FolderSharingInfo.php │ ├── MediaInfo.php │ ├── MediaMetadata.php │ ├── MetadataCollection.php │ ├── ModelCollection.php │ ├── ModelFactory.php │ ├── ModelInterface.php │ ├── PhotoMetadata.php │ ├── SearchResult.php │ ├── SearchResults.php │ ├── TemporaryLink.php │ ├── Thumbnail.php │ └── VideoMetadata.php │ ├── Security │ ├── McryptRandomStringGenerator.php │ ├── OpenSslRandomStringGenerator.php │ ├── RandomStringGeneratorFactory.php │ ├── RandomStringGeneratorInterface.php │ └── RandomStringGeneratorTrait.php │ └── Store │ ├── PersistentDataStoreFactory.php │ ├── PersistentDataStoreInterface.php │ └── SessionPersistentDataStore.php └── tests ├── DropboxFileTest.php └── DropboxTest.php /.editorconfig: -------------------------------------------------------------------------------- 1 | ; This file is for unifying the coding style for different editors and IDEs. 2 | ; More information at http://editorconfig.org 3 | 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | indent_size = 4 9 | indent_style = space 10 | end_of_line = lf 11 | insert_final_newline = true 12 | trim_trailing_whitespace = true 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | index.php 2 | .phpintel/ 3 | /vendor/ 4 | composer.lock 5 | /.idea 6 | .php_cs.cache 7 | -------------------------------------------------------------------------------- /.php_cs: -------------------------------------------------------------------------------- 1 | setRiskyAllowed(true) 8 | ->setRules([ 9 | '@PSR2' => true, 10 | 'array_syntax' => ['syntax' => 'short'], 11 | 'combine_consecutive_unsets' => true, 12 | 'heredoc_to_nowdoc' => true, 13 | 'list_syntax' => ['syntax' => 'long'], 14 | 'no_extra_consecutive_blank_lines' => ['break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block'], 15 | 'no_short_echo_tag' => true, 16 | 'no_unreachable_default_argument_value' => true, 17 | 'no_useless_else' => true, 18 | 'no_useless_return' => true, 19 | 'ordered_class_elements' => true, 20 | 'ordered_imports' => ['sortAlgorithm' => 'length'], 21 | 'phpdoc_add_missing_param_annotation' => true, 22 | 'phpdoc_order' => true, 23 | 'semicolon_after_instruction' => true, 24 | 'phpdoc_summary' => true, 25 | 'strict_comparison' => true, 26 | 'strict_param' => true, 27 | ]) 28 | ->setFinder( 29 | PhpCsFixer\Finder::create() 30 | ->exclude($vendorDir) 31 | ->in($sourceDir) 32 | ); 33 | -------------------------------------------------------------------------------- /.scrutinizer.yml: -------------------------------------------------------------------------------- 1 | filter: 2 | excluded_paths: [tests/*] 3 | 4 | checks: 5 | php: 6 | remove_extra_empty_lines: true 7 | remove_php_closing_tag: true 8 | remove_trailing_whitespace: true 9 | fix_use_statements: 10 | remove_unused: true 11 | preserve_multiple: false 12 | preserve_blanklines: true 13 | order_alphabetically: true 14 | fix_php_opening_tag: true 15 | fix_linefeed: true 16 | fix_line_ending: true 17 | fix_identation_4spaces: true 18 | fix_doc_comments: true 19 | tools: 20 | external_code_coverage: true 21 | build: false 22 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | risky: false 2 | version: 7.4 3 | preset: psr2 4 | tab-width: 4 5 | use-tabs: false 6 | disabled: 7 | - single_class_element_per_statement 8 | finder: 9 | exclude: 10 | - "modules" 11 | - "node_modules" 12 | - "nova" 13 | - "nova-components" 14 | - "storage" 15 | - "spark" 16 | - "vendor" 17 | name: "*.php" 18 | not-name: 19 | - "*.blade.php" 20 | - "_ide_helper.php" 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | php: 4 | - 7 5 | 6 | sudo: false 7 | 8 | cache: 9 | directories: 10 | - $HOME/.composer/cache 11 | 12 | before_install: 13 | - composer validate 14 | 15 | before_script: 16 | - travis_retry composer self-update 17 | - travis_retry composer update --no-interaction --prefer-source 18 | 19 | script: 20 | - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover 21 | 22 | after_script: 23 | - wget https://scrutinizer-ci.com/ocular.phar 24 | - php ocular.phar code-coverage:upload --format=php-clover coverage.clover 25 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Kunal Varma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Dropbox SDK v2 for PHP 2 | ====================================================== 3 | [![Latest Stable Version](https://poser.pugx.org/kunalvarma05/dropbox-php-sdk/v/stable?format=flat-square)](https://packagist.org/packages/kunalvarma05/dropbox-php-sdk) 4 | [![Build Status](https://img.shields.io/travis/kunalvarma05/dropbox-php-sdk.svg?style=flat-square)](https://travis-ci.org/kunalvarma05/dropbox-php-sdk) 5 | [![Quality Score](https://img.shields.io/scrutinizer/g/kunalvarma05/dropbox-php-sdk.svg?style=flat-square)](https://scrutinizer-ci.com/g/kunalvarma05/dropbox-php-sdk) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/kunalvarma05/dropbox-php-sdk.svg?style=flat-square)](https://packagist.org/packages/kunalvarma05/dropbox-php-sdk) 7 | [![StyleCI](https://styleci.io/repos/61913555/shield?branch=master)](https://styleci.io/repos/61913555) 8 | [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://packagist.org/packages/kunalvarma05/dropbox-php-sdk) 9 | 10 | 11 | An unofficial PHP SDK to work with the [Dropbox API v2](https://www.dropbox.com/developers/documentation/http/documentation). 12 | 13 | 14 | 15 | 16 | ## Get Started 17 | Head over to the [**Getting Started**](https://github.com/kunalvarma05/dropbox-php-sdk/wiki/Getting-Started) Wiki section to Install and Get started. 18 | 19 | 20 | ## API Docs 21 | [**View API Docs**](https://kunalvarma05.github.io/dropbox-php-sdk/) 22 | 23 | 24 | ## License 25 | Dropbox PHP Client is licensed under The MIT License (MIT). 26 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kunalvarma05/dropbox-php-sdk", 3 | "description": "Dropbox PHP API V2 SDK (Unofficial)", 4 | "keywords" : ["dropbox", "sdk", "api", "client", "php", "unofficial"], 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Kunal Varma", 9 | "email": "kunalvarma05@gmail.com" 10 | } 11 | ], 12 | "require": { 13 | "guzzlehttp/guzzle": "~6.0|~7.0", 14 | "illuminate/collections": "^8.0|^9.0|^10.0|^11.0" 15 | }, 16 | "autoload": { 17 | "psr-4": { 18 | "Kunnu\\Dropbox\\": "src/Dropbox" 19 | } 20 | }, 21 | "require-dev": { 22 | "phpunit/phpunit": "^6.0" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/Dropbox/Authentication/DropboxAuthHelper.php: -------------------------------------------------------------------------------- 1 | oAuth2Client = $oAuth2Client; 59 | $this->randomStringGenerator = $randomStringGenerator; 60 | $this->persistentDataStore = $persistentDataStore; 61 | } 62 | 63 | /** 64 | * Get OAuth2Client 65 | * 66 | * @return \Kunnu\Dropbox\Authentication\OAuth2Client 67 | */ 68 | public function getOAuth2Client() 69 | { 70 | return $this->oAuth2Client; 71 | } 72 | 73 | /** 74 | * Get the Random String Generator 75 | * 76 | * @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface 77 | */ 78 | public function getRandomStringGenerator() 79 | { 80 | return $this->randomStringGenerator; 81 | } 82 | 83 | /** 84 | * Get the Persistent Data Store 85 | * 86 | * @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface 87 | */ 88 | public function getPersistentDataStore() 89 | { 90 | return $this->persistentDataStore; 91 | } 92 | 93 | /** 94 | * Get CSRF Token 95 | * 96 | * @return string 97 | */ 98 | protected function getCsrfToken() 99 | { 100 | $generator = $this->getRandomStringGenerator(); 101 | 102 | return $generator->generateString(static::CSRF_LENGTH); 103 | } 104 | 105 | /** 106 | * Get Authorization URL 107 | * 108 | * @param string $redirectUri Callback URL to redirect to after authorization 109 | * @param array $params Additional Params 110 | * @param string $urlState Additional User Provided State Data 111 | * @param string $tokenAccessType Either `offline` or `online` or null 112 | * 113 | * @link https://www.dropbox.com/developers/documentation/http/documentation#oauth2-authorize 114 | * 115 | * @return string 116 | */ 117 | public function getAuthUrl($redirectUri = null, array $params = [], $urlState = null, $tokenAccessType = null) 118 | { 119 | // If no redirect URI 120 | // is provided, the 121 | // CSRF validation 122 | // is being handled 123 | // explicitly. 124 | $state = null; 125 | 126 | // Redirect URI is provided 127 | // thus, CSRF validation 128 | // needs to be handled. 129 | if (!is_null($redirectUri)) { 130 | //Get CSRF State Token 131 | $state = $this->getCsrfToken(); 132 | 133 | //Set the CSRF State Token in the Persistent Data Store 134 | $this->getPersistentDataStore()->set('state', $state); 135 | 136 | //Additional User Provided State Data 137 | if (!is_null($urlState)) { 138 | $state .= "|"; 139 | $state .= $urlState; 140 | } 141 | } 142 | 143 | //Get OAuth2 Authorization URL 144 | return $this->getOAuth2Client()->getAuthorizationUrl($redirectUri, $state, $params, $tokenAccessType); 145 | } 146 | 147 | /** 148 | * Decode State to get the CSRF Token and the URL State 149 | * 150 | * @param string $state State 151 | * 152 | * @return array 153 | */ 154 | protected function decodeState($state) 155 | { 156 | $csrfToken = $state; 157 | $urlState = null; 158 | 159 | $splitPos = strpos($state, "|"); 160 | 161 | if ($splitPos !== false) { 162 | $csrfToken = substr($state, 0, $splitPos); 163 | $urlState = substr($state, $splitPos + 1); 164 | } 165 | 166 | return ['csrfToken' => $csrfToken, 'urlState' => $urlState]; 167 | } 168 | 169 | /** 170 | * Validate CSRF Token 171 | * @param string $csrfToken CSRF Token 172 | * 173 | * @throws DropboxClientException 174 | * 175 | * @return void 176 | */ 177 | protected function validateCSRFToken($csrfToken) 178 | { 179 | $tokenInStore = $this->getPersistentDataStore()->get('state'); 180 | 181 | //Unable to fetch CSRF Token 182 | if (!$tokenInStore || !$csrfToken) { 183 | throw new DropboxClientException("Invalid CSRF Token. Unable to validate CSRF Token."); 184 | } 185 | 186 | //CSRF Token Mismatch 187 | if ($tokenInStore !== $csrfToken) { 188 | throw new DropboxClientException("Invalid CSRF Token. CSRF Token Mismatch."); 189 | } 190 | 191 | //Clear the state store 192 | $this->getPersistentDataStore()->clear('state'); 193 | } 194 | 195 | /** 196 | * Get Access Token 197 | * 198 | * @param string $code Authorization Code 199 | * @param string $state CSRF & URL State 200 | * @param string $redirectUri Redirect URI used while getAuthUrl 201 | * 202 | * @return \Kunnu\Dropbox\Models\AccessToken 203 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 204 | */ 205 | public function getAccessToken($code, $state = null, $redirectUri = null) 206 | { 207 | // No state provided 208 | // Should probably be 209 | // handled explicitly 210 | if (!is_null($state)) { 211 | //Decode the State 212 | $state = $this->decodeState($state); 213 | 214 | //CSRF Token 215 | $csrfToken = $state['csrfToken']; 216 | 217 | //Set the URL State 218 | $this->urlState = $state['urlState']; 219 | 220 | //Validate CSRF Token 221 | $this->validateCSRFToken($csrfToken); 222 | } 223 | 224 | //Fetch Access Token 225 | $accessToken = $this->getOAuth2Client()->getAccessToken($code, $redirectUri); 226 | 227 | //Make and return the model 228 | return new AccessToken($accessToken); 229 | } 230 | 231 | /** 232 | * Get new Access Token by using the refresh token 233 | * 234 | * @param \Kunnu\Dropbox\Models\AccessToken $accessToken - Current access token object 235 | * @param string $grantType ['refresh_token'] 236 | */ 237 | public function getRefreshedAccessToken($accessToken, $grantType = 'refresh_token') 238 | { 239 | $newToken = $this->getOAuth2Client()->getAccessToken($accessToken->refresh_token, null, $grantType); 240 | 241 | return new AccessToken( 242 | array_merge( 243 | $accessToken->getData(), 244 | $newToken 245 | ) 246 | ); 247 | } 248 | 249 | /** 250 | * Revoke Access Token 251 | * 252 | * @return void 253 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 254 | */ 255 | public function revokeAccessToken() 256 | { 257 | $this->getOAuth2Client()->revokeAccessToken(); 258 | } 259 | 260 | /** 261 | * Get URL State 262 | * 263 | * @return string 264 | */ 265 | public function getUrlState() 266 | { 267 | return $this->urlState; 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /src/Dropbox/Authentication/OAuth2Client.php: -------------------------------------------------------------------------------- 1 | app = $app; 57 | $this->client = $client; 58 | $this->randStrGenerator = $randStrGenerator; 59 | } 60 | 61 | /** 62 | * Build URL 63 | * 64 | * @param string $endpoint 65 | * @param array $params Query Params 66 | * 67 | * @return string 68 | */ 69 | protected function buildUrl($endpoint = '', array $params = []) 70 | { 71 | $queryParams = http_build_query($params, '', '&'); 72 | return static::BASE_URL . $endpoint . '?' . $queryParams; 73 | } 74 | 75 | /** 76 | * Get the Dropbox App 77 | * 78 | * @return \Kunnu\Dropbox\DropboxApp 79 | */ 80 | public function getApp() 81 | { 82 | return $this->app; 83 | } 84 | 85 | /** 86 | * Get the Dropbox Client 87 | * 88 | * @return \Kunnu\Dropbox\DropboxClient 89 | */ 90 | public function getClient() 91 | { 92 | return $this->client; 93 | } 94 | 95 | /** 96 | * Get the OAuth2 Authorization URL 97 | * 98 | * @param string $redirectUri Callback URL to redirect user after authorization. 99 | * If null is passed, redirect_uri will be omitted 100 | * from the url and the code will be presented directly 101 | * to the user. 102 | * @param string $state CSRF Token 103 | * @param array $params Additional Params 104 | * @param string $tokenAccessType Either `offline` or `online` or null 105 | * 106 | * @link https://www.dropbox.com/developers/documentation/http/documentation#oauth2-authorize 107 | * 108 | * @return string 109 | */ 110 | public function getAuthorizationUrl($redirectUri = null, $state = null, array $params = [], $tokenAccessType = null) 111 | { 112 | //Request Parameters 113 | $params = array_merge([ 114 | 'client_id' => $this->getApp()->getClientId(), 115 | 'response_type' => 'code', 116 | 'state' => $state, 117 | 'token_access_type' => $tokenAccessType, 118 | ], $params); 119 | 120 | if (!is_null($redirectUri)) { 121 | $params['redirect_uri'] = $redirectUri; 122 | } 123 | 124 | return $this->buildUrl('/oauth2/authorize', $params); 125 | } 126 | 127 | /** 128 | * Get Access Token 129 | * 130 | * @param string $code Authorization Code | Refresh Token 131 | * @param string $redirectUri Redirect URI used while getAuthorizationUrl 132 | * @param string $grant_type Grant Type ['authorization_code' | 'refresh_token'] 133 | * 134 | * @return array 135 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 136 | */ 137 | public function getAccessToken($code, $redirectUri = null, $grant_type = 'authorization_code') 138 | { 139 | //Request Params 140 | $params = [ 141 | 'code' => $code, 142 | 'grant_type' => $grant_type, 143 | 'client_id' => $this->getApp()->getClientId(), 144 | 'client_secret' => $this->getApp()->getClientSecret(), 145 | 'redirect_uri' => $redirectUri, 146 | ]; 147 | 148 | if ($grant_type === 'refresh_token') { 149 | // 150 | $params = [ 151 | 'refresh_token' => $code, 152 | 'grant_type' => $grant_type, 153 | 'client_id' => $this->getApp()->getClientId(), 154 | 'client_secret' => $this->getApp()->getClientSecret(), 155 | ]; 156 | } 157 | 158 | $params = http_build_query($params, '', '&'); 159 | 160 | $apiUrl = static::AUTH_TOKEN_URL; 161 | $uri = $apiUrl . "?" . $params; 162 | 163 | //Send Request through the DropboxClient 164 | //Fetch the Response (DropboxRawResponse) 165 | $response = $this->getClient() 166 | ->getHttpClient() 167 | ->send($uri, "POST", null); 168 | 169 | //Fetch Response Body 170 | $body = $response->getBody(); 171 | 172 | //Decode the Response body to associative array 173 | //and return 174 | return json_decode((string) $body, true); 175 | } 176 | 177 | /** 178 | * Disables the access token 179 | * 180 | * @return void 181 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 182 | */ 183 | public function revokeAccessToken() 184 | { 185 | //Access Token 186 | $accessToken = $this->getApp()->getAccessToken(); 187 | 188 | //Request 189 | $request = new DropboxRequest("POST", "/auth/token/revoke", $accessToken); 190 | // Do not validate the response 191 | // since the /token/revoke endpoint 192 | // doesn't return anything in the response. 193 | // See: https://www.dropbox.com/developers/documentation/http/documentation#auth-token-revoke 194 | $request->setParams(['validateResponse' => false]); 195 | 196 | //Revoke Access Token 197 | $this->getClient()->sendRequest($request); 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/Dropbox/Dropbox.php: -------------------------------------------------------------------------------- 1 | null, 107 | 'random_string_generator' => null, 108 | 'persistent_data_store' => null 109 | ], $config); 110 | 111 | //Set the app 112 | $this->app = $app; 113 | 114 | //Set the access token 115 | $this->setAccessToken($app->getAccessToken()); 116 | 117 | //Make the HTTP Client 118 | $httpClient = DropboxHttpClientFactory::make($config['http_client_handler']); 119 | 120 | //Make and Set the DropboxClient 121 | $this->client = new DropboxClient($httpClient); 122 | 123 | //Make and Set the Random String Generator 124 | $this->randomStringGenerator = RandomStringGeneratorFactory::makeRandomStringGenerator($config['random_string_generator']); 125 | 126 | //Make and Set the Persistent Data Store 127 | $this->persistentDataStore = PersistentDataStoreFactory::makePersistentDataStore($config['persistent_data_store']); 128 | } 129 | 130 | /** 131 | * Get Dropbox Auth Helper 132 | * 133 | * @return \Kunnu\Dropbox\Authentication\DropboxAuthHelper 134 | */ 135 | public function getAuthHelper() 136 | { 137 | return new DropboxAuthHelper( 138 | $this->getOAuth2Client(), 139 | $this->getRandomStringGenerator(), 140 | $this->getPersistentDataStore() 141 | ); 142 | } 143 | 144 | /** 145 | * Get OAuth2Client 146 | * 147 | * @return \Kunnu\Dropbox\Authentication\OAuth2Client 148 | */ 149 | public function getOAuth2Client() 150 | { 151 | if (!$this->oAuth2Client instanceof OAuth2Client) { 152 | return new OAuth2Client( 153 | $this->getApp(), 154 | $this->getClient(), 155 | $this->getRandomStringGenerator() 156 | ); 157 | } 158 | 159 | return $this->oAuth2Client; 160 | } 161 | 162 | /** 163 | * Get the Dropbox App. 164 | * 165 | * @return \Kunnu\Dropbox\DropboxApp Dropbox App 166 | */ 167 | public function getApp() 168 | { 169 | return $this->app; 170 | } 171 | 172 | /** 173 | * Get the Client 174 | * 175 | * @return \Kunnu\Dropbox\DropboxClient 176 | */ 177 | public function getClient() 178 | { 179 | return $this->client; 180 | } 181 | 182 | /** 183 | * Get the Random String Generator 184 | * 185 | * @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface 186 | */ 187 | public function getRandomStringGenerator() 188 | { 189 | return $this->randomStringGenerator; 190 | } 191 | 192 | /** 193 | * Get Persistent Data Store 194 | * 195 | * @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface 196 | */ 197 | public function getPersistentDataStore() 198 | { 199 | return $this->persistentDataStore; 200 | } 201 | 202 | /** 203 | * Get the Metadata for a file or folder 204 | * 205 | * @param string $path Path of the file or folder 206 | * @param array $params Additional Params 207 | * 208 | * @return \Kunnu\Dropbox\Models\FileMetadata | \Kunnu\Dropbox\Models\FolderMetadata 209 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 210 | * 211 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata 212 | * 213 | */ 214 | public function getMetadata($path, array $params = []) 215 | { 216 | //Root folder is unsupported 217 | if ($path === '/') { 218 | throw new DropboxClientException("Metadata for the root folder is unsupported."); 219 | } 220 | 221 | //Set the path 222 | $params['path'] = $path; 223 | 224 | //Get File Metadata 225 | $response = $this->postToAPI('/files/get_metadata', $params); 226 | 227 | //Make and Return the Model 228 | return $this->makeModelFromResponse($response); 229 | } 230 | 231 | /** 232 | * Make a HTTP POST Request to the API endpoint type 233 | * 234 | * @param string $endpoint API Endpoint to send Request to 235 | * @param array $params Request Query Params 236 | * @param string $accessToken Access Token to send with the Request 237 | * 238 | * @return \Kunnu\Dropbox\DropboxResponse 239 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 240 | */ 241 | public function postToAPI($endpoint, array $params = [], $accessToken = null) 242 | { 243 | return $this->sendRequest("POST", $endpoint, 'api', $params, $accessToken); 244 | } 245 | 246 | /** 247 | * Make Request to the API 248 | * 249 | * @param string $method HTTP Request Method 250 | * @param string $endpoint API Endpoint to send Request to 251 | * @param string $endpointType Endpoint type ['api'|'content'] 252 | * @param array $params Request Query Params 253 | * @param string $accessToken Access Token to send with the Request 254 | * @param DropboxFile $responseFile Save response to the file 255 | * 256 | * @return \Kunnu\Dropbox\DropboxResponse 257 | * 258 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 259 | */ 260 | public function sendRequest($method, $endpoint, $endpointType = 'api', array $params = [], $accessToken = null, DropboxFile $responseFile = null) 261 | { 262 | //Access Token 263 | $accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken; 264 | 265 | //Make a DropboxRequest object 266 | $request = new DropboxRequest($method, $endpoint, $accessToken, $endpointType, $params); 267 | 268 | //Make a DropboxResponse object if a response should be saved to the file 269 | $response = $responseFile ? new DropboxResponseToFile($request, $responseFile) : null; 270 | 271 | //Send Request through the DropboxClient 272 | //Fetch and return the Response 273 | return $this->getClient()->sendRequest($request, $response); 274 | } 275 | 276 | /** 277 | * Get the Access Token. 278 | * 279 | * @return string Access Token 280 | */ 281 | public function getAccessToken() 282 | { 283 | return $this->accessToken; 284 | } 285 | 286 | /** 287 | * Set the Access Token. 288 | * 289 | * @param string $accessToken Access Token 290 | * 291 | * @return \Kunnu\Dropbox\Dropbox Dropbox Client 292 | */ 293 | public function setAccessToken($accessToken) 294 | { 295 | $this->accessToken = $accessToken; 296 | 297 | return $this; 298 | } 299 | 300 | /** 301 | * Make Model from DropboxResponse 302 | * 303 | * @param DropboxResponse $response 304 | * 305 | * @return \Kunnu\Dropbox\Models\ModelInterface 306 | * 307 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 308 | */ 309 | public function makeModelFromResponse(DropboxResponse $response) 310 | { 311 | //Get the Decoded Body 312 | $body = $response->getDecodedBody(); 313 | 314 | if (is_null($body)) { 315 | $body = []; 316 | } 317 | 318 | //Make and Return the Model 319 | return ModelFactory::make($body); 320 | } 321 | 322 | /** 323 | * Get the contents of a Folder 324 | * 325 | * @param string $path Path to the folder. Defaults to root. 326 | * @param array $params Additional Params 327 | * 328 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder 329 | * 330 | * @return \Kunnu\Dropbox\Models\MetadataCollection 331 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 332 | */ 333 | public function listFolder($path = null, array $params = []) 334 | { 335 | //Specify the root folder as an 336 | //empty string rather than as "/" 337 | if ($path === '/') { 338 | $path = ""; 339 | } 340 | 341 | //Set the path 342 | $params['path'] = $path; 343 | 344 | //Get File Metadata 345 | $response = $this->postToAPI('/files/list_folder', $params); 346 | 347 | //Make and Return the Model 348 | return $this->makeModelFromResponse($response); 349 | } 350 | 351 | /** 352 | * Paginate through all files and retrieve updates to the folder, 353 | * using the cursor retrieved from listFolder or listFolderContinue 354 | * 355 | * @param string $cursor The cursor returned by your 356 | * last call to listFolder or listFolderContinue 357 | * 358 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue 359 | * 360 | * @return \Kunnu\Dropbox\Models\MetadataCollection 361 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 362 | */ 363 | public function listFolderContinue($cursor) 364 | { 365 | $response = $this->postToAPI('/files/list_folder/continue', ['cursor' => $cursor]); 366 | 367 | //Make and Return the Model 368 | return $this->makeModelFromResponse($response); 369 | } 370 | 371 | /** 372 | * Get a cursor for the folder's state. 373 | * 374 | * @param string $path Path to the folder. Defaults to root. 375 | * @param array $params Additional Params 376 | * 377 | * @return string The Cursor for the folder's state 378 | * 379 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 380 | * 381 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor 382 | * 383 | */ 384 | public function listFolderLatestCursor($path, array $params = []) 385 | { 386 | //Specify the root folder as an 387 | //empty string rather than as "/" 388 | if ($path === '/') { 389 | $path = ""; 390 | } 391 | 392 | //Set the path 393 | $params['path'] = $path; 394 | 395 | //Fetch the cursor 396 | $response = $this->postToAPI('/files/list_folder/get_latest_cursor', $params); 397 | 398 | //Retrieve the cursor 399 | $body = $response->getDecodedBody(); 400 | $cursor = isset($body['cursor']) ? $body['cursor'] : false; 401 | 402 | //No cursor returned 403 | if (!$cursor) { 404 | throw new DropboxClientException("Could not retrieve cursor. Something went wrong."); 405 | } 406 | 407 | //Return the cursor 408 | return $cursor; 409 | } 410 | 411 | /** 412 | * Get Revisions of a File 413 | * 414 | * @param string $path Path to the file 415 | * @param array $params Additional Params 416 | * 417 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_revisions 418 | * 419 | * @return \Kunnu\Dropbox\Models\ModelCollection 420 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 421 | */ 422 | public function listRevisions($path, array $params = []) 423 | { 424 | //Set the Path 425 | $params['path'] = $path; 426 | 427 | //Fetch the Revisions 428 | $response = $this->postToAPI('/files/list_revisions', $params); 429 | 430 | //The file metadata of the entries, returned by this 431 | //endpoint doesn't include a '.tag' attribute, which 432 | //is used by the ModelFactory to resolve the correct 433 | //model. But since we know that revisions returned 434 | //are file metadata objects, we can explicitly cast 435 | //them as \Kunnu\Dropbox\Models\FileMetadata manually. 436 | $body = $response->getDecodedBody(); 437 | $entries = isset($body['entries']) ? $body['entries'] : []; 438 | $processedEntries = []; 439 | 440 | foreach ($entries as $entry) { 441 | $processedEntries[] = new FileMetadata($entry); 442 | } 443 | 444 | return new ModelCollection($processedEntries); 445 | } 446 | 447 | /** 448 | * Search a folder for files/folders 449 | * 450 | * @param string $path Path to search 451 | * @param string $query Search Query 452 | * @param array $params Additional Params 453 | * 454 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-search 455 | * 456 | * @return \Kunnu\Dropbox\Models\SearchResults 457 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 458 | */ 459 | public function search($path, $query, array $params = []) 460 | { 461 | //Specify the root folder as an 462 | //empty string rather than as "/" 463 | if ($path === '/') { 464 | $path = ""; 465 | } 466 | 467 | //Set the path and query 468 | $params['path'] = $path; 469 | $params['query'] = $query; 470 | 471 | //Fetch Search Results 472 | $response = $this->postToAPI('/files/search', $params); 473 | 474 | //Make and Return the Model 475 | return $this->makeModelFromResponse($response); 476 | } 477 | 478 | /** 479 | * Create a folder at the given path 480 | * 481 | * @param string $path Path to create 482 | * @param boolean $autorename Auto Rename File 483 | * 484 | * @return \Kunnu\Dropbox\Models\FolderMetadata 485 | * 486 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 487 | * 488 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder 489 | * 490 | */ 491 | public function createFolder($path, $autorename = false) 492 | { 493 | //Path cannot be null 494 | if (is_null($path)) { 495 | throw new DropboxClientException("Path cannot be null."); 496 | } 497 | 498 | //Create Folder 499 | $response = $this->postToAPI('/files/create_folder', ['path' => $path, 'autorename' => $autorename]); 500 | 501 | //Fetch the Metadata 502 | $body = $response->getDecodedBody(); 503 | 504 | //Make and Return the Model 505 | return new FolderMetadata($body); 506 | } 507 | 508 | /** 509 | * Delete a file or folder at the given path 510 | * 511 | * @param string $path Path to file/folder to delete 512 | * 513 | * @return \Kunnu\Dropbox\Models\DeletedMetadata 514 | * 515 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 516 | * 517 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete 518 | * 519 | */ 520 | public function delete($path) 521 | { 522 | //Path cannot be null 523 | if (is_null($path)) { 524 | throw new DropboxClientException("Path cannot be null."); 525 | } 526 | 527 | //Delete 528 | $response = $this->postToAPI('/files/delete_v2', ['path' => $path]); 529 | $body = $response->getDecodedBody(); 530 | 531 | //Response doesn't have Metadata 532 | if (!isset($body['metadata']) || !is_array($body['metadata'])) { 533 | throw new DropboxClientException("Invalid Response."); 534 | } 535 | 536 | return new DeletedMetadata($body['metadata']); 537 | } 538 | 539 | /** 540 | * Move a file or folder to a different location 541 | * 542 | * @param string $fromPath Path to be moved 543 | * @param string $toPath Path to be moved to 544 | * 545 | * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata 546 | * 547 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 548 | * 549 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move 550 | * 551 | */ 552 | public function move($fromPath, $toPath) 553 | { 554 | //From and To paths cannot be null 555 | if (is_null($fromPath) || is_null($toPath)) { 556 | throw new DropboxClientException("From and To paths cannot be null."); 557 | } 558 | 559 | //Response 560 | $response = $this->postToAPI('/files/move', ['from_path' => $fromPath, 'to_path' => $toPath]); 561 | 562 | //Make and Return the Model 563 | return $this->makeModelFromResponse($response); 564 | } 565 | 566 | /** 567 | * Copy a file or folder to a different location 568 | * 569 | * @param string $fromPath Path to be copied 570 | * @param string $toPath Path to be copied to 571 | * 572 | * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata 573 | * 574 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 575 | * 576 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy 577 | * 578 | */ 579 | public function copy($fromPath, $toPath) 580 | { 581 | //From and To paths cannot be null 582 | if (is_null($fromPath) || is_null($toPath)) { 583 | throw new DropboxClientException("From and To paths cannot be null."); 584 | } 585 | 586 | //Response 587 | $response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]); 588 | 589 | //Make and Return the Model 590 | return $this->makeModelFromResponse($response); 591 | } 592 | 593 | /** 594 | * Restore a file to the specific version 595 | * 596 | * @param string $path Path to the file to restore 597 | * @param string $rev Revision to store for the file 598 | * 599 | * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata 600 | * 601 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 602 | * 603 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-restore 604 | * 605 | */ 606 | public function restore($path, $rev) 607 | { 608 | //Path and Revision cannot be null 609 | if (is_null($path) || is_null($rev)) { 610 | throw new DropboxClientException("Path and Revision cannot be null."); 611 | } 612 | 613 | //Response 614 | $response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]); 615 | 616 | //Fetch the Metadata 617 | $body = $response->getDecodedBody(); 618 | 619 | //Make and Return the Model 620 | return new FileMetadata($body); 621 | } 622 | 623 | /** 624 | * Get Copy Reference 625 | * 626 | * @param string $path Path to the file or folder to get a copy reference to 627 | * 628 | * @return \Kunnu\Dropbox\Models\CopyReference 629 | * 630 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 631 | * 632 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get 633 | * 634 | */ 635 | public function getCopyReference($path) 636 | { 637 | //Path cannot be null 638 | if (is_null($path)) { 639 | throw new DropboxClientException("Path cannot be null."); 640 | } 641 | 642 | //Get Copy Reference 643 | $response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]); 644 | $body = $response->getDecodedBody(); 645 | 646 | //Make and Return the Model 647 | return new CopyReference($body); 648 | } 649 | 650 | /** 651 | * Save Copy Reference 652 | * 653 | * @param string $path Path to the file or folder to get a copy reference to 654 | * @param string $copyReference Copy reference returned by getCopyReference 655 | * 656 | * @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata 657 | * 658 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 659 | * 660 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save 661 | * 662 | */ 663 | public function saveCopyReference($path, $copyReference) 664 | { 665 | //Path and Copy Reference cannot be null 666 | if (is_null($path) || is_null($copyReference)) { 667 | throw new DropboxClientException("Path and Copy Reference cannot be null."); 668 | } 669 | 670 | //Save Copy Reference 671 | $response = $this->postToAPI('/files/copy_reference/save', ['path' => $path, 'copy_reference' => $copyReference]); 672 | $body = $response->getDecodedBody(); 673 | 674 | //Response doesn't have Metadata 675 | if (!isset($body['metadata']) || !is_array($body['metadata'])) { 676 | throw new DropboxClientException("Invalid Response."); 677 | } 678 | 679 | //Make and return the Model 680 | return ModelFactory::make($body['metadata']); 681 | } 682 | 683 | /** 684 | * Get a temporary link to stream contents of a file 685 | * 686 | * @param string $path Path to the file you want a temporary link to 687 | * 688 | * https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link 689 | * 690 | * @return \Kunnu\Dropbox\Models\TemporaryLink 691 | * 692 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 693 | */ 694 | public function getTemporaryLink($path) 695 | { 696 | //Path cannot be null 697 | if (is_null($path)) { 698 | throw new DropboxClientException("Path cannot be null."); 699 | } 700 | 701 | //Get Temporary Link 702 | $response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]); 703 | 704 | //Make and Return the Model 705 | return $this->makeModelFromResponse($response); 706 | } 707 | 708 | /** 709 | * Save a specified URL into a file in user's Dropbox 710 | * 711 | * @param string $path Path where the URL will be saved 712 | * @param string $url URL to be saved 713 | * 714 | * @return string Async Job ID 715 | * 716 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 717 | * 718 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url 719 | * 720 | */ 721 | public function saveUrl($path, $url) 722 | { 723 | //Path and URL cannot be null 724 | if (is_null($path) || is_null($url)) { 725 | throw new DropboxClientException("Path and URL cannot be null."); 726 | } 727 | 728 | //Save URL 729 | $response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]); 730 | $body = $response->getDecodedBody(); 731 | 732 | if (!isset($body['async_job_id'])) { 733 | throw new DropboxClientException("Could not retrieve Async Job ID."); 734 | } 735 | 736 | //Return the Async Job ID 737 | return $body['async_job_id']; 738 | } 739 | 740 | /** 741 | * Save a specified URL into a file in user's Dropbox 742 | * 743 | * @param $asyncJobId 744 | * 745 | * @return \Kunnu\Dropbox\Models\FileMetadata|string Status (failed|in_progress) or FileMetadata (if complete) 746 | * 747 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 748 | * 749 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url-check_job_status 750 | * 751 | */ 752 | public function checkJobStatus($asyncJobId) 753 | { 754 | //Async Job ID cannot be null 755 | if (is_null($asyncJobId)) { 756 | throw new DropboxClientException("Async Job ID cannot be null."); 757 | } 758 | 759 | //Get Job Status 760 | $response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]); 761 | $body = $response->getDecodedBody(); 762 | 763 | //Status 764 | $status = isset($body['.tag']) ? $body['.tag'] : ''; 765 | 766 | //If status is complete 767 | if ($status === 'complete') { 768 | return new FileMetadata($body); 769 | } 770 | 771 | //Return the status 772 | return $status; 773 | } 774 | 775 | /** 776 | * Upload a File to Dropbox 777 | * 778 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 779 | * @param string $path Path to upload the file to 780 | * @param array $params Additional Params 781 | * 782 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload 783 | * 784 | * @return \Kunnu\Dropbox\Models\FileMetadata 785 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 786 | */ 787 | public function upload($dropboxFile, $path, array $params = []) 788 | { 789 | //Make Dropbox File 790 | $dropboxFile = $this->makeDropboxFile($dropboxFile); 791 | 792 | //If the file is larger than the Chunked Upload Threshold 793 | if ($dropboxFile->getSize() > static::AUTO_CHUNKED_UPLOAD_THRESHOLD) { 794 | //Upload the file in sessions/chunks 795 | return $this->uploadChunked($dropboxFile, $path, null, null, $params); 796 | } 797 | 798 | //Simple file upload 799 | return $this->simpleUpload($dropboxFile, $path, $params); 800 | } 801 | 802 | /** 803 | * Make DropboxFile Object 804 | * 805 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 806 | * @param int $maxLength Max Bytes to read from the file 807 | * @param int $offset Seek to specified offset before reading 808 | * @param string $mode The type of access 809 | * 810 | * @return \Kunnu\Dropbox\DropboxFile 811 | */ 812 | public function makeDropboxFile($dropboxFile, $maxLength = null, $offset = null, $mode = DropboxFile::MODE_READ) 813 | { 814 | //Uploading file by file path 815 | if (!$dropboxFile instanceof DropboxFile) { 816 | //Create a DropboxFile Object 817 | $dropboxFile = new DropboxFile($dropboxFile, $mode); 818 | } elseif ($mode !== $dropboxFile->getMode()) { 819 | //Reopen the file with expected mode 820 | $dropboxFile->close(); 821 | $dropboxFile = new DropboxFile($dropboxFile->getFilePath(), $mode); 822 | } 823 | 824 | if (!is_null($offset)) { 825 | $dropboxFile->setOffset($offset); 826 | } 827 | 828 | if (!is_null($maxLength)) { 829 | $dropboxFile->setMaxLength($maxLength); 830 | } 831 | 832 | //Return the DropboxFile Object 833 | return $dropboxFile; 834 | } 835 | 836 | /** 837 | * Upload file in sessions/chunks 838 | * 839 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 840 | * @param string $path Path to save the file to, on Dropbox 841 | * @param int $fileSize The size of the file 842 | * @param int $chunkSize The amount of data to upload in each chunk 843 | * @param array $params Additional Params 844 | * 845 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start 846 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish 847 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2 848 | * 849 | * @return \Kunnu\Dropbox\Models\FileMetadata 850 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 851 | */ 852 | public function uploadChunked($dropboxFile, $path, $fileSize = null, $chunkSize = null, array $params = array()) 853 | { 854 | //Make Dropbox File 855 | $dropboxFile = $this->makeDropboxFile($dropboxFile); 856 | 857 | //No file size specified explicitly 858 | if (is_null($fileSize)) { 859 | $fileSize = $dropboxFile->getSize(); 860 | } 861 | 862 | //No chunk size specified, use default size 863 | if (is_null($chunkSize)) { 864 | $chunkSize = static::DEFAULT_CHUNK_SIZE; 865 | } 866 | 867 | //If the fileSize is smaller 868 | //than the chunk size, we'll 869 | //make the chunk size relatively 870 | //smaller than the file size 871 | if ($fileSize <= $chunkSize) { 872 | $chunkSize = intval($fileSize / 2); 873 | } 874 | 875 | //Start the Upload Session with the file path 876 | //since the DropboxFile object will be created 877 | //again using the new chunk size. 878 | $sessionId = $this->startUploadSession($dropboxFile->getFilePath(), $chunkSize); 879 | 880 | //Uploaded 881 | $uploaded = $chunkSize; 882 | 883 | //Remaining 884 | $remaining = $fileSize - $chunkSize; 885 | 886 | //While the remaining bytes are 887 | //more than the chunk size, append 888 | //the chunk to the upload session. 889 | while ($remaining > $chunkSize) { 890 | //Append the next chunk to the Upload session 891 | $sessionId = $this->appendUploadSession($dropboxFile, $sessionId, $uploaded, $chunkSize); 892 | 893 | //Update remaining and uploaded 894 | $uploaded = $uploaded + $chunkSize; 895 | $remaining = $remaining - $chunkSize; 896 | } 897 | 898 | //Finish the Upload Session and return the Uploaded File Metadata 899 | return $this->finishUploadSession($dropboxFile, $sessionId, $uploaded, $remaining, $path, $params); 900 | } 901 | 902 | /** 903 | * Start an Upload Session 904 | * 905 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 906 | * @param int $chunkSize Size of file chunk to upload 907 | * @param boolean $close Closes the session for "appendUploadSession" 908 | * 909 | * @return string Unique identifier for the upload session 910 | * 911 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 912 | * 913 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start 914 | * 915 | */ 916 | public function startUploadSession($dropboxFile, $chunkSize = -1, $close = false) 917 | { 918 | //Make Dropbox File with the given chunk size 919 | $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize); 920 | 921 | //Set the close param 922 | $params = [ 923 | 'close' => $close ? true : false, 924 | 'file' => $dropboxFile 925 | ]; 926 | 927 | //Upload File 928 | $file = $this->postToContent('/files/upload_session/start', $params); 929 | $body = $file->getDecodedBody(); 930 | 931 | //Cannot retrieve Session ID 932 | if (!isset($body['session_id'])) { 933 | throw new DropboxClientException("Could not retrieve Session ID."); 934 | } 935 | 936 | //Return the Session ID 937 | return $body['session_id']; 938 | } 939 | 940 | /** 941 | * Make a HTTP POST Request to the Content endpoint type 942 | * 943 | * @param string $endpoint Content Endpoint to send Request to 944 | * @param array $params Request Query Params 945 | * @param string $accessToken Access Token to send with the Request 946 | * @param DropboxFile $responseFile Save response to the file 947 | * 948 | * @return \Kunnu\Dropbox\DropboxResponse 949 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 950 | */ 951 | public function postToContent($endpoint, array $params = [], $accessToken = null, DropboxFile $responseFile = null) 952 | { 953 | return $this->sendRequest("POST", $endpoint, 'content', $params, $accessToken, $responseFile); 954 | } 955 | 956 | /** 957 | * Append more data to an Upload Session 958 | * 959 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 960 | * @param string $sessionId Session ID returned by `startUploadSession` 961 | * @param int $offset The amount of data that has been uploaded so far 962 | * @param int $chunkSize The amount of data to upload 963 | * @param boolean $close Closes the session for futher "appendUploadSession" calls 964 | * 965 | * @return string Unique identifier for the upload session 966 | * 967 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 968 | * 969 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2 970 | * 971 | */ 972 | public function appendUploadSession($dropboxFile, $sessionId, $offset, $chunkSize, $close = false) 973 | { 974 | //Make Dropbox File 975 | $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize, $offset); 976 | 977 | //Session ID, offset, chunkSize and path cannot be null 978 | if (is_null($sessionId) || is_null($offset) || is_null($chunkSize)) { 979 | throw new DropboxClientException("Session ID, offset and chunk size cannot be null"); 980 | } 981 | 982 | $params = []; 983 | 984 | //Set the File 985 | $params['file'] = $dropboxFile; 986 | 987 | //Set the Cursor: Session ID and Offset 988 | $params['cursor'] = ['session_id' => $sessionId, 'offset' => $offset]; 989 | 990 | //Set the close param 991 | $params['close'] = $close ? true : false; 992 | 993 | //Since this endpoint doesn't have 994 | //any return values, we'll disable the 995 | //response validation for this request. 996 | $params['validateResponse'] = false; 997 | 998 | //Upload File 999 | $this->postToContent('/files/upload_session/append_v2', $params); 1000 | 1001 | //Make and Return the Model 1002 | return $sessionId; 1003 | } 1004 | 1005 | /** 1006 | * Finish an upload session and save the uploaded data to the given file path 1007 | * 1008 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 1009 | * @param string $sessionId Session ID returned by `startUploadSession` 1010 | * @param int $offset The amount of data that has been uploaded so far 1011 | * @param int $remaining The amount of data that is remaining 1012 | * @param string $path Path to save the file to, on Dropbox 1013 | * @param array $params Additional Params 1014 | * 1015 | * @return \Kunnu\Dropbox\Models\FileMetadata 1016 | * 1017 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1018 | * 1019 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish 1020 | * 1021 | */ 1022 | public function finishUploadSession($dropboxFile, $sessionId, $offset, $remaining, $path, array $params = []) 1023 | { 1024 | //Make Dropbox File 1025 | $dropboxFile = $this->makeDropboxFile($dropboxFile, $remaining, $offset); 1026 | 1027 | //Session ID, offset, remaining and path cannot be null 1028 | if (is_null($sessionId) || is_null($path) || is_null($offset) || is_null($remaining)) { 1029 | throw new DropboxClientException("Session ID, offset, remaining and path cannot be null"); 1030 | } 1031 | 1032 | $queryParams = []; 1033 | 1034 | //Set the File 1035 | $queryParams['file'] = $dropboxFile; 1036 | 1037 | //Set the Cursor: Session ID and Offset 1038 | $queryParams['cursor'] = ['session_id' => $sessionId, 'offset' => $offset]; 1039 | 1040 | //Set the path 1041 | $params['path'] = $path; 1042 | //Set the Commit 1043 | $queryParams['commit'] = $params; 1044 | 1045 | //Upload File 1046 | $file = $this->postToContent('/files/upload_session/finish', $queryParams); 1047 | $body = $file->getDecodedBody(); 1048 | 1049 | //Make and Return the Model 1050 | return new FileMetadata($body); 1051 | } 1052 | 1053 | /** 1054 | * Upload a File to Dropbox in a single request 1055 | * 1056 | * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file 1057 | * @param string $path Path to upload the file to 1058 | * @param array $params Additional Params 1059 | * 1060 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload 1061 | * 1062 | * @return \Kunnu\Dropbox\Models\FileMetadata 1063 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1064 | */ 1065 | public function simpleUpload($dropboxFile, $path, array $params = []) 1066 | { 1067 | //Make Dropbox File 1068 | $dropboxFile = $this->makeDropboxFile($dropboxFile); 1069 | 1070 | //Set the path and file 1071 | $params['path'] = $path; 1072 | $params['file'] = $dropboxFile; 1073 | 1074 | //Upload File 1075 | $file = $this->postToContent('/files/upload', $params); 1076 | $body = $file->getDecodedBody(); 1077 | 1078 | //Make and Return the Model 1079 | return new FileMetadata($body); 1080 | } 1081 | 1082 | /** 1083 | * Get a thumbnail for an image 1084 | * 1085 | * @param string $path Path to the file you want a thumbnail to 1086 | * @param string $size Size for the thumbnail image ['thumb','small','medium','large','huge'] 1087 | * @param string $format Format for the thumbnail image ['jpeg'|'png'] 1088 | * 1089 | * @return \Kunnu\Dropbox\Models\Thumbnail 1090 | * 1091 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1092 | * 1093 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail 1094 | * 1095 | */ 1096 | public function getThumbnail($path, $size = 'small', $format = 'jpeg') 1097 | { 1098 | //Path cannot be null 1099 | if (is_null($path)) { 1100 | throw new DropboxClientException("Path cannot be null."); 1101 | } 1102 | 1103 | //Invalid Format 1104 | if (!in_array($format, ['jpeg', 'png'])) { 1105 | throw new DropboxClientException("Invalid format. Must either be 'jpeg' or 'png'."); 1106 | } 1107 | 1108 | //Thumbnail size 1109 | $size = $this->getThumbnailSize($size); 1110 | 1111 | //Get Thumbnail 1112 | $response = $this->postToContent('/files/get_thumbnail', ['path' => $path, 'format' => $format, 'size' => $size]); 1113 | 1114 | //Get file metadata from response headers 1115 | $metadata = $this->getMetadataFromResponseHeaders($response); 1116 | 1117 | //File Contents 1118 | $contents = $response->getBody(); 1119 | 1120 | //Make and return a Thumbnail model 1121 | return new Thumbnail($metadata, $contents); 1122 | } 1123 | 1124 | /** 1125 | * Get thumbnail size 1126 | * 1127 | * @param string $size Thumbnail Size 1128 | * 1129 | * @return string 1130 | */ 1131 | protected function getThumbnailSize($size) 1132 | { 1133 | $thumbnailSizes = [ 1134 | 'thumb' => 'w32h32', 1135 | 'small' => 'w64h64', 1136 | 'medium' => 'w128h128', 1137 | 'large' => 'w640h480', 1138 | 'huge' => 'w1024h768' 1139 | ]; 1140 | 1141 | return isset($thumbnailSizes[$size]) ? $thumbnailSizes[$size] : $thumbnailSizes['small']; 1142 | } 1143 | 1144 | /** 1145 | * Get metadata from response headers 1146 | * 1147 | * @param DropboxResponse $response 1148 | * 1149 | * @return array 1150 | */ 1151 | protected function getMetadataFromResponseHeaders(DropboxResponse $response) 1152 | { 1153 | //Response Headers 1154 | $headers = $response->getHeaders(); 1155 | 1156 | //Empty metadata for when 1157 | //metadata isn't returned 1158 | $metadata = []; 1159 | 1160 | //If metadata is available 1161 | if (isset($headers[static::METADATA_HEADER])) { 1162 | //File Metadata 1163 | $data = $headers[static::METADATA_HEADER]; 1164 | 1165 | //The metadata is present in the first index 1166 | //of the metadata response header array 1167 | if (is_array($data) && isset($data[0])) { 1168 | $data = $data[0]; 1169 | } 1170 | 1171 | //Since the metadata is returned as a json string 1172 | //it needs to be decoded into an associative array 1173 | $metadata = json_decode((string)$data, true); 1174 | } 1175 | 1176 | //Return the metadata 1177 | return $metadata; 1178 | } 1179 | 1180 | /** 1181 | * Download a File 1182 | * 1183 | * @param string $path Path to the file you want to download 1184 | * @param null|string|DropboxFile $dropboxFile DropboxFile object or Path to target file 1185 | * 1186 | * @return \Kunnu\Dropbox\Models\File 1187 | * 1188 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1189 | * 1190 | * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download 1191 | * 1192 | */ 1193 | public function download($path, $dropboxFile = null) 1194 | { 1195 | //Path cannot be null 1196 | if (is_null($path)) { 1197 | throw new DropboxClientException("Path cannot be null."); 1198 | } 1199 | 1200 | //Make Dropbox File if target is specified 1201 | $dropboxFile = $dropboxFile ? $this->makeDropboxFile($dropboxFile, null, null, DropboxFile::MODE_WRITE) : null; 1202 | 1203 | //Download File 1204 | $response = $this->postToContent('/files/download', ['path' => $path], null, $dropboxFile); 1205 | 1206 | //Get file metadata from response headers 1207 | $metadata = $this->getMetadataFromResponseHeaders($response); 1208 | 1209 | //File Contents 1210 | $contents = $dropboxFile ? $this->makeDropboxFile($dropboxFile) : $response->getBody(); 1211 | 1212 | //Make and return a File model 1213 | return new File($metadata, $contents); 1214 | } 1215 | 1216 | /** 1217 | * Get Current Account 1218 | * 1219 | * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account 1220 | * 1221 | * @return \Kunnu\Dropbox\Models\Account 1222 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1223 | */ 1224 | public function getCurrentAccount() 1225 | { 1226 | //Get current account 1227 | $response = $this->postToAPI('/users/get_current_account', []); 1228 | $body = $response->getDecodedBody(); 1229 | 1230 | //Make and return the model 1231 | return new Account($body); 1232 | } 1233 | 1234 | /** 1235 | * Get Account 1236 | * 1237 | * @param string $account_id Account ID of the account to get details for 1238 | * 1239 | * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account 1240 | * 1241 | * @return \Kunnu\Dropbox\Models\Account 1242 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1243 | */ 1244 | public function getAccount($account_id) 1245 | { 1246 | //Get account 1247 | $response = $this->postToAPI('/users/get_account', ['account_id' => $account_id]); 1248 | $body = $response->getDecodedBody(); 1249 | 1250 | //Make and return the model 1251 | return new Account($body); 1252 | } 1253 | 1254 | /** 1255 | * Get Multiple Accounts in one call 1256 | * 1257 | * @param array $account_ids IDs of the accounts to get details for 1258 | * 1259 | * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account_batch 1260 | * 1261 | * @return \Kunnu\Dropbox\Models\AccountList 1262 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1263 | */ 1264 | public function getAccounts(array $account_ids = []) 1265 | { 1266 | //Get account 1267 | $response = $this->postToAPI('/users/get_account_batch', ['account_ids' => $account_ids]); 1268 | $body = $response->getDecodedBody(); 1269 | 1270 | //Make and return the model 1271 | return new AccountList($body); 1272 | } 1273 | 1274 | /** 1275 | * Get Space Usage for the current user's account 1276 | * 1277 | * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_space_usage 1278 | * 1279 | * @return array 1280 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 1281 | */ 1282 | public function getSpaceUsage() 1283 | { 1284 | //Get space usage 1285 | $response = $this->postToAPI('/users/get_space_usage', []); 1286 | $body = $response->getDecodedBody(); 1287 | 1288 | //Return the decoded body 1289 | return $body; 1290 | } 1291 | } 1292 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxApp.php: -------------------------------------------------------------------------------- 1 | clientId = $clientId; 42 | $this->clientSecret = $clientSecret; 43 | $this->accessToken = $accessToken; 44 | } 45 | 46 | /** 47 | * Get the App Client ID 48 | * 49 | * @return string 50 | */ 51 | public function getClientId() 52 | { 53 | return $this->clientId; 54 | } 55 | 56 | /** 57 | * Get the App Client Secret 58 | * 59 | * @return string 60 | */ 61 | public function getClientSecret() 62 | { 63 | return $this->clientSecret; 64 | } 65 | 66 | /** 67 | * Get the Access Token 68 | * 69 | * @return string 70 | */ 71 | public function getAccessToken() 72 | { 73 | return $this->accessToken; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxClient.php: -------------------------------------------------------------------------------- 1 | setHttpClient($httpClient); 41 | } 42 | 43 | /** 44 | * Get the HTTP Client 45 | * 46 | * @return \Kunnu\Dropbox\Http\Clients\DropboxHttpClientInterface $httpClient 47 | */ 48 | public function getHttpClient() 49 | { 50 | return $this->httpClient; 51 | } 52 | 53 | /** 54 | * Set the HTTP Client 55 | * 56 | * @param \Kunnu\Dropbox\Http\Clients\DropboxHttpClientInterface $httpClient 57 | * 58 | * @return \Kunnu\Dropbox\DropboxClient 59 | */ 60 | public function setHttpClient(DropboxHttpClientInterface $httpClient) 61 | { 62 | $this->httpClient = $httpClient; 63 | 64 | return $this; 65 | } 66 | 67 | /** 68 | * Get the API Base Path. 69 | * 70 | * @return string API Base Path 71 | */ 72 | public function getBasePath() 73 | { 74 | return static::BASE_PATH; 75 | } 76 | 77 | /** 78 | * Get the API Content Path. 79 | * 80 | * @return string API Content Path 81 | */ 82 | public function getContentPath() 83 | { 84 | return static::CONTENT_PATH; 85 | } 86 | 87 | /** 88 | * Get the Authorization Header with the Access Token. 89 | * 90 | * @param string $accessToken Access Token 91 | * 92 | * @return array Authorization Header 93 | */ 94 | protected function buildAuthHeader($accessToken = "") 95 | { 96 | return ['Authorization' => 'Bearer '. $accessToken]; 97 | } 98 | 99 | /** 100 | * Get the Content Type Header. 101 | * 102 | * @param string $contentType Request Content Type 103 | * 104 | * @return array Content Type Header 105 | */ 106 | protected function buildContentTypeHeader($contentType = "") 107 | { 108 | return ['Content-Type' => $contentType]; 109 | } 110 | 111 | /** 112 | * Build URL for the Request 113 | * 114 | * @param string $endpoint Relative API endpoint 115 | * @param string $type Endpoint Type 116 | * 117 | * @link https://www.dropbox.com/developers/documentation/http/documentation#formats Request and response formats 118 | * 119 | * @return string The Full URL to the API Endpoints 120 | */ 121 | protected function buildUrl($endpoint = '', $type = 'api') 122 | { 123 | //Get the base path 124 | $base = $this->getBasePath(); 125 | 126 | //If the endpoint type is 'content' 127 | if ($type === 'content') { 128 | //Get the Content Path 129 | $base = $this->getContentPath(); 130 | } 131 | 132 | //Join and return the base and api path/endpoint 133 | return $base . $endpoint; 134 | } 135 | 136 | /** 137 | * Send the Request to the Server and return the Response 138 | * 139 | * @param DropboxRequest $request 140 | * @param DropboxResponse $response 141 | * 142 | * @return \Kunnu\Dropbox\DropboxResponse 143 | * 144 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 145 | */ 146 | public function sendRequest(DropboxRequest $request, DropboxResponse $response = null) 147 | { 148 | //Method 149 | $method = $request->getMethod(); 150 | 151 | //Prepare Request 152 | list($url, $headers, $requestBody) = $this->prepareRequest($request); 153 | 154 | $options = []; 155 | if ($response instanceof DropboxResponseToFile) { 156 | $options['sink'] = $response->getSteamOrFilePath(); 157 | } 158 | 159 | //Send the Request to the Server through the HTTP Client 160 | //and fetch the raw response as DropboxRawResponse 161 | $rawResponse = $this->getHttpClient()->send($url, $method, $requestBody, $headers, $options); 162 | 163 | //Create DropboxResponse from DropboxRawResponse 164 | $response = $response ?: new DropboxResponse($request); 165 | $response->setHttpStatusCode($rawResponse->getHttpResponseCode()); 166 | $response->setHeaders($rawResponse->getHeaders()); 167 | if (!$response instanceof DropboxResponseToFile) { 168 | $response->setBody($rawResponse->getBody()); 169 | } 170 | 171 | //Return the DropboxResponse 172 | return $response; 173 | } 174 | 175 | /** 176 | * Prepare a Request before being sent to the HTTP Client 177 | * 178 | * @param \Kunnu\Dropbox\DropboxRequest $request 179 | * 180 | * @return array [Request URL, Request Headers, Request Body] 181 | */ 182 | protected function prepareRequest(DropboxRequest $request) 183 | { 184 | //Build URL 185 | $url = $this->buildUrl($request->getEndpoint(), $request->getEndpointType()); 186 | 187 | //The Endpoint is content 188 | if ($request->getEndpointType() === 'content') { 189 | //Dropbox requires the parameters to be passed 190 | //through the 'Dropbox-API-Arg' header 191 | $request->setHeaders(['Dropbox-API-Arg' => json_encode($request->getParams())]); 192 | 193 | //If a File is also being uploaded 194 | if ($request->hasFile()) { 195 | //Content Type 196 | $request->setContentType("application/octet-stream"); 197 | 198 | //Request Body (File Contents) 199 | $requestBody = $request->getStreamBody()->getBody(); 200 | } else { 201 | //Empty Body 202 | $requestBody = null; 203 | } 204 | } else { 205 | //The endpoint is 'api' 206 | //Request Body (Parameters) 207 | $requestBody = $request->getJsonBody()->getBody(); 208 | } 209 | 210 | //Empty body 211 | if (is_null($requestBody)) { 212 | //Content Type needs to be kept empty 213 | $request->setContentType(""); 214 | } 215 | 216 | //Build headers 217 | $headers = array_merge( 218 | $this->buildAuthHeader($request->getAccessToken()), 219 | $this->buildContentTypeHeader($request->getContentType()), 220 | $request->getHeaders() 221 | ); 222 | 223 | //Return the URL, Headers and Request Body 224 | return [$url, $headers, $requestBody]; 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxFile.php: -------------------------------------------------------------------------------- 1 | path = $filePath; 69 | $this->mode = $mode; 70 | } 71 | 72 | /** 73 | * Create a new DropboxFile instance using a file stream 74 | * 75 | * @param $fileName 76 | * @param $resource 77 | * @param string $mode 78 | * 79 | * @return DropboxFile 80 | * @throws DropboxClientException 81 | */ 82 | public static function createByStream($fileName, $resource, $mode = self::MODE_READ) 83 | { 84 | // create a new stream and set it to the dropbox file 85 | $stream = \GuzzleHttp\Psr7\Utils::streamFor($resource); 86 | if (!$stream) { 87 | throw new DropboxClientException('Failed to create DropboxFile instance. Unable to open the given resource.'); 88 | } 89 | 90 | // Try to get the file path from the stream (we'll need this for uploading bigger files) 91 | $filePath = $stream->getMetadata('uri'); 92 | if (!is_null($filePath)) { 93 | $fileName = $filePath; 94 | } 95 | 96 | $dropboxFile = new self($fileName, $mode); 97 | $dropboxFile->setStream($stream); 98 | 99 | return $dropboxFile; 100 | } 101 | 102 | /** 103 | * Create a new DropboxFile instance using a file path 104 | * 105 | * This behaves the same as the constructor but was added in order to 106 | * match the syntax of the static createByStream function 107 | * 108 | * @see DropboxFile::createByStream() 109 | * 110 | * @param $filePath 111 | * @param $mode 112 | * 113 | * @return DropboxFile 114 | */ 115 | public static function createByPath($filePath, $mode) 116 | { 117 | return new self($filePath, $mode); 118 | } 119 | 120 | /** 121 | * Closes the stream when destructed. 122 | */ 123 | public function __destruct() 124 | { 125 | $this->close(); 126 | } 127 | 128 | /** 129 | * Close the file stream 130 | */ 131 | public function close() 132 | { 133 | if ($this->stream) { 134 | $this->stream->close(); 135 | } 136 | } 137 | 138 | /** 139 | * Set the offset to start reading 140 | * the data from the stream 141 | * 142 | * @param int $offset 143 | */ 144 | public function setOffset($offset) 145 | { 146 | $this->offset = $offset; 147 | } 148 | 149 | /** 150 | * Set the Max Length till where to read 151 | * the data from the stream. 152 | * 153 | * @param int $maxLength 154 | */ 155 | public function setMaxLength($maxLength) 156 | { 157 | $this->maxLength = $maxLength; 158 | } 159 | 160 | /** 161 | * Return the contents of the file 162 | * 163 | * @return string 164 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 165 | */ 166 | public function getContents() 167 | { 168 | $stream = $this->getStream(); 169 | // If an offset is provided 170 | if ($this->offset !== -1) { 171 | // Seek to the offset 172 | $stream->seek($this->offset); 173 | } 174 | 175 | // If a max length is provided 176 | if ($this->maxLength !== -1) { 177 | // Read from the offset till the maxLength 178 | return $stream->read($this->maxLength); 179 | } 180 | 181 | return $stream->getContents(); 182 | } 183 | 184 | /** 185 | * Get the Open File Stream 186 | * 187 | * @return \GuzzleHttp\Psr7\Stream 188 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 189 | */ 190 | public function getStream() 191 | { 192 | if (!$this->stream) { 193 | $this->open(); 194 | } 195 | return $this->stream; 196 | } 197 | 198 | /** 199 | * Manually set the stream for this DropboxFile instance 200 | * 201 | * @param $stream 202 | */ 203 | public function setStream($stream) 204 | { 205 | $this->isStream = true; 206 | $this->stream = $stream; 207 | } 208 | 209 | /** 210 | * Opens the File Stream 211 | * 212 | * @throws DropboxClientException 213 | * 214 | * @return void 215 | */ 216 | public function open() 217 | { 218 | // File was created from a stream so don't open it again 219 | if ($this->isCreatedFromStream()) { 220 | return; 221 | } 222 | 223 | // File is not a remote file 224 | if (!$this->isRemoteFile($this->path)) { 225 | // File is not Readable 226 | if ($this->isNotReadable()) { 227 | throw new DropboxClientException('Failed to create DropboxFile instance. Unable to read resource: ' . $this->path . '.'); 228 | } 229 | 230 | // File is not Writable 231 | if ($this->isNotWritable()) { 232 | throw new DropboxClientException('Failed to create DropboxFile instance. Unable to write resource: ' . $this->path . '.'); 233 | } 234 | } 235 | 236 | // Create a stream 237 | $this->stream = \GuzzleHttp\Psr7\Utils::streamFor(fopen($this->path, $this->mode)); 238 | 239 | // Unable to create stream 240 | if (!$this->stream) { 241 | throw new DropboxClientException('Failed to create DropboxFile instance. Unable to open resource: ' . $this->path . '.'); 242 | } 243 | } 244 | 245 | /** 246 | * @return bool 247 | */ 248 | protected function isCreatedFromStream() 249 | { 250 | return $this->stream && $this->isStream === true; 251 | } 252 | 253 | /** 254 | * Returns true if the path to the file is remote 255 | * 256 | * @param string $pathToFile 257 | * 258 | * @return boolean 259 | */ 260 | protected function isRemoteFile($pathToFile) 261 | { 262 | return preg_match('/^(https?|ftp):\/\/.*/', $pathToFile) === 1; 263 | } 264 | 265 | /** 266 | * @return bool 267 | */ 268 | protected function isNotReadable() 269 | { 270 | return self::MODE_READ === $this->mode && !is_readable($this->path); 271 | } 272 | 273 | /** 274 | * @return bool 275 | */ 276 | protected function isNotWritable() 277 | { 278 | return self::MODE_WRITE === $this->mode && file_exists($this->path) && !is_writable($this->path); 279 | } 280 | 281 | /** 282 | * Get the name of the file 283 | * 284 | * @return string 285 | */ 286 | public function getFileName() 287 | { 288 | return basename($this->path); 289 | } 290 | 291 | /** 292 | * Get the path of the file 293 | * 294 | * @return string 295 | */ 296 | public function getFilePath() 297 | { 298 | return $this->path; 299 | } 300 | 301 | public function getStreamOrFilePath() 302 | { 303 | return $this->isCreatedFromStream() ? $this->getStream() : $this->getFilePath(); 304 | } 305 | 306 | /** 307 | * Get the mode of the file stream 308 | * 309 | * @return string 310 | */ 311 | public function getMode() 312 | { 313 | return $this->mode; 314 | } 315 | 316 | /** 317 | * Get the size of the file 318 | * 319 | * @return int 320 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 321 | */ 322 | public function getSize() 323 | { 324 | return $this->getStream()->getSize(); 325 | } 326 | 327 | /** 328 | * Get mimetype of the file 329 | * 330 | * @return string 331 | */ 332 | public function getMimetype() 333 | { 334 | return \GuzzleHttp\Psr7\mimetype_from_filename($this->path) ?: 'text/plain'; 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxRequest.php: -------------------------------------------------------------------------------- 1 | setMethod($method); 94 | $this->setEndpoint($endpoint); 95 | $this->setAccessToken($accessToken); 96 | $this->setEndpointType($endpointType); 97 | $this->setParams($params); 98 | $this->setHeaders($headers); 99 | 100 | if ($contentType) { 101 | $this->setContentType($contentType); 102 | } 103 | } 104 | 105 | /** 106 | * Get the Request Method 107 | * 108 | * @return string 109 | */ 110 | public function getMethod() 111 | { 112 | return $this->method; 113 | } 114 | 115 | /** 116 | * Set the Request Method 117 | * 118 | * @param string 119 | * 120 | * @return \Kunnu\Dropbox\DropboxRequest 121 | */ 122 | public function setMethod($method) 123 | { 124 | $this->method = $method; 125 | 126 | return $this; 127 | } 128 | 129 | /** 130 | * Get Access Token for the Request 131 | * 132 | * @return string 133 | */ 134 | public function getAccessToken() 135 | { 136 | return $this->accessToken; 137 | } 138 | 139 | /** 140 | * Set Access Token for the Request 141 | * 142 | * @param string 143 | * 144 | * @return \Kunnu\Dropbox\DropboxRequest 145 | */ 146 | public function setAccessToken($accessToken) 147 | { 148 | $this->accessToken = $accessToken; 149 | 150 | return $this; 151 | } 152 | 153 | /** 154 | * Get the Endpoint of the Request 155 | * 156 | * @return string 157 | */ 158 | public function getEndpoint() 159 | { 160 | return $this->endpoint; 161 | } 162 | 163 | /** 164 | * Set the Endpoint of the Request 165 | * 166 | * @param string 167 | * 168 | * @return \Kunnu\Dropbox\DropboxRequest 169 | */ 170 | public function setEndpoint($endpoint) 171 | { 172 | $this->endpoint = $endpoint; 173 | 174 | return $this; 175 | } 176 | 177 | /** 178 | * Get the Endpoint Type of the Request 179 | * 180 | * @return string 181 | */ 182 | public function getEndpointType() 183 | { 184 | return $this->endpointType; 185 | } 186 | 187 | /** 188 | * Set the Endpoint Type of the Request 189 | * 190 | * @param string 191 | * 192 | * @return \Kunnu\Dropbox\DropboxRequest 193 | */ 194 | public function setEndpointType($endpointType) 195 | { 196 | $this->endpointType = $endpointType; 197 | 198 | return $this; 199 | } 200 | 201 | /** 202 | * Get the Content Type of the Request 203 | * 204 | * @return string 205 | */ 206 | public function getContentType() 207 | { 208 | return $this->contentType; 209 | } 210 | 211 | /** 212 | * Set the Content Type of the Request 213 | * 214 | * @param string 215 | * 216 | * @return \Kunnu\Dropbox\DropboxRequest 217 | */ 218 | public function setContentType($contentType) 219 | { 220 | $this->contentType = $contentType; 221 | 222 | return $this; 223 | } 224 | 225 | /** 226 | * Get Request Headers 227 | * 228 | * @return array 229 | */ 230 | public function getHeaders() 231 | { 232 | return $this->headers; 233 | } 234 | 235 | /** 236 | * Set Request Headers 237 | * 238 | * @param array 239 | * 240 | * @return \Kunnu\Dropbox\DropboxRequest 241 | */ 242 | public function setHeaders(array $headers) 243 | { 244 | $this->headers = array_merge($this->headers, $headers); 245 | 246 | return $this; 247 | } 248 | 249 | /** 250 | * Get JSON Encoded Request Body 251 | * 252 | * @return \Kunnu\Dropbox\Http\RequestBodyJsonEncoded 253 | */ 254 | public function getJsonBody() 255 | { 256 | return new RequestBodyJsonEncoded($this->getParams()); 257 | } 258 | 259 | /** 260 | * Get the Request Params 261 | * 262 | * @return array 263 | */ 264 | public function getParams() 265 | { 266 | return $this->params; 267 | } 268 | 269 | /** 270 | * Set the Request Params 271 | * 272 | * @param array 273 | * 274 | * @return \Kunnu\Dropbox\DropboxRequest 275 | */ 276 | public function setParams(array $params = []) 277 | { 278 | 279 | //Process Params 280 | $params = $this->processParams($params); 281 | 282 | //Set the params 283 | $this->params = $params; 284 | 285 | return $this; 286 | } 287 | 288 | /** 289 | * Get Stream Request Body 290 | * 291 | * @return \Kunnu\Dropbox\Http\RequestBodyStream 292 | */ 293 | public function getStreamBody() 294 | { 295 | return new RequestBodyStream($this->getFile()); 296 | } 297 | 298 | /** 299 | * Get the File to be sent with the Request 300 | * 301 | * @return \Kunnu\Dropbox\DropboxFile 302 | */ 303 | public function getFile() 304 | { 305 | return $this->file; 306 | } 307 | 308 | /** 309 | * Set the File to be sent with the Request 310 | * 311 | * @param \Kunnu\Dropbox\DropboxFile 312 | * 313 | * @return \Kunnu\Dropbox\DropboxRequest 314 | */ 315 | public function setFile(DropboxFile $file) 316 | { 317 | $this->file = $file; 318 | 319 | return $this; 320 | } 321 | 322 | /** 323 | * Returns true if Request has file to be uploaded 324 | * 325 | * @return boolean 326 | */ 327 | public function hasFile() 328 | { 329 | return !is_null($this->file) ? true : false; 330 | } 331 | 332 | /** 333 | * Whether to validate response or not 334 | * 335 | * @return boolean 336 | */ 337 | public function validateResponse() 338 | { 339 | return $this->validateResponse; 340 | } 341 | 342 | /** 343 | * Process Params for the File parameter 344 | * 345 | * @param array $params Request Params 346 | * 347 | * @return array 348 | */ 349 | protected function processParams(array $params) 350 | { 351 | //If a file needs to be uploaded 352 | if (isset($params['file']) && $params['file'] instanceof DropboxFile) { 353 | //Set the file property 354 | $this->setFile($params['file']); 355 | //Remove the file item from the params array 356 | unset($params['file']); 357 | } 358 | 359 | //Whether the response needs to be validated 360 | //against being a valid JSON response 361 | if (isset($params['validateResponse'])) { 362 | //Set the validateResponse 363 | $this->validateResponse = $params['validateResponse']; 364 | //Remove the validateResponse from the params array 365 | unset($params['validateResponse']); 366 | } 367 | 368 | return $params; 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxResponse.php: -------------------------------------------------------------------------------- 1 | request = $request; 54 | $this->body = $body; 55 | $this->httpStatusCode = $httpStatusCode; 56 | $this->headers = $headers; 57 | } 58 | 59 | /** 60 | * @param string $body 61 | */ 62 | public function setBody($body) 63 | { 64 | $this->body = $body; 65 | } 66 | 67 | /** 68 | * @param int $httpStatusCode 69 | */ 70 | public function setHttpStatusCode($httpStatusCode) 71 | { 72 | $this->httpStatusCode = $httpStatusCode; 73 | } 74 | 75 | /** 76 | * @param array $headers 77 | */ 78 | public function setHeaders(array $headers) 79 | { 80 | $this->headers = $headers; 81 | } 82 | 83 | /** 84 | * Get the Request Request 85 | * 86 | * @return \Kunnu\Dropbox\DropboxRequest 87 | */ 88 | public function getRequest() 89 | { 90 | return $this->request; 91 | } 92 | 93 | /** 94 | * Get the Response Body 95 | * 96 | * @return string 97 | */ 98 | public function getBody() 99 | { 100 | return $this->body; 101 | } 102 | 103 | /** 104 | * Get the Decoded Body 105 | * 106 | * @return array 107 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 108 | */ 109 | public function getDecodedBody() 110 | { 111 | if (empty($this->decodedBody) || $this->decodedBody === null) { 112 | //Decode the Response Body 113 | $this->decodeBody(); 114 | } 115 | 116 | return $this->decodedBody; 117 | } 118 | 119 | /** 120 | * Get Access Token for the Request 121 | * 122 | * @return string 123 | */ 124 | public function getAccessToken() 125 | { 126 | return $this->getRequest()->getAccessToken(); 127 | } 128 | 129 | /** 130 | * Get Request Headers 131 | * 132 | * @return array 133 | */ 134 | public function getHeaders() 135 | { 136 | return $this->headers; 137 | } 138 | 139 | /** 140 | * Get the HTTP Status Code 141 | * 142 | * @return int 143 | */ 144 | public function getHttpStatusCode() 145 | { 146 | return $this->httpStatusCode; 147 | } 148 | 149 | /** 150 | * Decode the Body 151 | * 152 | * @throws DropboxClientException 153 | * 154 | * @return void 155 | */ 156 | protected function decodeBody() 157 | { 158 | $body = $this->getBody(); 159 | 160 | if (isset($this->headers['Content-Type']) && in_array('application/json', $this->headers['Content-Type'])) { 161 | $this->decodedBody = (array) json_decode((string) $body, true); 162 | } 163 | 164 | // If the response needs to be validated 165 | if ($this->getRequest()->validateResponse()) { 166 | //Validate Response 167 | $this->validateResponse(); 168 | } 169 | } 170 | 171 | /** 172 | * Validate Response 173 | * 174 | * @return void 175 | * 176 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 177 | */ 178 | protected function validateResponse() 179 | { 180 | // If JSON cannot be decoded 181 | if ($this->decodedBody === null) { 182 | throw new DropboxClientException("Invalid Response"); 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/Dropbox/DropboxResponseToFile.php: -------------------------------------------------------------------------------- 1 | file = $file; 23 | } 24 | 25 | /** 26 | * @throws Exceptions\DropboxClientException 27 | */ 28 | public function getBody() 29 | { 30 | return $this->file->getContents(); 31 | } 32 | 33 | public function getFilePath() 34 | { 35 | return $this->file->getFilePath(); 36 | } 37 | 38 | public function getSteamOrFilePath() 39 | { 40 | return $this->file->getStreamOrFilePath(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Dropbox/Exceptions/DropboxClientException.php: -------------------------------------------------------------------------------- 1 | client = $client ?: new Client(); 35 | } 36 | 37 | /** 38 | * Send request to the server and fetch the raw response. 39 | * 40 | * @param string $url URL/Endpoint to send the request to 41 | * @param string $method Request Method 42 | * @param string|resource|StreamInterface $body Request Body 43 | * @param array $headers Request Headers 44 | * @param array $options Additional Options 45 | * 46 | * @return \Kunnu\Dropbox\Http\DropboxRawResponse Raw response from the server 47 | * 48 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 49 | */ 50 | public function send($url, $method, $body, $headers = [], $options = []) 51 | { 52 | //Create a new Request Object 53 | $request = new Request($method, $url, $headers, $body); 54 | 55 | try { 56 | //Send the Request 57 | $rawResponse = $this->client->send($request, $options); 58 | } catch (BadResponseException $e) { 59 | throw new DropboxClientException($e->getResponse()->getBody(), $e->getCode(), $e); 60 | } catch (RequestException $e) { 61 | $rawResponse = $e->getResponse(); 62 | 63 | if (! $rawResponse instanceof ResponseInterface) { 64 | throw new DropboxClientException($e->getMessage(), $e->getCode()); 65 | } 66 | } 67 | 68 | //Something went wrong 69 | if ($rawResponse->getStatusCode() >= 400) { 70 | throw new DropboxClientException($rawResponse->getBody()); 71 | } 72 | 73 | if (array_key_exists('sink', $options)) { 74 | //Response Body is saved to a file 75 | $body = ''; 76 | } else { 77 | //Get the Response Body 78 | $body = $this->getResponseBody($rawResponse); 79 | } 80 | 81 | $rawHeaders = $rawResponse->getHeaders(); 82 | $httpStatusCode = $rawResponse->getStatusCode(); 83 | 84 | //Create and return a DropboxRawResponse object 85 | return new DropboxRawResponse($rawHeaders, $body, $httpStatusCode); 86 | } 87 | 88 | /** 89 | * Get the Response Body. 90 | * 91 | * @param string|\Psr\Http\Message\ResponseInterface $response Response object 92 | * 93 | * @return string 94 | */ 95 | protected function getResponseBody($response) 96 | { 97 | //Response must be string 98 | $body = $response; 99 | 100 | if ($response instanceof ResponseInterface) { 101 | //Fetch the body 102 | $body = $response->getBody(); 103 | } 104 | 105 | if ($body instanceof StreamInterface) { 106 | $body = $body->getContents(); 107 | } 108 | 109 | return (string) $body; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/Dropbox/Http/Clients/DropboxHttpClientFactory.php: -------------------------------------------------------------------------------- 1 | httpResponseCode = (int) $statusCode; 41 | } 42 | $this->headers = $headers; 43 | $this->body = $body; 44 | } 45 | 46 | /** 47 | * Get the response headers 48 | * 49 | * @return array 50 | */ 51 | public function getHeaders() 52 | { 53 | return $this->headers; 54 | } 55 | 56 | /** 57 | * Get the response body 58 | * 59 | * @return string 60 | */ 61 | public function getBody() 62 | { 63 | return $this->body; 64 | } 65 | 66 | /** 67 | * Get the HTTP response code 68 | * 69 | * @return int 70 | */ 71 | public function getHttpResponseCode() 72 | { 73 | return $this->httpResponseCode; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Dropbox/Http/RequestBodyInterface.php: -------------------------------------------------------------------------------- 1 | params = $params; 25 | } 26 | 27 | /** 28 | * Get the Body of the Request 29 | * 30 | * @return string|null 31 | */ 32 | public function getBody() 33 | { 34 | //Empty body 35 | if (empty($this->params)) { 36 | return null; 37 | } 38 | 39 | return json_encode($this->params); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Dropbox/Http/RequestBodyStream.php: -------------------------------------------------------------------------------- 1 | file = $file; 27 | } 28 | 29 | /** 30 | * Get the Body of the Request 31 | * 32 | * @return string 33 | */ 34 | public function getBody() 35 | { 36 | return $this->file->getContents(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Dropbox/Models/AccessToken.php: -------------------------------------------------------------------------------- 1 | token = $this->getDataProperty('access_token'); 72 | $this->tokenType = $this->getDataProperty('token_type'); 73 | $this->bearer = $this->getDataProperty('bearer'); 74 | $this->uid = $this->getDataProperty('uid'); 75 | $this->accountId = $this->getDataProperty('account_id'); 76 | $this->teamId = $this->getDataProperty('team_id'); 77 | $this->expiryTime = $this->getDataProperty('expires_in'); 78 | $this->refreshToken = $this->getDataProperty('refresh_token'); 79 | } 80 | 81 | /** 82 | * Get Access Token 83 | * 84 | * @return string 85 | */ 86 | public function getToken() 87 | { 88 | return $this->token; 89 | } 90 | 91 | /** 92 | * Get Refresh Token 93 | * 94 | * @return string 95 | */ 96 | public function getRefreshToken() 97 | { 98 | return $this->refreshToken; 99 | } 100 | 101 | /** 102 | * Get the expiry time 103 | * 104 | * @return int 105 | */ 106 | public function getExpiryTime() 107 | { 108 | return (int) $this->expiryTime; 109 | } 110 | 111 | /** 112 | * Get Token Type 113 | * 114 | * @return string 115 | */ 116 | public function getTokenType() 117 | { 118 | return $this->tokenType; 119 | } 120 | 121 | /** 122 | * Get Bearer 123 | * 124 | * @return string 125 | */ 126 | public function getBearer() 127 | { 128 | return $this->bearer; 129 | } 130 | 131 | /** 132 | * Get User ID 133 | * 134 | * @return string 135 | */ 136 | public function getUid() 137 | { 138 | return $this->uid; 139 | } 140 | 141 | /** 142 | * Get Account ID 143 | * 144 | * @return string 145 | */ 146 | public function getAccountId() 147 | { 148 | return $this->accountId; 149 | } 150 | 151 | /** 152 | * Get Team ID 153 | * 154 | * @return string 155 | */ 156 | public function getTeamId() 157 | { 158 | return $this->teamId; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/Dropbox/Models/Account.php: -------------------------------------------------------------------------------- 1 | account_id = $this->getDataProperty('account_id'); 93 | $this->name = (array) $this->getDataProperty('name'); 94 | $this->email = $this->getDataProperty('email'); 95 | $this->email_verified = $this->getDataProperty('email_verified'); 96 | $this->disabled = $this->getDataProperty('disabled'); 97 | $this->profile_photo_url = $this->getDataProperty('profile_photo_url'); 98 | $this->locale = $this->getDataProperty('locale'); 99 | $this->country = $this->getDataProperty('country'); 100 | $this->referral_link = $this->getDataProperty('referral_link'); 101 | $this->is_paired = $this->getDataProperty('is_paired'); 102 | 103 | //Account Type 104 | $account_type = $this->getDataProperty('account_type'); 105 | 106 | if (is_array($account_type) && !empty($account_type)) { 107 | $this->account_type = $account_type['.tag']; 108 | } 109 | } 110 | 111 | /** 112 | * Get Account ID 113 | * 114 | * @return string 115 | */ 116 | public function getAccountId() 117 | { 118 | return $this->account_id; 119 | } 120 | 121 | /** 122 | * Get Account User's Name Details 123 | * 124 | * @return array 125 | */ 126 | public function getNameDetails() 127 | { 128 | return $this->name; 129 | } 130 | 131 | /** 132 | * Get Display name 133 | * 134 | * @return string 135 | */ 136 | public function getDisplayName() 137 | { 138 | $name = $this->name; 139 | 140 | if (isset($name['display_name'])) { 141 | return $name['display_name']; 142 | } 143 | 144 | return ""; 145 | } 146 | 147 | /** 148 | * Get Account Email 149 | * 150 | * @return string 151 | */ 152 | public function getEmail() 153 | { 154 | return $this->email; 155 | } 156 | 157 | /** 158 | * Whether account email is verified 159 | * 160 | * @return boolean 161 | */ 162 | public function emailIsVerified() 163 | { 164 | return $this->email_verified ? true : false; 165 | } 166 | 167 | /** 168 | * Get Profile Pic URL 169 | * 170 | * @return string 171 | */ 172 | public function getProfilePhotoUrl() 173 | { 174 | return $this->profile_photo_url; 175 | } 176 | 177 | /** 178 | * Whether acocunt has been disabled 179 | * 180 | * @return boolean 181 | */ 182 | public function isDisabled() 183 | { 184 | return $this->disabled ? true : false; 185 | } 186 | 187 | /** 188 | * Get User's two-lettered country code 189 | * 190 | * @return string 191 | */ 192 | public function getCountry() 193 | { 194 | return $this->country; 195 | } 196 | 197 | /** 198 | * Get account language 199 | * 200 | * @return string 201 | */ 202 | public function getLocale() 203 | { 204 | return $this->locale; 205 | } 206 | 207 | /** 208 | * Get user's referral link 209 | * 210 | * @return string 211 | */ 212 | public function getReferralLink() 213 | { 214 | return $this->referral_link; 215 | } 216 | 217 | /** 218 | * Whether work account is paired 219 | * 220 | * @return boolean 221 | */ 222 | public function isPaired() 223 | { 224 | return $this->is_paired ? true : false; 225 | } 226 | 227 | /** 228 | * Get Account Type 229 | * 230 | * @return string 231 | */ 232 | public function getAccountType() 233 | { 234 | return $this->account_type; 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /src/Dropbox/Models/AccountList.php: -------------------------------------------------------------------------------- 1 | processItems($data); 14 | parent::__construct($processedItems); 15 | } 16 | 17 | /** 18 | * Process items and cast them 19 | * to Account Model 20 | * 21 | * @param array $items Unprocessed Items 22 | * 23 | * @return array Array of Account models 24 | */ 25 | protected function processItems(array $items) 26 | { 27 | $processedItems = []; 28 | 29 | foreach ($items as $entry) { 30 | $processedItems[] = new Account($entry); 31 | } 32 | 33 | return $processedItems; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Dropbox/Models/BaseModel.php: -------------------------------------------------------------------------------- 1 | data = $data; 22 | } 23 | 24 | /** 25 | * Get the Model data 26 | * 27 | * @return array 28 | */ 29 | public function getData() 30 | { 31 | return $this->data; 32 | } 33 | 34 | /** 35 | * Get Data Property 36 | * 37 | * @param string $property 38 | * 39 | * @return mixed 40 | */ 41 | public function getDataProperty($property) 42 | { 43 | return isset($this->data[$property]) ? $this->data[$property] : null; 44 | } 45 | 46 | /** 47 | * Handle calls to undefined properties. 48 | * Check whether an item with the key, 49 | * same as the property, is available 50 | * on the data property. 51 | * 52 | * @param string $property 53 | * 54 | * @return mixed|null 55 | */ 56 | public function __get($property) 57 | { 58 | if (array_key_exists($property, $this->getData())) { 59 | return $this->getData()[$property]; 60 | } 61 | 62 | return null; 63 | } 64 | 65 | /** 66 | * Handle calls to undefined properties. 67 | * Sets an item with the defined value 68 | * on the data property. 69 | * 70 | * @param string $property 71 | * @param string $value 72 | * 73 | * @return mixed|null 74 | */ 75 | public function __set($property, $value) 76 | { 77 | $this->data[$property] = $value; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/Dropbox/Models/CopyReference.php: -------------------------------------------------------------------------------- 1 | expires = new DateTime($this->getDataProperty('expires')); 40 | $this->reference = $this->getDataProperty('copy_reference'); 41 | $this->setMetadata(); 42 | } 43 | 44 | /** 45 | * Set Metadata 46 | */ 47 | protected function setMetadata() 48 | { 49 | $metadata = $this->getDataProperty('metadata'); 50 | if (is_array($metadata)) { 51 | $this->metadata = ModelFactory::make($metadata); 52 | } 53 | } 54 | 55 | /** 56 | * Get the expiration date of the copy reference 57 | * 58 | * @return DateTime 59 | */ 60 | public function getExpirationDate() 61 | { 62 | return $this->expires; 63 | } 64 | 65 | /** 66 | * The metadata for the file/folder 67 | * 68 | * @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata 69 | */ 70 | public function getMetadata() 71 | { 72 | return $this->metadata; 73 | } 74 | 75 | /** 76 | * Get the copy reference 77 | * 78 | * @return string 79 | */ 80 | public function getReference() 81 | { 82 | return $this->reference; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/Dropbox/Models/DeletedMetadata.php: -------------------------------------------------------------------------------- 1 | name = $this->getDataProperty('name'); 44 | $this->path_lower = $this->getDataProperty('path_lower'); 45 | $this->sharing_info = $this->getDataProperty('sharing_info'); 46 | $this->path_display = $this->getDataProperty('path_display'); 47 | } 48 | 49 | /** 50 | * Get the 'name' property of the metadata. 51 | * 52 | * @return string 53 | */ 54 | public function getName() 55 | { 56 | return $this->name; 57 | } 58 | 59 | /** 60 | * Get the 'path_lower' property of the metadata. 61 | * 62 | * @return string 63 | */ 64 | public function getPathLower() 65 | { 66 | return $this->path_lower; 67 | } 68 | 69 | /** 70 | * Get the 'path_display' property of the metadata. 71 | * 72 | * @return string 73 | */ 74 | public function getPathDisplay() 75 | { 76 | return $this->path_display; 77 | } 78 | 79 | /** 80 | * Get the 'sharing_info' property of the file model. 81 | * 82 | * @return \Kunnu\Dropbox\Models\FileSharingInfo 83 | */ 84 | public function getSharingInfo() 85 | { 86 | return $this->sharing_info; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Dropbox/Models/File.php: -------------------------------------------------------------------------------- 1 | contents = $contents; 34 | $this->metadata = new FileMetadata($data); 35 | } 36 | 37 | /** 38 | * The metadata for the file 39 | * 40 | * @return \Kunnu\Dropbox\Models\FileMetadata 41 | */ 42 | public function getMetadata() 43 | { 44 | return $this->metadata; 45 | } 46 | 47 | /** 48 | * Get the file contents 49 | * 50 | * @return string 51 | * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException 52 | */ 53 | public function getContents() 54 | { 55 | if ($this->contents instanceof DropboxFile) { 56 | return $this->contents->getContents(); 57 | } 58 | return $this->contents; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Dropbox/Models/FileMetadata.php: -------------------------------------------------------------------------------- 1 | id = $this->getDataProperty('id'); 110 | $this->tag = $this->getDataProperty('.tag'); 111 | $this->rev = $this->getDataProperty('rev'); 112 | $this->name = $this->getDataProperty('name'); 113 | $this->size = $this->getDataProperty('size'); 114 | $this->path_lower = $this->getDataProperty('path_lower'); 115 | $this->path_display = $this->getDataProperty('path_display'); 116 | $this->client_modified = $this->getDataProperty('client_modified'); 117 | $this->server_modified = $this->getDataProperty('server_modified'); 118 | $this->has_explicit_shared_members = $this->getDataProperty('has_explicit_shared_members'); 119 | 120 | //Make MediaInfo 121 | $mediaInfo = $this->getDataProperty('media_info'); 122 | if (is_array($mediaInfo)) { 123 | $this->media_info = new MediaInfo($mediaInfo); 124 | } 125 | 126 | //Make SharingInfo 127 | $sharingInfo = $this->getDataProperty('sharing_info'); 128 | if (is_array($sharingInfo)) { 129 | $this->sharing_info = new FileSharingInfo($sharingInfo); 130 | } 131 | } 132 | 133 | /** 134 | * Get the 'id' property of the file model. 135 | * 136 | * @return string 137 | */ 138 | public function getId() 139 | { 140 | return $this->id; 141 | } 142 | 143 | /** 144 | * Get the '.tag' property of the file model. 145 | * 146 | * @return string 147 | */ 148 | public function getTag() 149 | { 150 | return $this->tag; 151 | } 152 | 153 | /** 154 | * Get the 'name' property of the file model. 155 | * 156 | * @return string 157 | */ 158 | public function getName() 159 | { 160 | return $this->name; 161 | } 162 | 163 | /** 164 | * Get the 'rev' property of the file model. 165 | * 166 | * @return string 167 | */ 168 | public function getRev() 169 | { 170 | return $this->rev; 171 | } 172 | 173 | /** 174 | * Get the 'size' property of the file model. 175 | * 176 | * @return int 177 | */ 178 | public function getSize() 179 | { 180 | return $this->size; 181 | } 182 | 183 | /** 184 | * Get the 'path_lower' property of the file model. 185 | * 186 | * @return string 187 | */ 188 | public function getPathLower() 189 | { 190 | return $this->path_lower; 191 | } 192 | 193 | /** 194 | * Get the 'media_info' property of the file model. 195 | * 196 | * @return \Kunnu\Dropbox\Models\MediaInfo 197 | */ 198 | public function getMediaInfo() 199 | { 200 | return $this->media_info; 201 | } 202 | 203 | /** 204 | * Get the 'sharing_info' property of the file model. 205 | * 206 | * @return \Kunnu\Dropbox\Models\FileSharingInfo 207 | */ 208 | public function getSharingInfo() 209 | { 210 | return $this->sharing_info; 211 | } 212 | 213 | /** 214 | * Get the 'path_display' property of the file model. 215 | * 216 | * @return string 217 | */ 218 | public function getPathDisplay() 219 | { 220 | return $this->path_display; 221 | } 222 | 223 | /** 224 | * Get the 'client_modified' property of the file model. 225 | * 226 | * @return string 227 | */ 228 | public function getClientModified() 229 | { 230 | return $this->client_modified; 231 | } 232 | 233 | /** 234 | * Get the 'server_modified' property of the file model. 235 | * 236 | * @return string 237 | */ 238 | public function getServerModified() 239 | { 240 | return $this->server_modified; 241 | } 242 | 243 | /** 244 | * Get the 'has_explicit_shared_members' property of the file model. 245 | * 246 | * @return bool 247 | */ 248 | public function hasExplicitSharedMembers() 249 | { 250 | return $this->has_explicit_shared_members; 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /src/Dropbox/Models/FileSharingInfo.php: -------------------------------------------------------------------------------- 1 | read_only = $this->getDataProperty('read_only'); 38 | $this->modified_by = $this->getDataProperty('modified_by'); 39 | $this->parent_shared_folder_id = $this->getDataProperty('parent_shared_folder_id'); 40 | } 41 | 42 | /** 43 | * True if the file or folder is inside a read-only shared folder. 44 | * 45 | * @return bool 46 | */ 47 | public function isReadOnly() 48 | { 49 | return $this->read_only; 50 | } 51 | 52 | /** 53 | * ID of shared folder that holds this file. 54 | * 55 | * @return string 56 | */ 57 | public function getParentSharedFolderId() 58 | { 59 | return $this->parent_shared_folder_id; 60 | } 61 | 62 | /** 63 | * Get the last user who modified the file. 64 | * 65 | * @return string 66 | */ 67 | public function getModifiedBy() 68 | { 69 | return $this->modified_by; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Dropbox/Models/FolderMetadata.php: -------------------------------------------------------------------------------- 1 | id = $this->getDataProperty('id'); 61 | $this->tag = $this->getDataProperty('.tag'); 62 | $this->name = $this->getDataProperty('name'); 63 | $this->path_lower = $this->getDataProperty('path_lower'); 64 | $this->path_display = $this->getDataProperty('path_display'); 65 | 66 | //Make SharingInfo 67 | $sharingInfo = $this->getDataProperty('sharing_info'); 68 | if (is_array($sharingInfo)) { 69 | $this->sharing_info = new FolderSharingInfo($sharingInfo); 70 | } 71 | } 72 | 73 | /** 74 | * Get the 'id' property of the folder model. 75 | * 76 | * @return string 77 | */ 78 | public function getId() 79 | { 80 | return $this->id; 81 | } 82 | 83 | /** 84 | * Get the '.tag' property of the folder model. 85 | * 86 | * @return string 87 | */ 88 | public function getTag() 89 | { 90 | return $this->tag; 91 | } 92 | 93 | /** 94 | * Get the 'name' property of the folder model. 95 | * 96 | * @return string 97 | */ 98 | public function getName() 99 | { 100 | return $this->name; 101 | } 102 | 103 | /** 104 | * Get the 'path_lower' property of the folder model. 105 | * 106 | * @return string 107 | */ 108 | public function getPathLower() 109 | { 110 | return $this->path_lower; 111 | } 112 | 113 | /** 114 | * Get the 'sharing_info' property of the folder model. 115 | * 116 | * @return \Kunnu\Dropbox\Models\FolderSharingInfo 117 | */ 118 | public function getSharingInfo() 119 | { 120 | return $this->sharing_info; 121 | } 122 | 123 | /** 124 | * Get the 'path_display' property of the folder model. 125 | * 126 | * @return string 127 | */ 128 | public function getPathDisplay() 129 | { 130 | return $this->path_display; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/Dropbox/Models/FolderSharingInfo.php: -------------------------------------------------------------------------------- 1 | read_only = $this->getDataProperty('read_only'); 40 | $this->shared_folder_id = $this->getDataProperty('shared_folder_id'); 41 | $this->parent_shared_folder_id = $this->getDataProperty('parent_shared_folder_id'); 42 | } 43 | 44 | /** 45 | * True if the folder or folder is inside a read-only shared folder. 46 | * 47 | * @return bool 48 | */ 49 | public function isReadOnly() 50 | { 51 | return $this->read_only; 52 | } 53 | 54 | /** 55 | * ID of shared folder that holds this folder. 56 | * 57 | * @return string 58 | */ 59 | public function getParentSharedFolderId() 60 | { 61 | return $this->parent_shared_folder_id; 62 | } 63 | 64 | /** 65 | * ID of shared folder. 66 | * 67 | * @return string 68 | */ 69 | public function getSharedFolderId() 70 | { 71 | return $this->shared_folder_id; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/Dropbox/Models/MediaInfo.php: -------------------------------------------------------------------------------- 1 | pending = $this->getDataProperty('pending'); 32 | $this->setMediaMetadata(); 33 | } 34 | 35 | /** 36 | * Set Media Metadata 37 | */ 38 | protected function setMediaMetadata() 39 | { 40 | $mediaMetadata = $this->getDataProperty('metadata'); 41 | if (is_array($mediaMetadata)) { 42 | if ($mediaMetadata['.tag'] === 'photo') { 43 | //Media is Photo 44 | $this->mediaMetadata = new PhotoMetadata($mediaMetadata); 45 | } elseif ($mediaMetadata['.tag'] === 'video') { 46 | //Media is Video 47 | $this->mediaMetadata = new VideoMetadata($mediaMetadata); 48 | } else { 49 | //Unknown Media (Quite unlikely, though.) 50 | $this->mediaMetadata = new MediaMetadata($mediaMetadata); 51 | } 52 | } 53 | } 54 | 55 | /** 56 | * Indicates whether the photo/video is still under 57 | * processing and is the metadata available yet. 58 | * 59 | * @return bool 60 | */ 61 | public function isPending() 62 | { 63 | return $this->pending; 64 | } 65 | 66 | /** 67 | * The metadata for the photo/video. 68 | * 69 | * @return \Kunnu\Dropbox\Models\MediaMetadata 70 | */ 71 | public function getMediaMetadata() 72 | { 73 | return $this->mediaMetadata; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Dropbox/Models/MediaMetadata.php: -------------------------------------------------------------------------------- 1 | location = (array) $this->getDataProperty('location'); 40 | $this->dimensions = (array) $this->getDataProperty('dimensions'); 41 | 42 | $time_taken = $this->getDataProperty('time_taken'); 43 | if ($time_taken) { 44 | $this->time_taken = new DateTime($time_taken); 45 | } 46 | } 47 | 48 | /** 49 | * Get the location of the Media 50 | * 51 | * @return array 52 | */ 53 | public function getLocation() 54 | { 55 | return $this->location; 56 | } 57 | 58 | /** 59 | * Get the dimensions of the Media 60 | * 61 | * @return array 62 | */ 63 | public function getDimensions() 64 | { 65 | return $this->dimensions; 66 | } 67 | 68 | /** 69 | * Get the Time the Media was taken on 70 | * 71 | * @return DateTime 72 | */ 73 | public function getTimeTaken() 74 | { 75 | return $this->time_taken; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/Dropbox/Models/MetadataCollection.php: -------------------------------------------------------------------------------- 1 | cursor = isset($data[$this->getCollectionCursorKey()]) ? $data[$this->getCollectionCursorKey()] : ''; 66 | $this->hasMoreItems = isset($data[$this->getCollectionHasMoreItemsKey()]) && $data[$this->getCollectionHasMoreItemsKey()] ? true : false; 67 | 68 | $items = isset($data[$this->getCollectionItemsKey()]) ? $data[$this->getCollectionItemsKey()] : []; 69 | $this->processItems($items); 70 | } 71 | 72 | /** 73 | * Get the Collection Items Key 74 | * 75 | * @return string 76 | */ 77 | public function getCollectionItemsKey() 78 | { 79 | return static::COLLECTION_ITEMS_KEY; 80 | } 81 | 82 | /** 83 | * Get the Collection has-more-items Key 84 | * 85 | * @return string 86 | */ 87 | public function getCollectionHasMoreItemsKey() 88 | { 89 | return static::COLLECTION_HAS_MORE_ITEMS_KEY; 90 | } 91 | 92 | /** 93 | * Get the Collection Cursor Key 94 | * 95 | * @return string 96 | */ 97 | public function getCollectionCursorKey() 98 | { 99 | return static::COLLECTION_CURSOR_KEY; 100 | } 101 | 102 | /** 103 | * Get the Items 104 | * 105 | * @return \Kunnu\Dropbox\Models\ModelCollection 106 | */ 107 | public function getItems() 108 | { 109 | return $this->items; 110 | } 111 | 112 | /** 113 | * Get the cursor 114 | * 115 | * @return string 116 | */ 117 | public function getCursor() 118 | { 119 | return $this->cursor; 120 | } 121 | 122 | /** 123 | * More items are available 124 | * 125 | * @return boolean 126 | */ 127 | public function hasMoreItems() 128 | { 129 | return $this->hasMoreItems; 130 | } 131 | 132 | /** 133 | * Process items and cast them 134 | * to their respective Models 135 | * 136 | * @param array $items Unprocessed Items 137 | * 138 | * @return void 139 | */ 140 | protected function processItems(array $items) 141 | { 142 | $processedItems = []; 143 | 144 | foreach ($items as $entry) { 145 | $processedItems[] = ModelFactory::make($entry); 146 | } 147 | 148 | $this->items = new ModelCollection($processedItems); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/Dropbox/Models/ModelCollection.php: -------------------------------------------------------------------------------- 1 | getDataProperty('match_type'); 31 | $this->matchType = isset($matchType['.tag']) ? $matchType['.tag'] : null; 32 | $this->setMetadata(); 33 | } 34 | 35 | /** 36 | * Set Metadata 37 | * 38 | * @return void 39 | */ 40 | protected function setMetadata() 41 | { 42 | $metadata = $this->getDataProperty('metadata'); 43 | 44 | if (is_array($metadata)) { 45 | $this->metadata = ModelFactory::make($metadata); 46 | } 47 | } 48 | 49 | /** 50 | * Indicates what type of match was found for the result 51 | * 52 | * @return bool 53 | */ 54 | public function getMatchType() 55 | { 56 | return $this->matchType; 57 | } 58 | 59 | /** 60 | * Get the Search Result Metadata 61 | * 62 | * @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata 63 | */ 64 | public function getMetadata() 65 | { 66 | return $this->metadata; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/Dropbox/Models/SearchResults.php: -------------------------------------------------------------------------------- 1 | items = new ModelCollection($processedItems); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Dropbox/Models/TemporaryLink.php: -------------------------------------------------------------------------------- 1 | link = $this->getDataProperty('link'); 31 | $this->setMetadata(); 32 | } 33 | 34 | /** 35 | * Set Metadata 36 | */ 37 | protected function setMetadata() 38 | { 39 | $metadata = $this->getDataProperty('metadata'); 40 | if (is_array($metadata)) { 41 | $this->metadata = new FileMetadata($metadata); 42 | } 43 | } 44 | 45 | /** 46 | * The metadata for the file 47 | * 48 | * @return \Kunnu\Dropbox\Models\FileMetadata 49 | */ 50 | public function getMetadata() 51 | { 52 | return $this->metadata; 53 | } 54 | 55 | /** 56 | * Get the temporary link 57 | * 58 | * @return string 59 | */ 60 | public function getLink() 61 | { 62 | return $this->link; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Dropbox/Models/Thumbnail.php: -------------------------------------------------------------------------------- 1 | duration = $this->getDataProperty('duration'); 23 | } 24 | 25 | /** 26 | * Get the duration of the video 27 | * 28 | * @return int 29 | */ 30 | public function getDuration() 31 | { 32 | return $this->duration; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Dropbox/Security/McryptRandomStringGenerator.php: -------------------------------------------------------------------------------- 1 | binToHex($binaryString, $length); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Dropbox/Security/OpenSslRandomStringGenerator.php: -------------------------------------------------------------------------------- 1 | binToHex($binaryString, $length); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Dropbox/Security/RandomStringGeneratorFactory.php: -------------------------------------------------------------------------------- 1 | prefix = $prefix; 22 | } 23 | 24 | /** 25 | * Get a value from the store 26 | * 27 | * @param string $key Data Key 28 | * 29 | * @return string|null 30 | */ 31 | public function get($key) 32 | { 33 | if (isset($_SESSION[$this->prefix . $key])) { 34 | return $_SESSION[$this->prefix . $key]; 35 | } 36 | 37 | return null; 38 | } 39 | 40 | /** 41 | * Set a value in the store 42 | * @param string $key Data Key 43 | * @param string $value Data Value 44 | * 45 | * @return void 46 | */ 47 | public function set($key, $value) 48 | { 49 | $_SESSION[$this->prefix . $key] = $value; 50 | } 51 | 52 | /** 53 | * Clear the key from the store 54 | * 55 | * @param $key Data Key 56 | * 57 | * @return void 58 | */ 59 | public function clear($key) 60 | { 61 | if (isset($_SESSION[$this->prefix . $key])) { 62 | unset($_SESSION[$this->prefix . $key]); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /tests/DropboxFileTest.php: -------------------------------------------------------------------------------- 1 | stream = fopen(__FILE__, 'r'); 13 | } 14 | 15 | public function tearDown() 16 | { 17 | fclose($this->stream); 18 | } 19 | 20 | public function testGetStreamOrFilePathReturnsStringWhenConstructedNormally() 21 | { 22 | /** @var \PHPUnit_Framework_MockObject_MockObject|DropboxFile $dropboxFile */ 23 | $dropboxFile = $this->getMockBuilder(DropboxFile::class) 24 | ->setMethods(['getFilePath', 'getStream', 'isCreatedFromStream']) 25 | ->disableOriginalConstructor() 26 | ->getMock(); 27 | 28 | $dropboxFile 29 | ->expects($this->any()) 30 | ->method('getFilePath') 31 | ->willReturn('/i/am/a/file'); 32 | 33 | $dropboxFile 34 | ->expects($this->never()) 35 | ->method('getStream'); 36 | 37 | $dropboxFile 38 | ->expects($this->atLeastOnce()) 39 | ->method('isCreatedFromStream') 40 | ->willReturn(false); 41 | 42 | $result = $dropboxFile->getStreamOrFilePath(); 43 | 44 | self::assertSame('/i/am/a/file', $result); 45 | } 46 | 47 | public function testGetStreamOrFilePathReturnsStringWhenConstructedWithStream() 48 | { 49 | /** @var \PHPUnit_Framework_MockObject_MockObject|DropboxFile $dropboxFile */ 50 | $dropboxFile = $this->getMockBuilder(DropboxFile::class) 51 | ->setMethods(['getFilePath', 'getStream', 'isCreatedFromStream']) 52 | ->disableOriginalConstructor() 53 | ->getMock(); 54 | 55 | $dropboxFile 56 | ->expects($this->never()) 57 | ->method('getFilePath'); 58 | 59 | $dropboxFile 60 | ->expects($this->any()) 61 | ->method('getStream') 62 | ->willReturn($this->stream); 63 | 64 | $dropboxFile 65 | ->expects($this->atLeastOnce()) 66 | ->method('isCreatedFromStream') 67 | ->willReturn(true); 68 | 69 | $result = $dropboxFile->getStreamOrFilePath(); 70 | 71 | self::assertSame($this->stream, $result); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /tests/DropboxTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(0, 5 - 5); 9 | } 10 | } 11 | --------------------------------------------------------------------------------