files.com/files-php-sdk

Files.com PHP SDK

v2.0.108 2024-11-20 17:41 UTC

This package is auto-updated.

Last update: 2024-11-20 17:41:59 UTC


README

The Files.com PHP SDK provides convenient Files.com API access to applications written in PHP.

The content included here should be enough to get started, but please visit our Developer Documentation Website for the complete documentation.

Introduction

The Files.com PHP SDK provides convenient access to all of Files.com from applications written in PHP.

You can use it to directly work with files and folders as well as perform management tasks such as adding/removing users, onboarding counterparties, retrieving information about automations and more.

Installation

The Files.com PHP SDK is installed using Composer. See https://packagist.org for more info.

First, install Composer if necessary:

curl -sS https://getcomposer.org/installer | php

Then use Composer to install the Files.com SDK:

php composer.phar require files.com/files-php-sdk

Requirements

  • PHP 5.5+
  • php-curl extension

Explore the files-sdk-php code on GitHub.

Getting Support

The Files.com Support team provides official support for all of our official Files.com integration tools.

To initiate a support conversation, you can send an Authenticated Support Request or simply send an E-Mail to support@files.com.

Authentication

Authenticate with an API Key

Authenticating with an API key is the recommended authentication method for most scenarios, and is the method used in the examples on this site.

To use the API or SDKs with an API Key, first generate an API key from the web interface or via the API or an SDK.

Note that when using a user-specific API key, if the user is an administrator, you will have full access to the entire API. If the user is not an administrator, you will only be able to access files that user can access, and no access will be granted to site administration functions in the API.

\Files\Files::setApiKey('YOUR_API_KEY');

## Alternatively, you can specify the API key on a per-object basis in the second parameter to a model constructor.
$user = new \Files\Model\User($params, array('api_key' => 'YOUR_API_KEY'));

## You may also specify the API key on a per-request basis in the final parameter to static methods.
\Files\Model\User::find($id, $params, array('api_key' => 'YOUR_API_KEY'));

Don't forget to replace the placeholder, YOUR_API_KEY, with your actual API key.

Authenticate with a Session

You can also authenticate to the REST API or SDKs by creating a user session using the username and password of an active user. If the user is an administrator, the session will have full access to the entire API. Sessions created from regular user accounts will only be able to access files that user can access, and no access will be granted to site administration functions.

API sessions use the exact same session timeout settings as web interface sessions. When an API session times out, simply create a new session and resume where you left off. This process is not automatically handled by SDKs because we do not want to store password information in memory without your explicit consent.

Logging In

To create a session, the create method is called on the \Files\Model\Session object with the user's username and password.

This returns a session object that can be used to authenticate SDK method calls.

$session = \Files\Model\Session::create(['username' => 'motor', 'password' => 'vroom']);

Using a Session

Once a session has been created, you can store the session globally, use the session per object, or use the session per request to authenticate SDK operations.

## You may set the returned session ID to be used by default for subsequent requests.
\Files\Files::setSessionId($session->id);

## Alternatively, you can specify the session ID on a per-object basis in the second parameter to a model constructor.
$user = new \Files\Model\User($params, array('session_id' => $session->id));

## You may also specify the session ID on a per-request basis in the final parameter to static methods.
\Files\Model\User::find($id, $params, array('session_id' => $session->id));

Logging Out

User sessions can be ended by calling the Session::destroy method.

\Files\Model\Session::destroy();

Configuration

Global configuration can be done by setting properties directly on the \Files\Files class.

Configuration Options

Auto Paginate

Auto-fetch all pages when results span multiple pages. The default value is true.

\Files\Files::$autoPaginate = false

Base URL

Setting the base URL for the API is required if your site is configured to disable global acceleration. This can also be set to use a mock server in development or CI.

\Files\Files::setBaseUrl('https://MY-SUBDOMAIN.files.com');

Log Level

Supported values:

  • \Files\LogLevel::NONE
  • \Files\LogLevel::ERROR
  • \Files\LogLevel::WARN
  • \Files\LogLevel::INFO (default)
  • \Files\LogLevel::DEBUG
\Files\Files::$logLevel = \Files\LogLevel::DEBUG

Debug Requests

Enable debug logging of API requests. The default value is false.

\Files\Files::$debugRequest = true

Debug Response Headers

Enable debug logging of API response headers. The default value is false.

\Files\Files::$debugResponseHeaders = true

Connect Timeout

Network connect timeout in seconds. The default value is 30.0.

\Files\Files::$connectTimeout = 20.0

Read Timeout

Network read timeout in seconds. The default value is 90.

\Files\Files::$readTimeout = 60

Minimum Retry Delay

Minimum network delay in seconds before retrying. The default value is 0.5.

