diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..e7d03a4
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,32 @@
+name: Tests
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+
+jobs:
+ tests:
+ name: Playground against the Appwrite API stub
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ # appwrite/appwrite 32.x requires PHP 8.5.
+ php-version: '8.5'
+ extensions: curl, json
+ tools: composer:v2
+
+ - name: Install dependencies
+ run: composer install --no-interaction --no-progress --prefer-dist
+
+ - name: Lint
+ run: find . -path ./vendor -prune -o -name '*.php' -print0 | xargs -0 -n1 php -l
+
+ - name: Test
+ run: composer test
diff --git a/Dockerfile b/Dockerfile
index 700aa6d..d0a464b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,16 +1,17 @@
-FROM composer AS composer
+FROM php:8.5-cli
-COPY composer.json composer.json
-COPY composer.lock composer.lock
+COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
-RUN composer install --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends unzip \
+ && rm -rf /var/lib/apt/lists/*
-FROM php:8.1.11-alpine3.16
+WORKDIR /app
-COPY --from=composer /app/vendor /app/vendor
-COPY global.inc.php /app/global.inc.php
-COPY playground.php /app/playground.php
-COPY test.txt /app/test.txt
+COPY composer.json ./
+RUN composer install --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader
-WORKDIR /app
-CMD php playground.php
+COPY global.inc.php playground.php test.txt ./
+COPY resources ./resources
+
+CMD ["php", "playground.php"]
diff --git a/README.md b/README.md
index 4bfdaf5..89a07f3 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,8 @@ Appwrite playground is a simple way to explore the Appwrite API & Appwrite PHP S
This playground doesn't include any PHP best practices but rather intended to show some of the most simple examples and use cases of using the Appwrite API in your PHP application and server.
## System Requirements
-* A system with PHP installed.
+* PHP 8.5 or newer, with the `curl` and `json` extensions. The Appwrite PHP SDK
+ (`appwrite/appwrite` 32.x) requires PHP 8.5.
* You have readily available Appwrite running instance (localhost in most cases).
* Create a project in Appwrite instance using console.
* Generate a secret key in the Appwrite instance using console.
@@ -19,19 +20,35 @@ This playground doesn't include any PHP best practices but rather intended to sh
### Installation
1. Clone this repository.
2. cd into to repository.
-3. Copy the project_id, endpoint, and secret key from your Appwrite Console into the global.inc.php file.
+3. Copy the project_id, endpoint, and secret key from your Appwrite Console into the global.inc.php file, or pass them through the `APPWRITE_ENDPOINT`, `APPWRITE_PROJECT_ID` and `APPWRITE_API_KEY` environment variables.
4. Install dependencies using composer (`composer install`).
5. Execute the command `php playground.php`
6. You will see the JSON response in the console.
### API Covered in Playground.
-* Create Collection
-* List Collection
-* Add Document
-* List Documents
+* Create Database
+* Create Table
+* List Tables
+* Add Row
+* List Rows
* Upload File
+* List Files
* Create User
* List User
+* Create Function
+* Create Deployment
+* Create Execution
+
+Databases now hold tables of rows. The older collections and documents API is
+deprecated since Appwrite 1.8, so the playground uses the `TablesDB` service.
+
+### Tests
+`composer test` drives every example against a stub of the Appwrite API, so it
+needs no running instance:
+
+```
+composer test
+```
## Contributing
diff --git a/composer.json b/composer.json
index 060e8c4..f9e1aba 100644
--- a/composer.json
+++ b/composer.json
@@ -23,14 +23,21 @@
}
],
"require": {
- "php": ">=8.0",
+ "php": ">=8.5",
"ext-curl": "*",
- "appwrite/appwrite": "^12.0.0"
+ "ext-json": "*",
+ "appwrite/appwrite": "^32.2.0"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist"
},
+ "scripts": {
+ "test": [
+ "@php tests/smoke.php",
+ "@php tests/playground-run.php"
+ ]
+ },
"support": {
"email": "team@appwrite.io",
"issues": "https://github.com/appwrite/playground-for-php/issues",
diff --git a/docker-compose.yml b/docker-compose.yml
index 6a82cab..c4cf3d3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,9 +1,13 @@
-version: '3.9'
-
services:
playground-for-php:
build: .
+ # Mount the files worth editing rather than the whole directory, so the
+ # dependencies installed into the image stay in place.
volumes:
- - "./:/app"
- working_dir: /app
- command: "php playground.php"
\ No newline at end of file
+ - "./playground.php:/app/playground.php"
+ - "./global.inc.php:/app/global.inc.php"
+ environment:
+ - APPWRITE_ENDPOINT
+ - APPWRITE_PROJECT_ID
+ - APPWRITE_API_KEY
+ command: "php playground.php"
diff --git a/global.inc.php b/global.inc.php
index ec4a717..20592a8 100644
--- a/global.inc.php
+++ b/global.inc.php
@@ -1,16 +1,20 @@
');
+ \define('PROJECT_ID', \getenv('APPWRITE_PROJECT_ID') ?: '');
}
if (!\defined('API_KEY')) {
- \define('API_KEY', '');
+ \define('API_KEY', \getenv('APPWRITE_API_KEY') ?: '');
}
// Helper functions
diff --git a/playground.php b/playground.php
index c1e7283..1a71803 100644
--- a/playground.php
+++ b/playground.php
@@ -9,9 +9,9 @@
use Appwrite\Permission;
use Appwrite\Role;
use Appwrite\Services\Account;
-use Appwrite\Services\Databases;
use Appwrite\Services\Functions;
use Appwrite\Services\Storage;
+use Appwrite\Services\TablesDB;
use Appwrite\Services\Users;
$client = (new Client())
@@ -20,11 +20,13 @@
// ->setJWT('jwt') // Use this to authenticate with JWT generated from client
->setKey(API_KEY);
-$collectionId = "";
+$tableId = "";
$databaseId = "";
$bucketId = "";
+$fileId = "";
+$functionId = "";
-$databases = new Databases($client);
+$tablesDB = new TablesDB($client);
$storage = new Storage($client);
$functions = new Functions($client);
$users = new Users($client);
@@ -34,10 +36,11 @@
* Covered API methods
* - createDatabase
* - deleteDatabase
- * - createCollection
- * - deleteCollection
- * - listCollection
- * - addDoc
+ * - createTable
+ * - deleteTable
+ * - listTables
+ * - addRow
+ * - listRows
* - uploadFile
* - listFiles
* - deleteFile
@@ -49,19 +52,19 @@
/**
* Create a new Database.
*
- * @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreate
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#create
* @throws Exception
*/
function createDatabase(): array
{
- global $databases, $databaseId;
+ global $tablesDB, $databaseId;
- $response = $databases->create(
+ $response = $tablesDB->create(
databaseId: ID::unique(),
name: "Test Database"
);
- $databaseId = $response['$id'];
+ $databaseId = $response->id;
return [
'call' => 'api.createDatabase',
@@ -70,19 +73,19 @@ function createDatabase(): array
}
/**
-* Create a new Collection.
+* Create a new Table.
*
-* @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreateCollection
+* @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#createTable
* @throws Exception
*/
-function createCollection(): array
+function createTable(): array
{
- global $databases, $databaseId, $collectionId;
+ global $tablesDB, $databaseId, $tableId;
- $response = $databases->createCollection(
+ $response = $tablesDB->createTable(
databaseId: $databaseId,
- collectionId: ID::unique(),
- name: 'collection',
+ tableId: ID::unique(),
+ name: 'table',
permissions: [
Permission::read(Role::any()),
Permission::create(Role::users()),
@@ -91,65 +94,105 @@ function createCollection(): array
]
);
- $collectionId = $response['$id'];
+ $tableId = $response->id;
- $response1 = $databases->createStringAttribute(
+ $tablesDB->createStringColumn(
$databaseId,
- $collectionId,
+ $tableId,
key: 'name',
size: 255,
required: true,
);
- $response2 = $databases->createIntegerAttribute(
+ $tablesDB->createIntegerColumn(
$databaseId,
- $collectionId,
+ $tableId,
key: 'release_year',
required: true,
min: 0,
max: 9999,
);
+ // Columns are created asynchronously, so a row can only be written once the
+ // server reports every column as available.
+ awaitColumns(['name', 'release_year']);
+
return [
- 'call' => 'api.createCollection',
+ 'call' => 'api.createTable',
'response' => $response,
];
}
/**
- * Get a list of all the user collections.
- * On admin mode, this endpoint will return a list of all of the project collections.
+ * Wait until every given column of the current table is available.
*
- * @see https://appwrite.io/docs/server/databases?sdk=php#databasesListCollections
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#listColumns
+ * @param array $keys
+ * @throws Exception
+ */
+function awaitColumns(array $keys, int $timeout = 30): void
+{
+ global $tablesDB, $databaseId, $tableId;
+
+ $deadline = \time() + $timeout;
+
+ do {
+ $statuses = [];
+
+ foreach ($tablesDB->listColumns($databaseId, $tableId)->columns as $column) {
+ $statuses[$column['key'] ?? ''] = $column['status'] ?? 'unknown';
+ }
+
+ $pending = \array_filter(
+ $keys,
+ fn (string $key): bool => ($statuses[$key] ?? 'unknown') !== 'available'
+ );
+
+ if (\count($pending) === 0) {
+ return;
+ }
+
+ \sleep(1);
+ } while (\time() < $deadline);
+
+ throw new Exception('Columns did not become available in time: ' . \implode(', ', $pending));
+}
+
+/**
+ * Get a list of all the user tables.
+ * On admin mode, this endpoint will return a list of all of the project tables.
+ *
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#listTables
* @return array
* @throws Exception
*/
-function listCollections(): array
+function listTables(): array
{
- global $databases, $databaseId;
+ global $tablesDB, $databaseId;
- $response = $databases->listCollections($databaseId);
+ $response = $tablesDB->listTables($databaseId);
return [
- 'call' => 'api.listCollections',
+ 'call' => 'api.listTables',
'response' => $response,
];
}
/**
- * Create a new Document.
- * Before using this route, you should create a new collection resource
+ * Create a new Row.
+ * Before using this route, you should create a new table resource
*
- * @see https://appwrite.io/docs/server/databases?sdk=php#databasesCreateDocument
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#createRow
* @return array
* @throws Exception
*/
-function addDoc(): array
+function addRow(): array
{
- global $databases, $databaseId, $collectionId;
- $response = $databases->createDocument(
+ global $tablesDB, $databaseId, $tableId;
+
+ $response = $tablesDB->createRow(
$databaseId,
- $collectionId,
- documentId: ID::unique(),
+ $tableId,
+ rowId: ID::unique(),
data: [
'name' => 'Spider Man',
'release_year' => 1920,
@@ -162,27 +205,46 @@ function addDoc(): array
);
return [
- 'call' => 'api.addDoc',
+ 'call' => 'api.addRow',
'response' => $response,
];
}
/**
- * Delete collection
- * Delete a collection by it's unique id.
+ * Get a list of all the rows of a table.
*
- * @see https://appwrite.io/docs/server/databases?sdk=php#databasesDeleteCollection
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#listRows
* @return array
* @throws Exception
*/
-function deleteCollection(): array
+function listRows(): array
{
- global $databases, $databaseId, $collectionId;
+ global $tablesDB, $databaseId, $tableId;
- $response = $databases->deleteCollection($databaseId, $collectionId);
+ $response = $tablesDB->listRows($databaseId, $tableId);
return [
- 'call' => 'api.deleteCollection',
+ 'call' => 'api.listRows',
+ 'response' => $response,
+ ];
+}
+
+/**
+ * Delete table
+ * Delete a table by it's unique id.
+ *
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#deleteTable
+ * @return array
+ * @throws Exception
+ */
+function deleteTable(): array
+{
+ global $tablesDB, $databaseId, $tableId;
+
+ $response = $tablesDB->deleteTable($databaseId, $tableId);
+
+ return [
+ 'call' => 'api.deleteTable',
'response' => $response,
];
}
@@ -191,15 +253,15 @@ function deleteCollection(): array
* Delete Database
* Delete a database by it's unique id.
*
- * @see https://appwrite.io/docs/server/databases?sdk=php#databasesDelete
+ * @see https://appwrite.io/docs/references/cloud/server-php/tablesDB#delete
* @return array
* @throws Exception
*/
function deleteDatabase(): array
{
- global $databases, $databaseId;
+ global $tablesDB, $databaseId;
- $response = $databases->delete($databaseId);
+ $response = $tablesDB->delete($databaseId);
return [
'call' => 'api.deleteDatabase',
@@ -210,7 +272,7 @@ function deleteDatabase(): array
/**
* Create a bucket
*
- * @see https://appwrite.io/docs/server/storage?sdk=php#storageCreateBucket
+ * @see https://appwrite.io/docs/references/cloud/server-php/storage#createBucket
* @return array
* @throws Exception
*/
@@ -230,7 +292,7 @@ function createBucket(): array
fileSecurity: true,
);
- $bucketId = $response['$id'];
+ $bucketId = $response->id;
return [
'call' => 'api.createBucket',
@@ -243,7 +305,7 @@ function createBucket(): array
* The user who creates the file will automatically be assigned to read and write
* access unless he has passed custom values for read and write arguments.
*
- * @see https://appwrite.io/docs/client/storage?sdk=php#storageCreateFile
+ * @see https://appwrite.io/docs/references/cloud/server-php/storage#createFile
* @return array
* @throws Exception
*/
@@ -260,7 +322,7 @@ function createFile(): array
]
);
- $fileId = $response['$id'];
+ $fileId = $response->id;
return [
'call' => 'api.createFile',
@@ -273,7 +335,7 @@ function createFile(): array
* You can use the query params to filter your results. On admin mode,
* this endpoint will return a list of all of the project files.
*
- * @see https://appwrite.io/docs/client/storage?sdk=php#storageListFiles
+ * @see https://appwrite.io/docs/references/cloud/server-php/storage#listFiles
* @return array
* @throws Exception
*/
@@ -293,7 +355,7 @@ function listFiles(): array
* Delete a file by its unique ID.
* Only users with write permissions have access to delete this resource.
*
- * @see https://appwrite.io/docs/client/storage?sdk=php#storageDeleteFile
+ * @see https://appwrite.io/docs/references/cloud/server-php/storage#deleteFile
* @return array
* @throws Exception
*/
@@ -313,7 +375,7 @@ function deleteFile(): array
* Delete a bucket by its unique ID.
* Only users with write permissions have access to delete this resource.
*
- * @see https://appwrite.io/docs/server/storage?sdk=php#storageDeleteBucket
+ * @see https://appwrite.io/docs/references/cloud/server-php/storage#deleteBucket
* @return array
* @throws Exception
*/
@@ -332,7 +394,7 @@ function deleteBucket(): array
/**
* Create a new user.
*
- * @see https://appwrite.io/docs/server/users?sdk=php#usersCreate
+ * @see https://appwrite.io/docs/references/cloud/server-php/users#create
* @return array
* @throws Exception
*/
@@ -358,7 +420,7 @@ function createUser(): array
/**
* Get a list of all the project users.
*
- * @see https://appwrite.io/docs/server/users?sdk=php#usersList
+ * @see https://appwrite.io/docs/references/cloud/server-php/users#list
* @throws Exception
*/
function listUsers(): array
@@ -376,7 +438,7 @@ function listUsers(): array
/**
* Get an account of authenticated user. Works only with JWT
*
- * @see https://appwrite.io/docs/server/account?sdk=php#accountGet
+ * @see https://appwrite.io/docs/references/cloud/server-php/account#get
* @throws Exception
*/
function getAccount(): array
@@ -394,7 +456,7 @@ function getAccount(): array
/**
* Create a function
*
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreate
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#create
* @throws Exception
*/
function createFunction(): array
@@ -404,11 +466,11 @@ function createFunction(): array
$response = $functions->create(
functionId: ID::unique(),
name: 'Test Function',
- runtime: Runtime::PHP80(),
+ runtime: Runtime::PHP84(),
execute: [Role::any()],
);
- $functionId = $response['$id'];
+ $functionId = $response->id;
return [
'call' => 'api.createFunction',
@@ -418,8 +480,8 @@ functionId: ID::unique(),
/**
* Create a deployment
- *
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateDeployment
+ *
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#createDeployment
* @throws Exception
*/
function createDeployment(): array
@@ -445,8 +507,8 @@ functionId: $functionId,
/**
* Create sync execution
- *
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateExecution
+ *
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#createExecution
* @throws Exception
*/
function createSyncExecution(): array
@@ -470,8 +532,8 @@ functionId: $functionId,
/**
* Create async execution
- *
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsCreateExecution
+ *
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#createExecution
* @throws Exception
*/
function createAsyncExecution(): array
@@ -490,7 +552,7 @@ functionId: $functionId,
// wait for 2 seconds to ensure execution is finished
sleep(2);
- $asyncResponse = $functions->getExecution($functionId, $response['$id']);
+ $asyncResponse = $functions->getExecution($functionId, $response->id);
return [
'call' => 'api.createExecution',
@@ -501,7 +563,7 @@ functionId: $functionId,
/**
* List functions
*
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsList
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#list
* @throws Exception
*/
function listFunctions(): array
@@ -519,7 +581,7 @@ function listFunctions(): array
/**
* Delete a function
*
- * @see https://appwrite.io/docs/server/functions?sdk=php#functionsDelete
+ * @see https://appwrite.io/docs/references/cloud/server-php/functions#delete
* @throws Exception
*/
function deleteFunction(): array
@@ -534,44 +596,60 @@ function deleteFunction(): array
];
}
+/**
+ * The order the playground runs its examples in. `tests/smoke.php` drives the
+ * very same list against a stub of the Appwrite API.
+ *
+ * @return array
+ */
+function playgroundMethods(): array
+{
+ return [
+ 'createDatabase',
+ 'createTable',
+ 'listTables',
+ 'addRow',
+ 'listRows',
+ 'deleteTable',
+ 'deleteDatabase',
+ 'createBucket',
+ 'createFile',
+ 'listFiles',
+ 'deleteFile',
+ 'deleteBucket',
+ 'createUser',
+ 'listUsers',
+ 'createFunction',
+ 'createDeployment',
+ 'createSyncExecution',
+ 'createAsyncExecution',
+ 'listFunctions',
+ 'deleteFunction',
+ // 'getAccount' // works only with JWT
+ ];
+}
+
/**
* Execute all functions, collect their return values
* and print everything at the end.
+ *
+ * Defining `PLAYGROUND_SUPPRESS_RUN` before requiring this file loads the
+ * examples without calling them, which is how the tests drive them one by one.
*/
-$ret = [];
-$methods = [
- 'createDatabase',
- 'createCollection',
- 'listCollections',
- 'addDoc',
- 'deleteCollection',
- 'deleteDatabase',
- 'createBucket',
- 'createFile',
- 'listFiles',
- 'deleteFile',
- 'deleteBucket',
- 'createUser',
- 'listUsers',
- 'createFunction',
- 'createDeployment',
- 'createSyncExecution',
- 'createAsyncExecution',
- 'listFunctions',
- 'deleteFunction',
- // 'getAccount' // works only with JWT
-];
-
-foreach ($methods as $method) {
- try {
- if (\function_exists($method)) {
- $ret[] = $method();
+if (!\defined('PLAYGROUND_SUPPRESS_RUN')) {
+ $ret = [];
+
+ foreach (playgroundMethods() as $method) {
+ try {
+ if (\function_exists($method)) {
+ $ret[] = $method();
+ }
+ } catch (Exception $e) {
+ \print_r($e->getMessage());
+ \print_r($e->getTraceAsString());
+ \print_r("");
}
- } catch (Exception $e) {
- \print_r($e->getMessage());
- \print_r($e->getTraceAsString());
- \print_r("");
}
-}
-appwriteDebug($ret);
+ appwriteDebug($ret);
+}
diff --git a/resources/code.tar.gz b/resources/code.tar.gz
index b8d5fb3..eba0023 100644
Binary files a/resources/code.tar.gz and b/resources/code.tar.gz differ
diff --git a/resources/composer.json b/resources/composer.json
index d69714a..db3c125 100644
--- a/resources/composer.json
+++ b/resources/composer.json
@@ -2,7 +2,6 @@
"name": "templates/starter",
"type": "library",
"require": {
- "php": ">=8.0.0",
- "appwrite/appwrite": "^8.0"
+ "php": ">=8.4.0"
}
- }
\ No newline at end of file
+ }
diff --git a/tests/playground-run.php b/tests/playground-run.php
new file mode 100644
index 0000000..abef571
--- /dev/null
+++ b/tests/playground-run.php
@@ -0,0 +1,136 @@
+ ['file', '/dev/null', 'r'],
+ 1 => ['pipe', 'w'],
+ 2 => ['pipe', 'w'],
+ ],
+ $pipes,
+ \dirname(__DIR__),
+ \array_merge(\getenv(), [
+ 'APPWRITE_ENDPOINT' => "http://127.0.0.1:{$stub['port']}/v1",
+ 'APPWRITE_PROJECT_ID' => 'playground',
+ 'APPWRITE_API_KEY' => 'a-test-api-key',
+ 'no_proxy' => '127.0.0.1,localhost',
+ ])
+);
+
+if (!\is_resource($process)) {
+ \fwrite(STDERR, "Could not run the playground.\n");
+
+ exit(1);
+}
+
+$output = (string) \stream_get_contents($pipes[1]);
+$errors = (string) \stream_get_contents($pipes[2]);
+\fclose($pipes[1]);
+\fclose($pipes[2]);
+$status = \proc_close($process);
+
+$requests = stubRequests($stub['requestLog']);
+
+echo "The playground script end to end\n";
+
+test('the script exits successfully', function () use ($status, $errors): void {
+ assertSame(0, $status, "playground.php exited with {$status}, stderr:\n{$errors}");
+ assertSame('', $errors, 'Nothing is written to stderr');
+});
+
+test('no example reports an Appwrite error', function () use ($output): void {
+ foreach (['Server Error', 'has no route', 'Missing required parameter', 'Fatal error'] as $needle) {
+ assertTrue(
+ !\str_contains($output, $needle),
+ "The playground output mentions \"{$needle}\":\n{$output}"
+ );
+ }
+});
+
+test('every example reaches the API', function () use ($requests): void {
+ $trail = \array_map(
+ static fn (array $request): string => "{$request['method']} {$request['path']}",
+ $requests
+ );
+
+ // One request per example, plus the column creations and the two polls the
+ // table and the async execution need.
+ $expected = [
+ 'POST /v1/tablesdb',
+ 'POST /v1/tablesdb/{db}/tables',
+ 'POST /v1/tablesdb/{db}/tables/{table}/columns/string',
+ 'POST /v1/tablesdb/{db}/tables/{table}/columns/integer',
+ 'GET /v1/tablesdb/{db}/tables/{table}/columns',
+ 'GET /v1/tablesdb/{db}/tables',
+ 'POST /v1/tablesdb/{db}/tables/{table}/rows',
+ 'GET /v1/tablesdb/{db}/tables/{table}/rows',
+ 'DELETE /v1/tablesdb/{db}/tables/{table}',
+ 'DELETE /v1/tablesdb/{db}',
+ 'POST /v1/storage/buckets',
+ 'POST /v1/storage/buckets/{bucket}/files',
+ 'GET /v1/storage/buckets/{bucket}/files',
+ 'DELETE /v1/storage/buckets/{bucket}/files/{file}',
+ 'DELETE /v1/storage/buckets/{bucket}',
+ 'POST /v1/users',
+ 'GET /v1/users',
+ 'POST /v1/functions',
+ 'POST /v1/functions/{function}/deployments',
+ 'POST /v1/functions/{function}/executions',
+ 'POST /v1/functions/{function}/executions',
+ 'GET /v1/functions/{function}/executions/execution-1',
+ 'GET /v1/functions',
+ 'DELETE /v1/functions/{function}',
+ ];
+
+ // Ids are generated per run, so compare the shape of each path.
+ $actual = \array_map(
+ static fn (string $entry): string => \preg_replace(
+ [
+ '#/tablesdb/[^/{]+#',
+ '#/tables/(?!{)[^/]+#',
+ '#/buckets/[^/{]+#',
+ '#/files/(?!{)[^/]+#',
+ '#/functions/(?!{)[^/]+#',
+ ],
+ [
+ '/tablesdb/{db}',
+ '/tables/{table}',
+ '/buckets/{bucket}',
+ '/files/{file}',
+ '/functions/{function}',
+ ],
+ $entry
+ ),
+ $trail
+ );
+
+ assertSame($expected, $actual);
+});
+
+test('the output lists the result of every example', function () use ($output): void {
+ assertTrue(
+ \str_contains($output, 'api.createDatabase'),
+ 'The collected responses are printed'
+ );
+ assertTrue(
+ \str_contains($output, 'api.deleteFunction'),
+ 'The sequence runs to the last example'
+ );
+});
+
+exit(results());
diff --git a/tests/prelude.php b/tests/prelude.php
new file mode 100644
index 0000000..25cbf64
--- /dev/null
+++ b/tests/prelude.php
@@ -0,0 +1,65 @@
+ 0, 'failed' => 0];
+
+function test(string $name, callable $case): void
+{
+ try {
+ $case();
+ $GLOBALS['results']['passed']++;
+ echo " ok {$name}\n";
+ } catch (Throwable $e) {
+ $GLOBALS['results']['failed']++;
+ echo " FAIL {$name}\n " . \str_replace("\n", "\n ", $e->getMessage()) . "\n";
+ }
+}
+
+function assertSame(mixed $expected, mixed $actual, string $message = 'Unexpected value'): void
+{
+ if ($expected !== $actual) {
+ throw new RuntimeException(\sprintf(
+ "%s\nexpected: %s\nactual: %s",
+ $message,
+ \var_export($expected, true),
+ \var_export($actual, true)
+ ));
+ }
+}
+
+function assertTrue(bool $condition, string $message = 'Expected condition to hold'): void
+{
+ if (!$condition) {
+ throw new RuntimeException($message);
+ }
+}
+
+function assertInstanceOf(string $expected, mixed $actual, string $message = 'Unexpected type'): void
+{
+ if (!$actual instanceof $expected) {
+ throw new RuntimeException(\sprintf(
+ '%s: expected %s, got %s',
+ $message,
+ $expected,
+ \get_debug_type($actual)
+ ));
+ }
+}
+
+/**
+ * Print the summary and return the exit code the test script should use.
+ */
+function results(): int
+{
+ $passed = $GLOBALS['results']['passed'];
+ $failed = $GLOBALS['results']['failed'];
+
+ echo "\n{$passed} passed, {$failed} failed\n";
+
+ return $failed === 0 ? 0 : 1;
+}
diff --git a/tests/smoke.php b/tests/smoke.php
new file mode 100644
index 0000000..5ffe1df
--- /dev/null
+++ b/tests/smoke.php
@@ -0,0 +1,387 @@
+ 0) {
+ echo "\nStub server log:\n" . (string) \file_get_contents($stub['serverLog']);
+ }
+});
+
+// The playground reads its configuration from the environment.
+\putenv("APPWRITE_ENDPOINT=http://127.0.0.1:{$port}/v1");
+\putenv('APPWRITE_PROJECT_ID=playground');
+\putenv('APPWRITE_API_KEY=a-test-api-key-that-is-long-enough-to-sign-with');
+\putenv('no_proxy=127.0.0.1,localhost');
+
+// Load the examples without running the whole sequence.
+\define('PLAYGROUND_SUPPRESS_RUN', true);
+require \dirname(__DIR__) . '/playground.php';
+
+/**
+ * Every request the stub has seen so far, oldest first.
+ *
+ * @return array>
+ */
+function requests(): array
+{
+ global $logFile;
+
+ return stubRequests($logFile);
+}
+
+/**
+ * The request the stub saw most recently.
+ *
+ * @return array
+ */
+function lastRequest(): array
+{
+ $requests = requests();
+
+ if ($requests === []) {
+ throw new RuntimeException('The stub has not seen any request.');
+ }
+
+ return \end($requests);
+}
+
+/**
+ * The method and path of every request the stub has seen since `$offset`.
+ *
+ * @return array
+ */
+function requestTrail(int $offset = 0): array
+{
+ return \array_map(
+ static fn (array $request): string => "{$request['method']} {$request['path']}",
+ \array_slice(requests(), $offset)
+ );
+}
+
+echo "Playground examples against the Appwrite API stub\n";
+
+test('the endpoint and project come from the environment', function (): void {
+ global $port;
+
+ assertSame("http://127.0.0.1:{$port}/v1", ENDPOINT);
+ assertSame('playground', PROJECT_ID);
+});
+
+test('createDatabase creates a TablesDB database', function (): void {
+ global $databaseId;
+
+ $result = createDatabase();
+
+ assertSame('api.createDatabase', $result['call']);
+ assertInstanceOf(\Appwrite\Models\Database::class, $result['response']);
+ assertSame('Test Database', $result['response']->name);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame('/v1/tablesdb', $request['path']);
+ assertSame('Test Database', $request['json']['name']);
+ assertSame($databaseId, $request['json']['databaseId'], 'The playground keeps the created id');
+ assertSame('playground', $request['project']);
+ assertSame(
+ 'a-test-api-key-that-is-long-enough-to-sign-with',
+ $request['key'],
+ 'The API key is sent as the project key header'
+ );
+});
+
+test('createTable creates the table, then its columns, and waits for them', function (): void {
+ global $databaseId, $tableId;
+
+ $offset = \count(requests());
+ $result = createTable();
+
+ assertInstanceOf(\Appwrite\Models\Table::class, $result['response']);
+ assertSame($databaseId, $result['response']->databaseId);
+
+ assertSame([
+ "POST /v1/tablesdb/{$databaseId}/tables",
+ "POST /v1/tablesdb/{$databaseId}/tables/{$tableId}/columns/string",
+ "POST /v1/tablesdb/{$databaseId}/tables/{$tableId}/columns/integer",
+ "GET /v1/tablesdb/{$databaseId}/tables/{$tableId}/columns",
+ ], requestTrail($offset), 'Columns are created and then awaited');
+
+ $table = requests()[$offset];
+ assertSame('table', $table['json']['name']);
+ assertSame(
+ ['read("any")', 'create("users")', 'update("users")', 'delete("users")'],
+ $table['json']['permissions']
+ );
+
+ $string = requests()[$offset + 1];
+ assertSame('name', $string['json']['key']);
+ assertSame(255, $string['json']['size']);
+ assertSame(true, $string['json']['required']);
+
+ $integer = requests()[$offset + 2];
+ assertSame('release_year', $integer['json']['key']);
+ assertSame(0, $integer['json']['min']);
+ assertSame(9999, $integer['json']['max']);
+});
+
+test('listTables lists the tables of the database', function (): void {
+ global $databaseId;
+
+ $result = listTables();
+
+ assertInstanceOf(\Appwrite\Models\TableList::class, $result['response']);
+ assertSame(1, $result['response']->total);
+ assertInstanceOf(\Appwrite\Models\Table::class, $result['response']->tables[0]);
+
+ $request = lastRequest();
+ assertSame('GET', $request['method']);
+ assertSame("/v1/tablesdb/{$databaseId}/tables", $request['path']);
+});
+
+test('addRow writes a row into the table', function (): void {
+ global $databaseId, $tableId;
+
+ $result = addRow();
+
+ assertSame('api.addRow', $result['call']);
+ assertInstanceOf(\Appwrite\Models\Row::class, $result['response']);
+ assertSame($databaseId, $result['response']->databaseId);
+ assertSame($tableId, $result['response']->tableId);
+ assertSame('Spider Man', $result['response']->data['name']);
+ assertSame(1920, $result['response']->data['release_year']);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame("/v1/tablesdb/{$databaseId}/tables/{$tableId}/rows", $request['path']);
+ assertSame(['name' => 'Spider Man', 'release_year' => 1920], $request['json']['data']);
+ assertSame(
+ ['read("any")', 'update("users")', 'delete("users")'],
+ $request['json']['permissions']
+ );
+});
+
+test('listRows reads the rows back', function (): void {
+ global $databaseId, $tableId;
+
+ $result = listRows();
+
+ assertInstanceOf(\Appwrite\Models\RowList::class, $result['response']);
+ assertSame(1, $result['response']->total);
+ assertSame('Spider Man', $result['response']->rows[0]->data['name']);
+
+ $request = lastRequest();
+ assertSame('GET', $request['method']);
+ assertSame("/v1/tablesdb/{$databaseId}/tables/{$tableId}/rows", $request['path']);
+});
+
+test('deleteTable and deleteDatabase clean up', function (): void {
+ global $databaseId, $tableId;
+
+ $offset = \count(requests());
+
+ assertSame('', deleteTable()['response'], 'A delete answers with no content');
+ assertSame('', deleteDatabase()['response']);
+
+ assertSame([
+ "DELETE /v1/tablesdb/{$databaseId}/tables/{$tableId}",
+ "DELETE /v1/tablesdb/{$databaseId}",
+ ], requestTrail($offset));
+});
+
+test('createBucket creates a bucket with file security', function (): void {
+ global $bucketId;
+
+ $result = createBucket();
+
+ assertInstanceOf(\Appwrite\Models\Bucket::class, $result['response']);
+ assertSame(true, $result['response']->fileSecurity);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame('/v1/storage/buckets', $request['path']);
+ assertSame('test bucket', $request['json']['name']);
+ assertSame(true, $request['json']['fileSecurity']);
+ assertSame($bucketId, $request['json']['bucketId']);
+});
+
+test('createFile uploads test.txt as multipart form data', function (): void {
+ global $bucketId, $fileId;
+
+ $result = createFile();
+
+ assertInstanceOf(\Appwrite\Models\File::class, $result['response']);
+ assertSame('test.txt', $result['response']->name);
+ assertSame($bucketId, $result['response']->bucketId);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame("/v1/storage/buckets/{$bucketId}/files", $request['path']);
+ assertTrue(
+ \str_starts_with((string) $request['contentType'], 'multipart/form-data'),
+ "A file is uploaded as multipart, got {$request['contentType']}"
+ );
+ assertSame('test.txt', $request['files']['file']['name'], 'The upload carries the file');
+ assertSame(\filesize(\dirname(__DIR__) . '/test.txt'), $request['files']['file']['size']);
+ assertSame($fileId, $request['form']['fileId'], 'The upload carries the generated file id');
+});
+
+test('listFiles lists the bucket files', function (): void {
+ global $bucketId;
+
+ $result = listFiles();
+
+ assertInstanceOf(\Appwrite\Models\FileList::class, $result['response']);
+ assertSame(1, $result['response']->total);
+
+ assertSame("/v1/storage/buckets/{$bucketId}/files", lastRequest()['path']);
+});
+
+test('deleteFile and deleteBucket clean up', function (): void {
+ global $bucketId, $fileId;
+
+ $offset = \count(requests());
+
+ assertSame('', deleteFile()['response']);
+ assertSame('', deleteBucket()['response']);
+
+ assertSame([
+ "DELETE /v1/storage/buckets/{$bucketId}/files/{$fileId}",
+ "DELETE /v1/storage/buckets/{$bucketId}",
+ ], requestTrail($offset));
+});
+
+test('createUser creates a user', function (): void {
+ $result = createUser();
+
+ assertInstanceOf(\Appwrite\Models\User::class, $result['response']);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame('/v1/users', $request['path']);
+ assertSame('password', $request['json']['password']);
+ assertTrue(
+ \str_ends_with((string) $request['json']['email'], '@example.com'),
+ 'The generated email keeps the example domain'
+ );
+});
+
+test('listUsers lists the project users', function (): void {
+ $result = listUsers();
+
+ assertInstanceOf(\Appwrite\Models\UserList::class, $result['response']);
+ assertSame(1, $result['response']->total);
+
+ $request = lastRequest();
+ assertSame('GET', $request['method']);
+ assertSame('/v1/users', $request['path']);
+});
+
+test('createFunction asks for a runtime the SDK still offers', function (): void {
+ global $functionId;
+
+ $result = createFunction();
+
+ assertInstanceOf(\Appwrite\Models\FunctionModel::class, $result['response']);
+ assertSame('php-8.4', $result['response']->runtime);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame('/v1/functions', $request['path']);
+ assertSame('php-8.4', $request['json']['runtime'], 'The Runtime enum serializes to its API value');
+ assertSame(['any'], $request['json']['execute']);
+ assertSame($functionId, $request['json']['functionId']);
+});
+
+test('createDeployment uploads the code archive', function (): void {
+ global $functionId;
+
+ $result = createDeployment();
+
+ assertInstanceOf(\Appwrite\Models\Deployment::class, $result['response']);
+ assertSame('src/index.php', $result['response']->entrypoint);
+ assertSame(true, $result['response']->activate);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame("/v1/functions/{$functionId}/deployments", $request['path']);
+ assertSame(
+ 'code.tar.gz',
+ $request['files']['code']['name'],
+ 'The deployment carries the code archive'
+ );
+ assertSame('src/index.php', $request['form']['entrypoint']);
+ assertSame('composer install', $request['form']['commands']);
+ assertSame('1', $request['form']['activate'], 'The deployment is activated');
+});
+
+test('createSyncExecution executes the function and waits for the response', function (): void {
+ global $functionId;
+
+ $result = createSyncExecution();
+
+ assertInstanceOf(\Appwrite\Models\Execution::class, $result['response']);
+ assertSame('Hello, World!', $result['response']->responseBody);
+
+ $request = lastRequest();
+ assertSame('POST', $request['method']);
+ assertSame("/v1/functions/{$functionId}/executions", $request['path']);
+ assertSame(false, $request['json']['async']);
+ assertSame('GET', $request['json']['method'], 'The ExecutionMethod enum serializes to its API value');
+ assertSame('/', $request['json']['path']);
+});
+
+test('createAsyncExecution polls the execution it queued', function (): void {
+ global $functionId;
+
+ $offset = \count(requests());
+ $result = createAsyncExecution();
+
+ assertInstanceOf(\Appwrite\Models\Execution::class, $result['response']);
+ assertSame('execution-1', $result['response']->id);
+
+ assertSame([
+ "POST /v1/functions/{$functionId}/executions",
+ "GET /v1/functions/{$functionId}/executions/execution-1",
+ ], requestTrail($offset));
+
+ assertSame(true, requests()[$offset]['json']['async']);
+});
+
+test('listFunctions and deleteFunction finish the sequence', function (): void {
+ global $functionId;
+
+ $offset = \count(requests());
+
+ $listed = listFunctions();
+ assertInstanceOf(\Appwrite\Models\FunctionList::class, $listed['response']);
+ assertSame(1, $listed['response']->total);
+
+ assertSame('', deleteFunction()['response']);
+
+ assertSame([
+ 'GET /v1/functions',
+ "DELETE /v1/functions/{$functionId}",
+ ], requestTrail($offset));
+});
+
+test('every example the playground runs exists', function (): void {
+ foreach (playgroundMethods() as $method) {
+ assertTrue(\function_exists($method), "playground.php lists an unknown example: {$method}");
+ }
+});
+
+exit(results());
diff --git a/tests/stub-server.php b/tests/stub-server.php
new file mode 100644
index 0000000..0f24a5c
--- /dev/null
+++ b/tests/stub-server.php
@@ -0,0 +1,375 @@
+ [
+ 'name' => $file['name'],
+ 'type' => $file['type'],
+ 'size' => $file['size'],
+ ],
+ $_FILES
+);
+
+$log = \getenv('STUB_LOG');
+if (\is_string($log) && $log !== '') {
+ \file_put_contents(
+ $log,
+ \json_encode([
+ 'method' => $method,
+ 'path' => $path,
+ 'query' => $query,
+ 'contentType' => $contentType,
+ 'json' => $json,
+ 'form' => $form,
+ 'files' => $files,
+ 'project' => $_SERVER['HTTP_X_APPWRITE_PROJECT'] ?? null,
+ 'key' => $_SERVER['HTTP_X_APPWRITE_KEY'] ?? null,
+ 'userAgent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
+ ], JSON_UNESCAPED_SLASHES) . "\n",
+ FILE_APPEND
+ );
+}
+
+const NOW = '2026-11-11T09:00:00.000+00:00';
+
+function respond(array $body, int $status = 200): never
+{
+ \http_response_code($status);
+ \header('content-type: application/json; charset=utf-8');
+ echo \json_encode($body);
+
+ exit;
+}
+
+/**
+ * Appwrite answers a delete with `204 No Content` and no content type, which is
+ * what makes the SDK's `string` return type hold.
+ */
+function respondNoContent(): never
+{
+ \http_response_code(204);
+
+ exit;
+}
+
+function column(string $key, string $type, array $extra = []): array
+{
+ return [
+ 'key' => $key,
+ 'description' => '',
+ 'type' => $type,
+ 'status' => 'available',
+ 'error' => '',
+ 'required' => true,
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ ] + $extra;
+}
+
+function row(string $databaseId, string $tableId, string $rowId, array $data, array $permissions = []): array
+{
+ return [
+ '$id' => $rowId,
+ '$sequence' => '1',
+ '$tableId' => $tableId,
+ '$databaseId' => $databaseId,
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => $permissions,
+ ] + $data;
+}
+
+function execution(string $functionId, string $executionId, array $payload, string $status = 'completed'): array
+{
+ return [
+ '$id' => $executionId,
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => [],
+ 'resourceId' => $functionId,
+ 'resourceType' => 'functions',
+ 'deploymentId' => 'deployment-1',
+ 'trigger' => 'http',
+ 'status' => $status,
+ 'requestMethod' => $payload['method'] ?? 'GET',
+ 'requestPath' => $payload['path'] ?? '/',
+ 'requestHeaders' => [],
+ 'responseStatusCode' => 200,
+ 'responseBody' => $status === 'completed' ? 'Hello, World!' : '',
+ 'responseHeaders' => [],
+ 'logs' => '',
+ 'errors' => '',
+ 'duration' => 0.1,
+ ];
+}
+
+$routes = [
+ // TablesDB
+ ['POST', '#^/v1/tablesdb$#', fn (): never => respond([
+ '$id' => $json['databaseId'] ?? 'database-1',
+ 'name' => $json['name'] ?? '',
+ 'description' => '',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'enabled' => true,
+ 'type' => 'tablesdb',
+ ], 201)],
+ ['GET', '#^/v1/tablesdb/(?P[^/]+)/tables$#', fn (array $m): never => respond([
+ 'total' => 1,
+ 'tables' => [[
+ '$id' => 'table-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => [],
+ 'databaseId' => $m['databaseId'],
+ 'name' => 'table',
+ 'description' => '',
+ 'enabled' => true,
+ 'rowSecurity' => false,
+ 'columns' => [],
+ 'indexes' => [],
+ 'bytesMax' => 0,
+ 'bytesUsed' => 0,
+ ]],
+ ])],
+ ['POST', '#^/v1/tablesdb/(?P[^/]+)/tables$#', fn (array $m): never => respond([
+ '$id' => $json['tableId'] ?? 'table-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => $json['permissions'] ?? [],
+ 'databaseId' => $m['databaseId'],
+ 'name' => $json['name'] ?? '',
+ 'description' => '',
+ 'enabled' => true,
+ 'rowSecurity' => false,
+ 'columns' => [],
+ 'indexes' => [],
+ 'bytesMax' => 65535,
+ 'bytesUsed' => 0,
+ ], 201)],
+ ['POST', '#^/v1/tablesdb/[^/]+/tables/[^/]+/columns/string$#', fn (): never => respond(
+ column($json['key'] ?? '', 'string', ['size' => $json['size'] ?? 0]),
+ 202
+ )],
+ ['POST', '#^/v1/tablesdb/[^/]+/tables/[^/]+/columns/integer$#', fn (): never => respond(
+ column($json['key'] ?? '', 'integer', ['min' => $json['min'] ?? null, 'max' => $json['max'] ?? null]),
+ 202
+ )],
+ ['GET', '#^/v1/tablesdb/[^/]+/tables/[^/]+/columns$#', fn (): never => respond([
+ 'total' => 2,
+ 'columns' => [
+ column('name', 'string', ['size' => 255]),
+ column('release_year', 'integer', ['min' => 0, 'max' => 9999]),
+ ],
+ ])],
+ ['GET', '#^/v1/tablesdb/(?P[^/]+)/tables/(?P[^/]+)/rows$#', fn (array $m): never => respond([
+ 'total' => 1,
+ 'rows' => [row($m['databaseId'], $m['tableId'], 'row-1', [
+ 'name' => 'Spider Man',
+ 'release_year' => 1920,
+ ])],
+ ])],
+ ['POST', '#^/v1/tablesdb/(?P[^/]+)/tables/(?P[^/]+)/rows$#', fn (array $m): never => respond(
+ row(
+ $m['databaseId'],
+ $m['tableId'],
+ $json['rowId'] ?? 'row-1',
+ $json['data'] ?? [],
+ $json['permissions'] ?? []
+ ),
+ 201
+ )],
+ ['DELETE', '#^/v1/tablesdb/[^/]+/tables/[^/]+$#', fn (): never => respondNoContent()],
+ ['DELETE', '#^/v1/tablesdb/[^/]+$#', fn (): never => respondNoContent()],
+
+ // Storage
+ ['POST', '#^/v1/storage/buckets$#', fn (): never => respond([
+ '$id' => $json['bucketId'] ?? 'bucket-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => $json['permissions'] ?? [],
+ 'fileSecurity' => $json['fileSecurity'] ?? false,
+ 'name' => $json['name'] ?? '',
+ 'enabled' => true,
+ 'maximumFileSize' => 30000000,
+ 'allowedFileExtensions' => [],
+ 'compression' => 'gzip',
+ ], 201)],
+ ['GET', '#^/v1/storage/buckets/(?P[^/]+)/files$#', fn (array $m): never => respond([
+ 'total' => 1,
+ 'files' => [[
+ '$id' => 'file-1',
+ 'bucketId' => $m['bucketId'],
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => [],
+ 'name' => 'test.txt',
+ 'signature' => 'd41d8cd98f00b204e9800998ecf8427e',
+ 'mimeType' => 'text/plain',
+ 'sizeOriginal' => 19,
+ 'chunksTotal' => 1,
+ 'chunksUploaded' => 1,
+ ]],
+ ])],
+ ['POST', '#^/v1/storage/buckets/(?P[^/]+)/files$#', fn (array $m): never => respond([
+ '$id' => $form['fileId'] ?? 'file-1',
+ 'bucketId' => $m['bucketId'],
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ '$permissions' => [],
+ 'name' => $files['file']['name'] ?? 'file',
+ 'signature' => 'd41d8cd98f00b204e9800998ecf8427e',
+ 'mimeType' => $files['file']['type'] ?? 'text/plain',
+ 'sizeOriginal' => $files['file']['size'] ?? 0,
+ 'sizeActual' => $files['file']['size'] ?? 0,
+ 'chunksTotal' => 1,
+ 'chunksUploaded' => 1,
+ ], 201)],
+ ['DELETE', '#^/v1/storage/buckets/[^/]+/files/[^/]+$#', fn (): never => respondNoContent()],
+ ['DELETE', '#^/v1/storage/buckets/[^/]+$#', fn (): never => respondNoContent()],
+
+ // Users
+ ['GET', '#^/v1/users$#', fn (): never => respond([
+ 'total' => 1,
+ 'users' => [[
+ '$id' => 'user-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'name' => 'Example',
+ 'email' => 'email@example.com',
+ 'registration' => NOW,
+ 'hash' => 'argon2',
+ 'hashOptions' => [],
+ 'prefs' => [],
+ 'targets' => [],
+ 'mfaRecoveryCodes' => [],
+ ]],
+ ])],
+ ['POST', '#^/v1/users$#', fn (): never => respond([
+ '$id' => $json['userId'] ?? 'user-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'name' => $json['name'] ?? '',
+ 'email' => $json['email'] ?? '',
+ 'registration' => NOW,
+ 'hash' => 'argon2',
+ 'hashOptions' => [],
+ 'prefs' => [],
+ 'targets' => [],
+ 'mfaRecoveryCodes' => [],
+ ], 201)],
+
+ // Functions
+ ['GET', '#^/v1/functions$#', fn (): never => respond([
+ 'total' => 1,
+ 'functions' => [[
+ '$id' => 'function-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'execute' => ['any'],
+ 'name' => 'Test Function',
+ 'runtime' => 'php-8.4',
+ ]],
+ ])],
+ ['POST', '#^/v1/functions$#', fn (): never => respond([
+ '$id' => $json['functionId'] ?? 'function-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'execute' => $json['execute'] ?? [],
+ 'name' => $json['name'] ?? '',
+ 'runtime' => $json['runtime'] ?? '',
+ ], 201)],
+ ['POST', '#^/v1/functions/(?P[^/]+)/deployments$#', fn (array $m): never => respond([
+ '$id' => 'deployment-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'type' => 'manual',
+ 'resourceId' => $m['functionId'],
+ 'resourceType' => 'functions',
+ 'entrypoint' => $form['entrypoint'] ?? '',
+ 'sourceSize' => $files['code']['size'] ?? 0,
+ 'buildSize' => 0,
+ 'totalSize' => $files['code']['size'] ?? 0,
+ 'buildId' => 'build-1',
+ // A multipart body carries booleans as strings.
+ 'activate' => \in_array($form['activate'] ?? '', ['1', 'true'], true),
+ 'screenshotLight' => '',
+ 'screenshotDark' => '',
+ 'status' => 'ready',
+ 'buildLogs' => '',
+ 'buildDuration' => 1,
+ 'providerRepositoryName' => '',
+ 'providerRepositoryOwner' => '',
+ 'providerRepositoryUrl' => '',
+ 'providerCommitHash' => '',
+ 'providerCommitAuthorUrl' => '',
+ 'providerCommitAuthor' => '',
+ 'providerCommitMessage' => '',
+ 'providerCommitUrl' => '',
+ 'providerBranch' => '',
+ 'providerBranchUrl' => '',
+ ], 202)],
+ ['GET', '#^/v1/functions/(?P[^/]+)/executions/(?P[^/]+)$#', fn (array $m): never => respond(
+ execution($m['functionId'], $m['executionId'], [])
+ )],
+ // An async execution is only queued, so its result has to be fetched later.
+ ['POST', '#^/v1/functions/(?P[^/]+)/executions$#', fn (array $m): never => respond(
+ execution(
+ $m['functionId'],
+ 'execution-1',
+ $json ?? [],
+ ($json['async'] ?? false) ? 'processing' : 'completed'
+ ),
+ ($json['async'] ?? false) ? 202 : 201
+ )],
+ ['DELETE', '#^/v1/functions/[^/]+$#', fn (): never => respondNoContent()],
+
+ // Account
+ ['GET', '#^/v1/account$#', fn (): never => respond([
+ '$id' => 'user-1',
+ '$createdAt' => NOW,
+ '$updatedAt' => NOW,
+ 'name' => 'Example',
+ 'email' => 'email@example.com',
+ 'registration' => NOW,
+ 'hash' => 'argon2',
+ 'hashOptions' => [],
+ 'prefs' => [],
+ 'targets' => [],
+ 'mfaRecoveryCodes' => [],
+ ])],
+];
+
+foreach ($routes as [$routeMethod, $pattern, $handler]) {
+ if ($routeMethod === $method && \preg_match($pattern, $path, $matches) === 1) {
+ $handler($matches);
+ }
+}
+
+respond([
+ 'message' => "Stub has no route for {$method} {$path}",
+ 'type' => 'general_route_not_found',
+], 404);
diff --git a/tests/stub.php b/tests/stub.php
new file mode 100644
index 0000000..7824705
--- /dev/null
+++ b/tests/stub.php
@@ -0,0 +1,87 @@
+ ['file', '/dev/null', 'r'],
+ 1 => ['file', $serverLog, 'w'],
+ 2 => ['file', $serverLog, 'a'],
+ ],
+ $pipes,
+ __DIR__,
+ \array_merge(\getenv(), ['STUB_LOG' => $requestLog])
+ );
+
+ if (!\is_resource($server)) {
+ throw new RuntimeException('Could not start the stub server.');
+ }
+
+ \register_shutdown_function(static function () use ($server): void {
+ \proc_terminate($server);
+ \proc_close($server);
+ });
+
+ // Wait for the server to accept connections.
+ $deadline = \microtime(true) + 10;
+ do {
+ $probe = @\fsockopen('127.0.0.1', $port, $errno, $error, 0.2);
+
+ if (\is_resource($probe)) {
+ \fclose($probe);
+
+ return ['port' => $port, 'requestLog' => $requestLog, 'serverLog' => $serverLog];
+ }
+
+ \usleep(50_000);
+ } while (\microtime(true) < $deadline);
+
+ throw new RuntimeException("The stub server never came up on port {$port}.");
+}
+
+/**
+ * Every request the stub has seen so far, oldest first.
+ *
+ * @return array>
+ */
+function stubRequests(string $requestLog): array
+{
+ $lines = \array_filter(\explode("\n", (string) \file_get_contents($requestLog)), '\strlen');
+
+ return \array_map(
+ static fn (string $line): array => \json_decode($line, true),
+ \array_values($lines)
+ );
+}