\Files\Files::$minNetworkRetryDelay = 1.0

Maximum Retry Delay

Maximum network delay in seconds before retrying. The default value is 1.5.

\Files\Files::$maxNetworkRetryDelay = 3.0

Maximum Network Retries

Maximum number of retries. The default value is 3.

\Files\Files::$maxNetworkRetries = 5

Sort and Filter

Several of the Files.com API resources have list operations that return multiple instances of the resource. The List operations can be sorted and filtered.

Sorting

To sort the returned data, pass in the sort_by method argument.

Each resource supports a unique set of valid sort fields and can only be sorted by one field at a time.

The argument value is a Php associative array that has a key of the resource field name sort on and a value of either "asc" or "desc" to specify the sort order.

// users sorted by username
\Files\Files::setApiKey('my-key');
$users = \Files\Model\User::list(array(
  'sort_by' => array("username" => "asc")
));

Filtering

Filters apply selection criteria to the underlying query that returns the results. They can be applied individually or combined with other filters, and the resulting data can be sorted by a single field.

Each resource supports a unique set of valid filter fields, filter combinations, and combinations of filters and sort fields.

The passed in argument value is a Php associative array that has a key of the resource field name to filter on and a passed in value to use in the filter comparison.

Filter Types

// non admin users
\Files\Files::setApiKey('my-key');
$users = \Files\Model\User::list(array(
  'filter' => array("not_site_admin" => true)
));

foreach ($users as $value) {
  print("User username: " . $value->getUserName() . "\n");
}
// users who haven't logged in since 2024-01-01
\Files\Files::setApiKey('my-key');
$users = \Files\Model\User::list(array(
  'filter_gteq' => array("last_login_at" => "2024-01-01")
));

foreach ($users as $value) {
  print("User username: " . $value->getUserName() . "\n");
}
// users whose usernames start with 'test'
\Files\Files::setApiKey('my-key');
$users = \Files\Model\User::list(array(
  'filter_prefix' => array("username" => "test")
));

foreach ($users as $value) {
  print("User username: " . $value->getUserName() . "\n");
}
// users whose usernames start with 'test' and are not admins
\Files\Files::setApiKey('my-key');
$users = \Files\Model\User::list(array(
  'filter_prefix' => array("username" => "test"),
  'filter' => array("not_site_admin" => true),
  'sort_by' => array("last_login_at" => "asc")
));

foreach ($users as $value) {
  print("User username: " . $value->getUserName() . "\n");
}

Errors

The Files.com PHP SDK will return errors by raising exceptions. There are many exception classes defined in the Files SDK that correspond to specific errors.

The raised exceptions come from two categories:

  1. SDK Exceptions - errors that originate within the SDK
  2. API Exceptions - errors that occur due to the response from the Files.com API. These errors are grouped into common error types.

There are several types of exceptions within each category. Exception classes indicate different types of errors and are named in a fashion that describe the general premise of the originating error. More details can be found in the exception object message using the php getMessage() method call.

Use standard PHP exception handling to detect and deal with errors. It is generally recommended to catch specific errors first, then catch the general Files\FilesException exception as a catch-all.

try {
  $session = Files\Model\Session::create(['username' => 'USERNAME', 'password' => 'BADPASSWORD']);
} catch (Files\NotAuthenticated\InvalidUsernameOrPasswordException $e) {
  echo 'Authentication Error Occurred (' . get_class($e) . '): ',  $e->getMessage(), "\n";
} catch (Files\FilesException $e) {
  echo 'Unknown Error Occurred (' . get_class($e) . '): ',  $e->getMessage(), "\n";
}

Error Types

SDK Errors

SDK errors are general errors that occur within the SDK code. These errors generate exceptions. Each of these exception classes inherit from a standard Exception base class.

Files\Exception\ApiConnectException ->
Files\Exception\FilesException ->
Exception
SDK Exception Classes

API Errors

API errors are errors returned by the Files.com API. Each exception class inherits from an error group base class. The error group base class indicates a particular type of error.

Files\Exception\NotAuthorizedException\FolderAdminPermissionRequiredException ->
Files\Exception\NotAuthorizedException ->
Files\Exception\ApiException ->
Files\Exception\FilesException ->
Exception
API Exception Classes

Examples

Static File Operations

List Files in Root Folder

$rootFiles = \Files\Model\Folder::listFor('/');
foreach ($rootFiles as $file) {
    echo $file->getPath() . "\n";
}

Uploading a File on Disk

$sourceFilePath = 'local.txt';
$destinationFileName = 'uploads/remote.txt';
\Files\Model\File::uploadFile($destinationFileName, $sourceFilePath);

If the parent directories do not already exist, they can be automatically created by passing mkdir_parents in the params.

\Files\Model\File::uploadFile($destinationFileName, $sourceFilePath, ['mkdir_parents' => true]);

Writing a File

$fileData = 'contents';
$destinationFileName = 'uploads/remote.txt';
\Files\Model\File::uploadData($destinationFileName, $fileData);

Reading a File to Stream

$outputStream = fopen('php://output', 'w');
$remoteFilePath = 'uploads/remote.txt';
\Files\Model\File::downloadToStream($remoteFilePath, $outputStream);

Download a File to Disk

$localFilePath = 'local.txt';
$remoteFilePath = 'uploads/remote.txt';

// download entire file - with retries enabled
\Files\Model\File::downloadToFile($remoteFilePath, $localFilePath);

// partially download - just the first KB
\Files\Model\File::partialDownloadToFile($remoteFilePath, $localFilePath, 0, 1023);

// resume an incomplete download
\Files\Model\File::resumeDownloadToFile($remoteFilePath, $localFilePath);

Getting a File Record by Path

$remoteFilePath = 'uploads/remote.txt';
$foundFile = \Files\Model\File::find($remoteFilePath);

File Object Operations

Getting a File Record by Path

$remoteFilePath = 'uploads/remote.txt';
$file = new \Files\Model\File();
$file->get($remoteFilePath);
Updating Metadata
$file->update([
    'provided_mtime' => '2000-01-01T01:00:00Z',
    'priority_color' => 'red',
]);
Retrieving Metadata
$file->metadata([
    'with_previews' => true,
    'with_priority_color' => true,
]);

Comparing Case-Insensitive Files and Paths

For related documentation see Case Sensitivity Documentation.

if(\Files\Util\PathUtil::same("Fïłèńämê.Txt", "filename.txt")) {
    echo "Paths are the same\n";
}

Mock Server

Files.com publishes a Files.com API server, which is useful for testing your use of the Files.com SDKs and other direct integrations against the Files.com API in an integration test environment.

It is a Ruby app that operates as a minimal server for the purpose of testing basic network operations and JSON encoding for your SDK or API client. It does not maintain state and it does not deeply inspect your submissions for correctness.

Eventually we will add more features intended for integration testing, such as the ability to intentionally provoke errors.

Download the server as a Docker image via Docker Hub.

The Source Code is also available on GitHub.

A README is available on the GitHub link.

Upgrading

Upgrading to Version 2.0 from previous versions

In Version 2.0, the Files.com PHP SDK was updated to comply with both the PSR-12 coding standard and the PSR-4 autoloading standard. No new classes were added or any existing classes removed, but some were moved to comply with the PSR-4 standard. If a client of the sdk references the moved classes, the client code will need to be updated to reference the new location of these classes.

Exception Classes

The affected classes were primarily Exception classes. Exceptions were moved into their own namespace (and source files).

The following table shows the classes that were changed for compliance

Base Exceptions

The Base exception were moved from the \Files namespace to the \Files\Exception namespace.

Examples of Base Exceptions Classes moved.

BadRequest Exceptions

The BadRequest group of exceptions were moved from the \Files\BadRequest namespace to the \Files\Exception\BadRequest namespace.

Example of BadRequest Classes moved.

NotAuthenticated Exceptions

The NotAuthenticated group of exceptions were moved from the \Files\NotAuthenticated namespace to the \Files\Exception\NotAuthenticated namespace.

Example of NotAuthenticated Classes moved.

NotAuthorized Exceptions

The NotAuthorized group of exceptions were moved from the \Files\NotAuthorized namespace to the \Files\Exception\NotAuthorized namespace.

Example of NotAuthorized Classes moved.

NotFound Exceptions

The NotFound group of exceptions were moved from the \Files\NotFound namespace to the \Files\Exception\NotFound namespace.

Example of NotFound Classes moved.

ProcessingFailure Exceptions

The ProcessingFailure group of exceptions were moved from the \Files\ProcessingFailure namespace to the \Files\Exception\ProcessingFailure namespace.

Example of ProcessingFailure Classes moved.

RateLimited Exceptions

The ProcessingFailure group of exceptions were moved from the \Files\RateLimited namespace to the \Files\Exception\RateLimited namespace.

Example of RateLimited Classes moved.

ServiceUnavailable Exceptions

The ServiceUnavailable group of exceptions were moved from the \Files\ServiceUnavailable namespace to the \Files\Exception\ServiceUnavailable namespace.

Example of ServiceUnavailable Classes moved.

SiteConfiguration Exceptions

The SiteConfiguration group of exceptions were moved from the \Files\SiteConfiguration namespace to the \Files\Exception\SiteConfiguration namespace.

Example of SiteConfiguration Classes moved.