From bf740e222f1e2c89a80876733be427eec5dfac29 Mon Sep 17 00:00:00 2001 From: Damodar Lohani Date: Tue, 18 Jul 2023 02:58:40 +0000 Subject: [PATCH 001/103] fix validator namespaces --- bin/tasks/index.php | 2 +- bin/tasks/load.php | 4 +- bin/tasks/query.php | 4 +- composer.json | 2 +- composer.lock | 71 ++++++++++++++---------- src/Database/Validator/Authorization.php | 2 +- src/Database/Validator/Datetime.php | 2 +- src/Database/Validator/Index.php | 2 +- src/Database/Validator/Key.php | 2 +- src/Database/Validator/Queries.php | 2 +- src/Database/Validator/Query/Base.php | 2 +- src/Database/Validator/Query/Limit.php | 4 +- src/Database/Validator/Query/Offset.php | 4 +- src/Database/Validator/Roles.php | 2 +- src/Database/Validator/Structure.php | 12 ++-- tests/Database/Base.php | 2 +- tests/Database/Format.php | 6 +- 17 files changed, 68 insertions(+), 57 deletions(-) diff --git a/bin/tasks/index.php b/bin/tasks/index.php index 66c919704..5c965db4d 100644 --- a/bin/tasks/index.php +++ b/bin/tasks/index.php @@ -14,7 +14,7 @@ use Utopia\Database\Database; use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MariaDB; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Text; /** * @Example diff --git a/bin/tasks/load.php b/bin/tasks/load.php index 1a4804290..336da747d 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -22,8 +22,8 @@ use Utopia\Database\Document; use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MariaDB; -use Utopia\Validator\Numeric; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Text; /** * @Example diff --git a/bin/tasks/query.php b/bin/tasks/query.php index ab7115563..5f718e1f9 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -16,8 +16,8 @@ use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MariaDB; use Utopia\Database\Validator\Authorization; -use Utopia\Validator\Numeric; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Text; /** * @Example diff --git a/composer.json b/composer.json index c28e846a0..4c65a6e0a 100755 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "require": { "ext-pdo": "*", "php": ">=8.0", - "utopia-php/framework": "0.*.*", + "utopia-php/framework": "dev-feat-v2 as 0.28.4", "utopia-php/cache": "0.8.*", "utopia-php/mongo": "0.2.*" }, diff --git a/composer.lock b/composer.lock index ce55d7f30..f36a6b8e5 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "edeac562417fec69a2f2c46f44fc6ab4", + "content-hash": "98a0a6c19bafbd73bfc1821f791e0b33", "packages": [ { "name": "composer/package-versions-deprecated", @@ -336,31 +336,33 @@ }, { "name": "utopia-php/framework", - "version": "0.28.4", + "version": "dev-feat-v2", "source": { "type": "git", "url": "https://github.com/utopia-php/framework.git", - "reference": "98c5469efe195aeecc63745dbf8e2f357f8cedac" + "reference": "22bd6d6566b457172fb55ede59d485e2f4600e2c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/framework/zipball/98c5469efe195aeecc63745dbf8e2f357f8cedac", - "reference": "98c5469efe195aeecc63745dbf8e2f357f8cedac", + "url": "https://api.github.com/repos/utopia-php/framework/zipball/22bd6d6566b457172fb55ede59d485e2f4600e2c", + "reference": "22bd6d6566b457172fb55ede59d485e2f4600e2c", "shasum": "" }, "require": { + "ext-swoole": "*", "php": ">=8.0" }, "require-dev": { "laravel/pint": "^1.2", - "phpstan/phpstan": "1.9.x-dev", + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^9.5.25", - "vimeo/psalm": "4.27.0" + "swoole/ide-helper": "4.8.3" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/" + "Utopia\\Http\\": "src/Http" } }, "notification-url": "https://packagist.org/downloads/", @@ -375,9 +377,9 @@ ], "support": { "issues": "https://github.com/utopia-php/framework/issues", - "source": "https://github.com/utopia-php/framework/tree/0.28.4" + "source": "https://github.com/utopia-php/framework/tree/feat-v2" }, - "time": "2023-06-03T14:09:22+00:00" + "time": "2023-07-18T02:39:39+00:00" }, { "name": "utopia-php/mongo", @@ -706,16 +708,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.15.5", + "version": "v4.16.0", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "11e2663a5bc9db5d714eedb4277ee300403b4a9e" + "reference": "19526a33fb561ef417e822e85f08a00db4059c17" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/11e2663a5bc9db5d714eedb4277ee300403b4a9e", - "reference": "11e2663a5bc9db5d714eedb4277ee300403b4a9e", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/19526a33fb561ef417e822e85f08a00db4059c17", + "reference": "19526a33fb561ef417e822e85f08a00db4059c17", "shasum": "" }, "require": { @@ -756,9 +758,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.15.5" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.16.0" }, - "time": "2023-05-19T20:20:00+00:00" + "time": "2023-06-25T14:52:30+00:00" }, { "name": "pcov/clobber", @@ -907,16 +909,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.18", + "version": "1.10.25", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "52b6416c579663eebdd2f1d97df21971daf3b43f" + "reference": "578f4e70d117f9a90699324c555922800ac38d8c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/52b6416c579663eebdd2f1d97df21971daf3b43f", - "reference": "52b6416c579663eebdd2f1d97df21971daf3b43f", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/578f4e70d117f9a90699324c555922800ac38d8c", + "reference": "578f4e70d117f9a90699324c555922800ac38d8c", "shasum": "" }, "require": { @@ -965,7 +967,7 @@ "type": "tidelift" } ], - "time": "2023-06-07T22:00:43+00:00" + "time": "2023-07-06T12:11:37+00:00" }, { "name": "phpunit/php-code-coverage", @@ -1287,16 +1289,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.9", + "version": "9.6.10", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "a9aceaf20a682aeacf28d582654a1670d8826778" + "reference": "a6d351645c3fe5a30f5e86be6577d946af65a328" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a9aceaf20a682aeacf28d582654a1670d8826778", - "reference": "a9aceaf20a682aeacf28d582654a1670d8826778", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a6d351645c3fe5a30f5e86be6577d946af65a328", + "reference": "a6d351645c3fe5a30f5e86be6577d946af65a328", "shasum": "" }, "require": { @@ -1370,7 +1372,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.9" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.10" }, "funding": [ { @@ -1386,7 +1388,7 @@ "type": "tidelift" } ], - "time": "2023-06-11T06:13:56+00:00" + "time": "2023-07-10T04:04:23+00:00" }, { "name": "psr/container", @@ -2664,9 +2666,18 @@ "time": "2022-10-09T10:19:07+00:00" } ], - "aliases": [], + "aliases": [ + { + "package": "utopia-php/framework", + "version": "dev-feat-v2", + "alias": "0.28.4", + "alias_normalized": "0.28.4.0" + } + ], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": { + "utopia-php/framework": 20 + }, "prefer-stable": false, "prefer-lowest": false, "platform": { @@ -2674,5 +2685,5 @@ "php": ">=8.0" }, "platform-dev": [], - "plugin-api-version": "2.2.0" + "plugin-api-version": "2.3.0" } diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 2dd645ba7..f9b7b918b 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Validator; +use Utopia\Http\Validator; class Authorization extends Validator { diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index 702ce50b4..f76ac2139 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Validator; +use Utopia\Http\Validator; class Datetime extends Validator { diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index 07c5b3688..a495eddf8 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -4,7 +4,7 @@ use Utopia\Database\Database; use Utopia\Database\Exception as DatabaseException; -use Utopia\Validator; +use Utopia\Http\Validator; use Utopia\Database\Document; class Index extends Validator diff --git a/src/Database/Validator/Key.php b/src/Database/Validator/Key.php index d1cdf8793..9f393bdfc 100644 --- a/src/Database/Validator/Key.php +++ b/src/Database/Validator/Key.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Validator; +use Utopia\Http\Validator; class Key extends Validator { diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index c80a18366..524941ce8 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -3,7 +3,7 @@ namespace Utopia\Database\Validator; use Utopia\Database\Validator\Query\Base; -use Utopia\Validator; +use Utopia\Http\Validator; use Utopia\Database\Query; class Queries extends Validator diff --git a/src/Database/Validator/Query/Base.php b/src/Database/Validator/Query/Base.php index a37fdd65a..fa96b5a69 100644 --- a/src/Database/Validator/Query/Base.php +++ b/src/Database/Validator/Query/Base.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator\Query; -use Utopia\Validator; +use Utopia\Http\Validator; abstract class Base extends Validator { diff --git a/src/Database/Validator/Query/Limit.php b/src/Database/Validator/Query/Limit.php index facc266d7..affe0bc89 100644 --- a/src/Database/Validator/Query/Limit.php +++ b/src/Database/Validator/Query/Limit.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Validator\Numeric; -use Utopia\Validator\Range; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Range; class Limit extends Base { diff --git a/src/Database/Validator/Query/Offset.php b/src/Database/Validator/Query/Offset.php index 8d59be4d0..6fc7c9564 100644 --- a/src/Database/Validator/Query/Offset.php +++ b/src/Database/Validator/Query/Offset.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Validator\Numeric; -use Utopia\Validator\Range; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Range; class Offset extends Base { diff --git a/src/Database/Validator/Roles.php b/src/Database/Validator/Roles.php index 77ac5d454..f72aa3d65 100644 --- a/src/Database/Validator/Roles.php +++ b/src/Database/Validator/Roles.php @@ -3,7 +3,7 @@ namespace Utopia\Database\Validator; use Utopia\Database\Helpers\Role; -use Utopia\Validator; +use Utopia\Http\Validator; class Roles extends Validator { diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 14223b1a5..4a7534ac7 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -8,11 +8,11 @@ use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Validator; -use Utopia\Validator\Boolean; -use Utopia\Validator\FloatValidator; -use Utopia\Validator\Integer; -use Utopia\Validator\Text; +use Utopia\Http\Validator; +use Utopia\Http\Validator\Boolean; +use Utopia\Http\Validator\FloatValidator; +use Utopia\Http\Validator\Integer; +use Utopia\Http\Validator\Text; class Structure extends Validator { @@ -115,7 +115,7 @@ public static function getFormats(): array * Stores a callback and required params to create Validator * * @param string $name - * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Validator + * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Http\Validator * @param string $type Primitive data type for validation */ public static function addFormat(string $name, Closure $callback, string $type): void diff --git a/tests/Database/Base.php b/tests/Database/Base.php index 403ca424b..2a5d3ab63 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -25,7 +25,7 @@ use Utopia\Database\Validator\Index; use Utopia\Database\Validator\Query\Filter; use Utopia\Database\Validator\Structure; -use Utopia\Validator\Range; +use Utopia\Http\Validator\Range; use Utopia\Database\Exception\Structure as StructureException; abstract class Base extends TestCase diff --git a/tests/Database/Format.php b/tests/Database/Format.php index 5f5d40a1c..389324283 100644 --- a/tests/Database/Format.php +++ b/tests/Database/Format.php @@ -2,15 +2,15 @@ namespace Utopia\Tests; -use Utopia\Validator; -use Utopia\Validator\Text; +use Utopia\Http\Validator; +use Utopia\Http\Validator\Text; /** * Format Test for Email * * Validate that an variable is a valid email address * - * @package Utopia\Validator + * @package Utopia\Http\Validator */ class Format extends Text { From 3bf21fdee4d4983c0b241ca14e02b07eed9f671e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 4 Oct 2023 11:38:48 +0000 Subject: [PATCH 002/103] Switch v2 branch --- composer.json | 2 +- composer.lock | 97 ++++++++++++++++++++++++++------------------------- 2 files changed, 50 insertions(+), 49 deletions(-) diff --git a/composer.json b/composer.json index 4c65a6e0a..d08678c57 100755 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "require": { "ext-pdo": "*", "php": ">=8.0", - "utopia-php/framework": "dev-feat-v2 as 0.28.4", + "utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0", "utopia-php/cache": "0.8.*", "utopia-php/mongo": "0.2.*" }, diff --git a/composer.lock b/composer.lock index f36a6b8e5..8711a3041 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "98a0a6c19bafbd73bfc1821f791e0b33", + "content-hash": "6409a4a403e59db3dfbc2eb7ab251bc0", "packages": [ { "name": "composer/package-versions-deprecated", @@ -204,16 +204,16 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.27.0", + "version": "v1.28.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936" + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", - "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", "shasum": "" }, "require": { @@ -222,7 +222,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "1.27-dev" + "dev-main": "1.28-dev" }, "thanks": { "name": "symfony/polyfill", @@ -267,7 +267,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.27.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" }, "funding": [ { @@ -283,7 +283,7 @@ "type": "tidelift" } ], - "time": "2022-11-03T14:55:06+00:00" + "time": "2023-01-26T09:26:14+00:00" }, { "name": "utopia-php/cache", @@ -336,16 +336,16 @@ }, { "name": "utopia-php/framework", - "version": "dev-feat-v2", + "version": "dev-fix-v2-swoole-coroutines", "source": { "type": "git", "url": "https://github.com/utopia-php/framework.git", - "reference": "22bd6d6566b457172fb55ede59d485e2f4600e2c" + "reference": "c9ea90ea4326852ec530c0f17912c78cd2fceebf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/framework/zipball/22bd6d6566b457172fb55ede59d485e2f4600e2c", - "reference": "22bd6d6566b457172fb55ede59d485e2f4600e2c", + "url": "https://api.github.com/repos/utopia-php/framework/zipball/c9ea90ea4326852ec530c0f17912c78cd2fceebf", + "reference": "c9ea90ea4326852ec530c0f17912c78cd2fceebf", "shasum": "" }, "require": { @@ -377,9 +377,9 @@ ], "support": { "issues": "https://github.com/utopia-php/framework/issues", - "source": "https://github.com/utopia-php/framework/tree/feat-v2" + "source": "https://github.com/utopia-php/framework/tree/fix-v2-swoole-coroutines" }, - "time": "2023-07-18T02:39:39+00:00" + "time": "2023-10-03T12:56:31+00:00" }, { "name": "utopia-php/mongo", @@ -708,16 +708,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.16.0", + "version": "v4.17.1", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "19526a33fb561ef417e822e85f08a00db4059c17" + "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/19526a33fb561ef417e822e85f08a00db4059c17", - "reference": "19526a33fb561ef417e822e85f08a00db4059c17", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", + "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", "shasum": "" }, "require": { @@ -758,9 +758,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.16.0" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.17.1" }, - "time": "2023-06-25T14:52:30+00:00" + "time": "2023-08-13T19:53:39+00:00" }, { "name": "pcov/clobber", @@ -909,16 +909,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.25", + "version": "1.10.37", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "578f4e70d117f9a90699324c555922800ac38d8c" + "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/578f4e70d117f9a90699324c555922800ac38d8c", - "reference": "578f4e70d117f9a90699324c555922800ac38d8c", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/058ba07e92f744d4dcf6061ae75283d0c6456f2e", + "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e", "shasum": "" }, "require": { @@ -967,20 +967,20 @@ "type": "tidelift" } ], - "time": "2023-07-06T12:11:37+00:00" + "time": "2023-10-02T16:18:37+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "9.2.26", + "version": "9.2.29", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "443bc6912c9bd5b409254a40f4b0f4ced7c80ea1" + "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/443bc6912c9bd5b409254a40f4b0f4ced7c80ea1", - "reference": "443bc6912c9bd5b409254a40f4b0f4ced7c80ea1", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6a3a87ac2bbe33b25042753df8195ba4aa534c76", + "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76", "shasum": "" }, "require": { @@ -1036,7 +1036,8 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.26" + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.29" }, "funding": [ { @@ -1044,7 +1045,7 @@ "type": "github" } ], - "time": "2023-03-06T12:58:08+00:00" + "time": "2023-09-19T04:57:46+00:00" }, { "name": "phpunit/php-file-iterator", @@ -1289,16 +1290,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.10", + "version": "9.6.13", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "a6d351645c3fe5a30f5e86be6577d946af65a328" + "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a6d351645c3fe5a30f5e86be6577d946af65a328", - "reference": "a6d351645c3fe5a30f5e86be6577d946af65a328", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f3d767f7f9e191eab4189abe41ab37797e30b1be", + "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be", "shasum": "" }, "require": { @@ -1313,7 +1314,7 @@ "phar-io/manifest": "^2.0.3", "phar-io/version": "^3.0.2", "php": ">=7.3", - "phpunit/php-code-coverage": "^9.2.13", + "phpunit/php-code-coverage": "^9.2.28", "phpunit/php-file-iterator": "^3.0.5", "phpunit/php-invoker": "^3.1.1", "phpunit/php-text-template": "^2.0.3", @@ -1372,7 +1373,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.10" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.13" }, "funding": [ { @@ -1388,7 +1389,7 @@ "type": "tidelift" } ], - "time": "2023-07-10T04:04:23+00:00" + "time": "2023-09-19T05:39:22+00:00" }, { "name": "psr/container", @@ -1995,16 +1996,16 @@ }, { "name": "sebastian/global-state", - "version": "5.0.5", + "version": "5.0.6", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "0ca8db5a5fc9c8646244e629625ac486fa286bf2" + "reference": "bde739e7565280bda77be70044ac1047bc007e34" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/0ca8db5a5fc9c8646244e629625ac486fa286bf2", - "reference": "0ca8db5a5fc9c8646244e629625ac486fa286bf2", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bde739e7565280bda77be70044ac1047bc007e34", + "reference": "bde739e7565280bda77be70044ac1047bc007e34", "shasum": "" }, "require": { @@ -2047,7 +2048,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/global-state/issues", - "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.5" + "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.6" }, "funding": [ { @@ -2055,7 +2056,7 @@ "type": "github" } ], - "time": "2022-02-14T08:28:10+00:00" + "time": "2023-08-02T09:26:13+00:00" }, { "name": "sebastian/lines-of-code", @@ -2669,9 +2670,9 @@ "aliases": [ { "package": "utopia-php/framework", - "version": "dev-feat-v2", - "alias": "0.28.4", - "alias_normalized": "0.28.4.0" + "version": "dev-fix-v2-swoole-coroutines", + "alias": "0.31.0", + "alias_normalized": "0.31.0.0" } ], "minimum-stability": "stable", @@ -2685,5 +2686,5 @@ "php": ">=8.0" }, "platform-dev": [], - "plugin-api-version": "2.3.0" + "plugin-api-version": "2.6.0" } From 1d4ab3dfafbe7a3adfd167e5e288c19634c223ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 5 Oct 2023 09:43:50 +0000 Subject: [PATCH 003/103] Fix lockfile after merge --- composer.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.lock b/composer.lock index dbfdea8e2..b9555f4af 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6409a4a403e59db3dfbc2eb7ab251bc0", + "content-hash": "b01ce402808990664d677e2754c65578", "packages": [ { "name": "jean85/pretty-package-versions", @@ -272,12 +272,12 @@ "source": { "type": "git", "url": "https://github.com/utopia-php/framework.git", - "reference": "c9ea90ea4326852ec530c0f17912c78cd2fceebf" + "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/framework/zipball/c9ea90ea4326852ec530c0f17912c78cd2fceebf", - "reference": "c9ea90ea4326852ec530c0f17912c78cd2fceebf", + "url": "https://api.github.com/repos/utopia-php/framework/zipball/e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", + "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", "shasum": "" }, "require": { @@ -311,7 +311,7 @@ "issues": "https://github.com/utopia-php/framework/issues", "source": "https://github.com/utopia-php/framework/tree/fix-v2-swoole-coroutines" }, - "time": "2023-10-03T12:56:31+00:00" + "time": "2023-10-04T11:53:40+00:00" }, { "name": "utopia-php/mongo", From 41134cc926543839799be0bd3f91ff1d18de8bf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 19 Oct 2023 14:19:16 +0200 Subject: [PATCH 004/103] Make authorization per-instance --- composer.lock | 20 +- src/Database/Adapter.php | 18 ++ src/Database/Adapter/MariaDB.php | 13 +- src/Database/Adapter/Mongo.php | 12 +- src/Database/Adapter/Postgres.php | 14 +- src/Database/Database.php | 62 +++--- src/Database/Validator/Authorization.php | 73 ++++--- tests/Database/Base.php | 196 +++++++++--------- .../Database/Validator/AuthorizationTest.php | 68 +++--- 9 files changed, 263 insertions(+), 213 deletions(-) diff --git a/composer.lock b/composer.lock index b9555f4af..569814fb4 100644 --- a/composer.lock +++ b/composer.lock @@ -272,12 +272,12 @@ "source": { "type": "git", "url": "https://github.com/utopia-php/framework.git", - "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef" + "reference": "7405c1fea69443c9034c2f6494a7cbd2d6e6813f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/framework/zipball/e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", - "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", + "url": "https://api.github.com/repos/utopia-php/framework/zipball/7405c1fea69443c9034c2f6494a7cbd2d6e6813f", + "reference": "7405c1fea69443c9034c2f6494a7cbd2d6e6813f", "shasum": "" }, "require": { @@ -311,7 +311,7 @@ "issues": "https://github.com/utopia-php/framework/issues", "source": "https://github.com/utopia-php/framework/tree/fix-v2-swoole-coroutines" }, - "time": "2023-10-04T11:53:40+00:00" + "time": "2023-10-17T11:16:05+00:00" }, { "name": "utopia-php/mongo", @@ -841,16 +841,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.37", + "version": "1.10.39", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e" + "reference": "d9dedb0413f678b4d03cbc2279a48f91592c97c4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/058ba07e92f744d4dcf6061ae75283d0c6456f2e", - "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/d9dedb0413f678b4d03cbc2279a48f91592c97c4", + "reference": "d9dedb0413f678b4d03cbc2279a48f91592c97c4", "shasum": "" }, "require": { @@ -899,7 +899,7 @@ "type": "tidelift" } ], - "time": "2023-10-02T16:18:37+00:00" + "time": "2023-10-17T15:46:26+00:00" }, { "name": "phpunit/php-code-coverage", @@ -2619,5 +2619,5 @@ "php": ">=8.0" }, "platform-dev": [], - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.3.0" } diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index decfd7db4..146c4f81b 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -4,6 +4,7 @@ use Exception; use Utopia\Database\Exception as DatabaseException; +use Utopia\Database\Validator\Authorization; abstract class Adapter { @@ -24,6 +25,23 @@ abstract class Adapter protected static ?int $timeout = null; + /** + * @var Authorization + */ + protected Authorization $authorization; + + /** + * @param Authorization $authorization + * + * @return $this + */ + public function setAuthorization(Authorization $authorization): self + { + $this->authorization = $authorization; + + return $this; + } + /** * @param string $key * @param mixed $value diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index d4647f754..07aaa0baa 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -11,7 +11,6 @@ use Utopia\Database\Exception\Duplicate; use Utopia\Database\Exception\Timeout; use Utopia\Database\Query; -use Utopia\Database\Validator\Authorization; class MariaDB extends SQL { @@ -953,7 +952,7 @@ public function deleteDocument(string $collection, string $id): bool public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, ?int $timeout = null): array { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $orders = []; @@ -1039,7 +1038,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1144,7 +1143,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null, ?int $timeout = null): int { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1152,7 +1151,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, $where[] = $this->getSQLCondition($query); } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1200,7 +1199,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null, ?int $timeout = null): int|float { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1208,7 +1207,7 @@ public function sum(string $collection, string $attribute, array $queries = [], $where[] = $this->getSQLCondition($query); } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index df827a405..d788efb3e 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -825,8 +825,8 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, $filters = $this->buildFilters($queries); // permissions - if (Authorization::$status) { // skip if authorization is disabled - $roles = \implode('|', Authorization::getRoles()); + if ($this->authorization->status) { // skip if authorization is disabled + $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1096,8 +1096,8 @@ public function count(string $collection, array $queries = [], ?int $max = null, $filters = $this->buildFilters($queries); // permissions - if (Authorization::$status) { // skip if authorization is disabled - $roles = \implode('|', Authorization::getRoles()); + if ($this->authorization->status) { // skip if authorization is disabled + $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1129,8 +1129,8 @@ public function sum(string $collection, string $attribute, array $queries = [], $filters = $this->buildFilters($queries); // permissions - if (Authorization::$status) { // skip if authorization is disabled - $roles = \implode('|', Authorization::getRoles()); + if ($this->authorization->status) { // skip if authorization is disabled + $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8df026bda..7cab7fc52 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -966,7 +966,7 @@ public function deleteDocument(string $collection, string $id): bool public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, ?int $timeout = null): array { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $orders = []; @@ -1046,7 +1046,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1151,7 +1151,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null, ?int $timeout = null): int { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1159,7 +1159,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, $where[] = $this->getSQLCondition($query); } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1209,17 +1209,17 @@ public function count(string $collection, array $queries = [], ?int $max = null, public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null, ?int $timeout = null): int|float { $name = $this->filter($collection); - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; - $permissions = (Authorization::$status) ? $this->getSQLPermissionsCondition($collection, $roles) : '1=1'; // Disable join when no authorization required + $permissions = ($this->authorization->status) ? $this->getSQLPermissionsCondition($collection, $roles) : '1=1'; // Disable join when no authorization required foreach ($queries as $query) { $where[] = $this->getSQLCondition($query); } - if (Authorization::$status) { + if ($this->authorization->status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } diff --git a/src/Database/Database.php b/src/Database/Database.php index 8292bf6bf..dc500b9f0 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -306,13 +306,25 @@ class Database */ private array $relationshipDeleteStack = []; + /** + * @var Authorization + */ + private Authorization $authorization; + /** * @param Adapter $adapter * @param Cache $cache * @param array $filters */ - public function __construct(Adapter $adapter, Cache $cache, array $filters = []) + public function __construct(Adapter $adapter, Cache $cache, array $filters = [], Authorization $authorization = null) { + if (\is_null($authorization)) { + $authorization = new Authorization(); + } + + $adapter->setAuthorization($authorization); + + $this->authorization = $authorization; $this->adapter = $adapter; $this->cache = $cache; $this->instanceFilters = $filters; @@ -791,14 +803,14 @@ public function getCollection(string $id): Document */ public function listCollections(int $limit = 25, int $offset = 0): array { - Authorization::disable(); + $this->authorization->disable(); $result = $this->silent(fn () => $this->find(self::METADATA, [ Query::limit($limit), Query::offset($offset) ])); - Authorization::reset(); + $this->authorization->reset(); $this->trigger(self::EVENT_COLLECTION_LIST, $result); @@ -2235,7 +2247,7 @@ public function getDocument(string $collection, string $id, array $queries = []) $queries = \array_values($queries); - $validator = new Authorization(self::PERMISSION_READ); + $validator = $this->authorization->setAction(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); $cacheKey = 'cache-' . $this->getNamespace() . ':' . $collection->getId() . ':' . $id; @@ -2593,7 +2605,7 @@ public function createDocument(string $collection, Document $document): Document $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { - $authorization = new Authorization(self::PERMISSION_CREATE); + $authorization = $this->authorization->setAction(self::PERMISSION_CREATE); if (!$authorization->isValid($collection->getCreate())) { throw new AuthorizationException($authorization->getDescription()); } @@ -2932,7 +2944,7 @@ public function updateDocument(string $collection, string $id, Document $documen } $time = DateTime::now(); - $old = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $old = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $document = \array_merge($old->getArrayCopy(), $document->getArrayCopy()); $document['$collection'] = $old->getAttribute('$collection'); // Make sure user doesn't switch collectionID $document['$createdAt'] = $old->getCreatedAt(); // Make sure user doesn't switch createdAt @@ -2943,7 +2955,7 @@ public function updateDocument(string $collection, string $id, Document $documen return $attribute['type'] === Database::VAR_RELATIONSHIP; }); - $validator = new Authorization(self::PERMISSION_UPDATE); + $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); $shouldUpdate = false; if ($collection->getId() !== self::METADATA) { @@ -3265,12 +3277,12 @@ private function updateDocumentRelationships(Document $collection, Document $old $removedDocuments = \array_diff($oldIds, $newIds); foreach ($removedDocuments as $relation) { - $relation = Authorization::skip(fn () => $this->skipRelationships(fn () => $this->getDocument( + $relation = $this->authorization->skip(fn () => $this->skipRelationships(fn () => $this->getDocument( $relatedCollection->getId(), $relation ))); - Authorization::skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( + $this->authorization->skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation->getId(), $relation->setAttribute($twoWayKey, null) @@ -3388,7 +3400,7 @@ private function updateDocumentRelationships(Document $collection, Document $old ]); foreach ($junctions as $junction) { - Authorization::skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); + $this->authorization->skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); } } @@ -3476,9 +3488,9 @@ public function increaseDocumentAttribute(string $collection, string $id, string throw new DatabaseException('Value must be numeric and greater than 0'); } - $validator = new Authorization(self::PERMISSION_UPDATE); + $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); - $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); @@ -3543,9 +3555,9 @@ public function decreaseDocumentAttribute(string $collection, string $id, string throw new DatabaseException('Value must be numeric and greater than 0'); } - $validator = new Authorization(self::PERMISSION_UPDATE); + $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); - $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); @@ -3605,10 +3617,10 @@ public function decreaseDocumentAttribute(string $collection, string $id, string */ public function deleteDocument(string $collection, string $id): bool { - $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); - $validator = new Authorization(self::PERMISSION_DELETE); + $validator = $this->authorization->setAction(self::PERMISSION_DELETE); if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); @@ -3776,7 +3788,7 @@ private function deleteRestrict( && $side === Database::RELATION_SIDE_CHILD && !$twoWay ) { - Authorization::skip(function () use ($document, $relatedCollection, $twoWayKey) { + $this->authorization->skip(function () use ($document, $relatedCollection, $twoWayKey) { $related = $this->findOne($relatedCollection->getId(), [ Query::equal($twoWayKey, [$document->getId()]) ]); @@ -3798,7 +3810,7 @@ private function deleteRestrict( $relationType === Database::RELATION_MANY_TO_ONE && $side === Database::RELATION_SIDE_CHILD ) { - $related = Authorization::skip(fn () => $this->findOne($relatedCollection->getId(), [ + $related = $this->authorization->skip(fn () => $this->findOne($relatedCollection->getId(), [ Query::equal($twoWayKey, [$document->getId()]) ])); @@ -3833,7 +3845,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } // Shouldn't need read or update permission to delete - Authorization::skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { + $this->authorization->skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { if (!$twoWay && $side === Database::RELATION_SIDE_CHILD) { $related = $this->findOne($relatedCollection->getId(), [ Query::equal($twoWayKey, [$document->getId()]) @@ -3858,7 +3870,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection break; } foreach ($value as $relation) { - Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { + $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { $related = $this->getDocument($relatedCollection->getId(), $relation->getId()); $this->skipRelationships(fn () => $this->updateDocument( @@ -3882,7 +3894,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } foreach ($value as $relation) { - Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { + $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { $related = $this->getDocument($relatedCollection->getId(), $relation->getId()); $this->skipRelationships(fn () => $this->updateDocument( @@ -4069,7 +4081,7 @@ public function find(string $collection, array $queries = [], ?int $timeout = nu throw new QueryException($validator->getDescription()); } - $authorization = new Authorization(self::PERMISSION_READ); + $authorization = $this->authorization->setAction(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); $skipAuth = $authorization->isValid($collection->getRead()); @@ -4161,7 +4173,7 @@ public function find(string $collection, array $queries = [], ?int $timeout = nu $timeout ); - $results = $skipAuth ? Authorization::skip($getResults) : $getResults(); + $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { @@ -4241,7 +4253,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) throw new QueryException($validator->getDescription()); } - $authorization = new Authorization(self::PERMISSION_READ); + $authorization = $this->authorization->setAction(self::PERMISSION_READ); if ($authorization->isValid($collection->getRead())) { $skipAuth = true; } @@ -4250,7 +4262,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = self::convertQueries($collection, $queries); $getCount = fn () => $this->adapter->count($collection->getId(), $queries, $max); - $count = $skipAuth ?? false ? Authorization::skip($getCount) : $getCount(); + $count = $skipAuth ?? false ? $this->authorization->skip($getCount) : $getCount(); $this->trigger(self::EVENT_DOCUMENT_COUNT, $count); diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index f9b7b918b..c38c74539 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -9,7 +9,7 @@ class Authorization extends Validator /** * @var array */ - private static array $roles = [ + private array $roles = [ 'any' => true ]; @@ -26,11 +26,22 @@ class Authorization extends Validator /** * @param string $action */ - public function __construct(string $action) + public function __construct(string $action = '') { $this->action = $action; } + /** + * @param string $action + * @return self + */ + public function setAction(string $action): self + { + $this->action = $action; + + return $this; + } + /** * Get Description. * @@ -54,7 +65,7 @@ public function getDescription(): string */ public function isValid($permissions): bool { - if (!self::$status) { + if (!$this->status) { return true; } @@ -66,12 +77,12 @@ public function isValid($permissions): bool $permission = '-'; foreach ($permissions as $permission) { - if (\array_key_exists($permission, self::$roles)) { + if (\array_key_exists($permission, $this->roles)) { return true; } } - $this->message = 'Missing "'.$this->action.'" permission for role "'.$permission.'". Only "'.\json_encode(self::getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + $this->message = 'Missing "'.$this->action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; return false; } @@ -80,9 +91,9 @@ public function isValid($permissions): bool * @param string $role * @return void */ - public static function setRole(string $role): void + public function setRole(string $role): void { - self::$roles[$role] = true; + $this->roles[$role] = true; } /** @@ -90,25 +101,25 @@ public static function setRole(string $role): void * * @return void */ - public static function unsetRole(string $role): void + public function unsetRole(string $role): void { - unset(self::$roles[$role]); + unset($this->roles[$role]); } /** * @return array */ - public static function getRoles(): array + public function getRoles(): array { - return \array_keys(self::$roles); + return \array_keys($this->roles); } /** * @return void */ - public static function cleanRoles(): void + public function cleanRoles(): void { - self::$roles = []; + $this->roles = []; } /** @@ -116,15 +127,15 @@ public static function cleanRoles(): void * * @return bool */ - public static function isRole(string $role): bool + public function isRole(string $role): bool { - return (\array_key_exists($role, self::$roles)); + return (\array_key_exists($role, $this->roles)); } /** * @var bool */ - public static bool $status = true; + public bool $status = true; /** * Default value in case we need @@ -132,20 +143,20 @@ public static function isRole(string $role): bool * * @var bool */ - public static bool $statusDefault = true; + public bool $statusDefault = true; /** * Change default status. * This will be used for the - * value set on the self::reset() method + * value set on the $this->reset() method * * @param bool $status * @return void */ - public static function setDefaultStatus(bool $status): void + public function setDefaultStatus(bool $status): void { - self::$statusDefault = $status; - self::$status = $status; + $this->statusDefault = $status; + $this->status = $status; } /** @@ -157,15 +168,15 @@ public static function setDefaultStatus(bool $status): void * @param callable(): T $callback * @return T */ - public static function skip(callable $callback): mixed + public function skip(callable $callback): mixed { - $initialStatus = self::$status; - self::disable(); + $initialStatus = $this->status; + $this->disable(); try { return $callback(); } finally { - self::$status = $initialStatus; + $this->status = $initialStatus; } } @@ -174,9 +185,9 @@ public static function skip(callable $callback): mixed * * @return void */ - public static function enable(): void + public function enable(): void { - self::$status = true; + $this->status = true; } /** @@ -184,9 +195,9 @@ public static function enable(): void * * @return void */ - public static function disable(): void + public function disable(): void { - self::$status = false; + $this->status = false; } /** @@ -194,9 +205,9 @@ public static function disable(): void * * @return void */ - public static function reset(): void + public function reset(): void { - self::$status = self::$statusDefault; + $this->status = $this->statusDefault; } /** diff --git a/tests/Database/Base.php b/tests/Database/Base.php index 76da3a51e..75be1c0ae 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -29,6 +29,11 @@ abstract class Base extends TestCase { + /** + * @var Authorization + */ + private Authorization $authorization; + /** * @return Database */ @@ -41,12 +46,13 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - Authorization::setRole('any'); + $this->authorization = new Authorization(); + $this->authorization->setRole('any'); } public function tearDown(): void { - Authorization::setDefaultStatus(true); + $this->authorization->setDefaultStatus(true); } protected string $testDatabase = 'utopiaTests'; @@ -1482,7 +1488,7 @@ public function testDeleteDocument(Document $document): void */ public function testFind(): array { - Authorization::setRole(Role::any()->toString()); + $this->authorization->setRole(Role::any()->toString()); static::getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) @@ -1716,7 +1722,7 @@ public function testFindCheckPermissions(): void /** * Check Permissions */ - Authorization::setRole('user:x'); + $this->authorization->setRole('user:x'); $documents = static::getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); @@ -2964,30 +2970,30 @@ public function testCount(): void $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); - Authorization::unsetRole('user:x'); + $this->authorization->unsetRole('user:x'); $count = static::getDatabase()->count('movies'); $this->assertEquals(5, $count); - Authorization::disable(); + $this->authorization->disable(); $count = static::getDatabase()->count('movies'); $this->assertEquals(6, $count); - Authorization::reset(); + $this->authorization->reset(); - Authorization::disable(); + $this->authorization->disable(); $count = static::getDatabase()->count('movies', [], 3); $this->assertEquals(3, $count); - Authorization::reset(); + $this->authorization->reset(); /** * Test that OR queries are handled correctly */ - Authorization::disable(); + $this->authorization->disable(); $count = static::getDatabase()->count('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); $this->assertEquals(1, $count); - Authorization::reset(); + $this->authorization->reset(); } /** @@ -2995,7 +3001,7 @@ public function testCount(): void */ public function testSum(): void { - Authorization::setRole('user:x'); + $this->authorization->setRole('user:x'); $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = static::getDatabase()->sum('movies', 'year'); @@ -3008,8 +3014,8 @@ public function testSum(): void $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); - Authorization::unsetRole('user:x'); - Authorization::unsetRole('userx'); + $this->authorization->unsetRole('user:x'); + $this->authorization->unsetRole('userx'); $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = static::getDatabase()->sum('movies', 'year'); @@ -3269,8 +3275,8 @@ public function testEncodeDecode(): void */ public function testReadPermissionsSuccess(Document $document): Document { - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3289,20 +3295,20 @@ public function testReadPermissionsSuccess(Document $document): Document $this->assertEquals(false, $document->isEmpty()); - Authorization::cleanRoles(); + $this->authorization->cleanRoles(); $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - Authorization::setRole(Role::any()->toString()); + $this->authorization->setRole(Role::any()->toString()); return $document; } public function testReadPermissionsFailure(): Document { - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3319,13 +3325,13 @@ public function testReadPermissionsFailure(): Document 'colors' => ['pink', 'green', 'blue'], ])); - Authorization::cleanRoles(); + $this->authorization->cleanRoles(); $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - Authorization::setRole(Role::any()->toString()); + $this->authorization->setRole(Role::any()->toString()); return $document; } @@ -3335,7 +3341,7 @@ public function testReadPermissionsFailure(): Document */ public function testWritePermissionsSuccess(Document $document): void { - Authorization::cleanRoles(); + $this->authorization->cleanRoles(); $this->expectException(AuthorizationException::class); static::getDatabase()->createDocument('documents', new Document([ @@ -3361,8 +3367,8 @@ public function testWritePermissionsUpdateFailure(Document $document): Document { $this->expectException(AuthorizationException::class); - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3379,7 +3385,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document 'colors' => ['pink', 'green', 'blue'], ])); - Authorization::cleanRoles(); + $this->authorization->cleanRoles(); $document = static::getDatabase()->updateDocument('documents', $document->getId(), new Document([ '$id' => ID::custom($document->getId()), @@ -3796,7 +3802,7 @@ public function testUniqueIndexDuplicate(): void */ public function testUniqueIndexDuplicateUpdate(): void { - Authorization::setRole(Role::users()->toString()); + $this->authorization->setRole(Role::users()->toString()); // create document then update to conflict with index $document = static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ @@ -4453,7 +4459,7 @@ public function testKeywords(): void public function testWritePermissions(): void { - Authorization::setRole(Role::any()->toString()); + $this->authorization->setRole(Role::any()->toString()); $database = static::getDatabase(); $database->createCollection('animals', permissions: [ @@ -4519,7 +4525,7 @@ public function testWritePermissions(): void $newCat = $cat->setAttribute('type', 'newCat'); $database->updateDocument('animals', 'cat', $newCat); - $docs = Authorization::skip(fn () => $database->find('animals')); + $docs = $this->authorization->skip(fn () => $database->find('animals')); $this->assertCount(1, $docs); $this->assertEquals('cat', $docs[0]['$id']); $this->assertEquals('newCat', $docs[0]['type']); @@ -9970,8 +9976,8 @@ public function testEnforceRelationshipPermissions(): void $this->expectNotToPerformAssertions(); return; } - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); @@ -10048,7 +10054,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - Authorization::setRole(Role::user('user1')->toString()); + $this->authorization->setRole(Role::user('user1')->toString()); $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); @@ -10061,7 +10067,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Bird 1 Updated', $bird1['name']); - Authorization::setRole(Role::user('user2')->toString()); + $this->authorization->setRole(Role::user('user2')->toString()); // Try delete multi-level nested document $deleted = static::getDatabase()->deleteDocument( @@ -11335,8 +11341,8 @@ public function testCollectionPermissionsExceptions(): void */ public function testCollectionPermissionsCreateWorks(Document $collection): array { - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -11358,8 +11364,8 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra */ public function testCollectionPermissionsCreateThrowsException(Document $collection): void { - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); static::getDatabase()->createDocument($collection->getId(), new Document([ @@ -11382,8 +11388,8 @@ public function testCollectionPermissionsGetWorks(array $data): array { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $document = static::getDatabase()->getDocument( $collection->getId(), @@ -11403,8 +11409,8 @@ public function testCollectionPermissionsGetThrowsException(array $data): void { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $document = static::getDatabase()->getDocument( $collection->getId(), @@ -11423,14 +11429,14 @@ public function testCollectionPermissionsFindWorks(array $data): array { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $documents = static::getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('random')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('random')->toString()); try { static::getDatabase()->find($collection->getId()); @@ -11449,8 +11455,8 @@ public function testCollectionPermissionsFindThrowsException(array $data): void { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); static::getDatabase()->find($collection->getId()); @@ -11465,8 +11471,8 @@ public function testCollectionPermissionsCountWorks(array $data): array { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $count = static::getDatabase()->count( $collection->getId() @@ -11485,8 +11491,8 @@ public function testCollectionPermissionsCountThrowsException(array $data): void { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $count = static::getDatabase()->count( $collection->getId() @@ -11503,8 +11509,8 @@ public function testCollectionPermissionsUpdateWorks(array $data): array { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $this->assertInstanceOf(Document::class, static::getDatabase()->updateDocument( $collection->getId(), @@ -11522,8 +11528,8 @@ public function testCollectionPermissionsUpdateWorks(array $data): array public function testCollectionPermissionsUpdateThrowsException(array $data): void { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = static::getDatabase()->updateDocument( @@ -11541,8 +11547,8 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); static::getDatabase()->deleteDocument( @@ -11559,8 +11565,8 @@ public function testCollectionPermissionsDeleteWorks(array $data): void { [$collection, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), @@ -11651,8 +11657,8 @@ public function testCollectionPermissionsRelationships(): array public function testCollectionPermissionsRelationshipsCreateWorks(array $data): array { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -11704,8 +11710,8 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); static::getDatabase()->createDocument($collection->getId(), new Document([ @@ -11727,8 +11733,8 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $document = static::getDatabase()->getDocument( $collection->getId(), @@ -11741,8 +11747,8 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('random')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('random')->toString()); $document = static::getDatabase()->getDocument( $collection->getId(), @@ -11766,8 +11772,8 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $document = static::getDatabase()->getDocument( $collection->getId(), @@ -11785,8 +11791,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $documents = static::getDatabase()->find( $collection->getId() @@ -11801,8 +11807,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('random')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('random')->toString()); $documents = static::getDatabase()->find( $collection->getId() @@ -11817,8 +11823,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(1, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('unknown')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('unknown')->toString()); $documents = static::getDatabase()->find( $collection->getId() @@ -11836,8 +11842,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $documents = static::getDatabase()->count( $collection->getId() @@ -11845,8 +11851,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('random')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('random')->toString()); $documents = static::getDatabase()->count( $collection->getId() @@ -11854,8 +11860,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('unknown')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('unknown')->toString()); $documents = static::getDatabase()->count( $collection->getId() @@ -11873,8 +11879,8 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), @@ -11883,8 +11889,8 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->assertTrue(true); - Authorization::cleanRoles(); - Authorization::setRole(Role::user('random')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('random')->toString()); static::getDatabase()->updateDocument( $collection->getId(), @@ -11905,8 +11911,8 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = static::getDatabase()->updateDocument( @@ -11924,8 +11930,8 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::any()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = static::getDatabase()->deleteDocument( @@ -11942,8 +11948,8 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - Authorization::cleanRoles(); - Authorization::setRole(Role::users()->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::users()->toString()); $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), @@ -11958,8 +11964,8 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void return; } - Authorization::cleanRoles(); - Authorization::setRole(Role::user('a')->toString()); + $this->authorization->cleanRoles(); + $this->authorization->setRole(Role::user('a')->toString()); static::getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), @@ -12324,7 +12330,7 @@ public function testLabels(): void $this->assertEmpty($documents); - Authorization::setRole(Role::label('reader')->toString()); + $this->authorization->setRole(Role::label('reader')->toString()); $documents = static::getDatabase()->find('labels_test'); @@ -12416,7 +12422,7 @@ public function testEmptyOperatorValues(): void public function testEvents(): void { - Authorization::skip(function () { + $this->authorization->skip(function () { $database = static::getDatabase(); $events = [ diff --git a/tests/Database/Validator/AuthorizationTest.php b/tests/Database/Validator/AuthorizationTest.php index f900ff776..89c98a0ad 100644 --- a/tests/Database/Validator/AuthorizationTest.php +++ b/tests/Database/Validator/AuthorizationTest.php @@ -12,8 +12,11 @@ class AuthorizationTest extends TestCase { + protected Authorization $authorization; + public function setUp(): void { + $this->authorization = new Authorization(); } public function tearDown(): void @@ -22,7 +25,7 @@ public function tearDown(): void public function testValues(): void { - Authorization::setRole(Role::any()->toString()); + $this->authorization->setRole(Role::any()->toString()); $document = new Document([ '$id' => ID::unique(), @@ -35,88 +38,89 @@ public function testValues(): void Permission::delete(Role::any()), ], ]); - $object = new Authorization(Database::PERMISSION_READ); + + $object = $this->authorization->setAction(Database::PERMISSION_READ); $this->assertEquals($object->isValid($document->getRead()), false); $this->assertEquals($object->isValid(''), false); $this->assertEquals($object->isValid([]), false); $this->assertEquals($object->getDescription(), 'No permissions provided for action \'read\''); - Authorization::setRole(Role::user('456')->toString()); - Authorization::setRole(Role::user('123')->toString()); + $this->authorization->setRole(Role::user('456')->toString()); + $this->authorization->setRole(Role::user('123')->toString()); - $this->assertEquals(Authorization::isRole(Role::user('456')->toString()), true); - $this->assertEquals(Authorization::isRole(Role::user('457')->toString()), false); - $this->assertEquals(Authorization::isRole(''), false); - $this->assertEquals(Authorization::isRole(Role::any()->toString()), true); + $this->assertEquals($this->authorization->isRole(Role::user('456')->toString()), true); + $this->assertEquals($this->authorization->isRole(Role::user('457')->toString()), false); + $this->assertEquals($this->authorization->isRole(''), false); + $this->assertEquals($this->authorization->isRole(Role::any()->toString()), true); $this->assertEquals($object->isValid($document->getRead()), true); - Authorization::cleanRoles(); + $this->authorization->cleanRoles(); $this->assertEquals($object->isValid($document->getRead()), false); - Authorization::setRole(Role::team('123')->toString()); + $this->authorization->setRole(Role::team('123')->toString()); $this->assertEquals($object->isValid($document->getRead()), true); - Authorization::cleanRoles(); - Authorization::disable(); + $this->authorization->cleanRoles(); + $this->authorization->disable(); $this->assertEquals($object->isValid($document->getRead()), true); - Authorization::reset(); + $this->authorization->reset(); $this->assertEquals($object->isValid($document->getRead()), false); - Authorization::setDefaultStatus(false); - Authorization::disable(); + $this->authorization->setDefaultStatus(false); + $this->authorization->disable(); $this->assertEquals($object->isValid($document->getRead()), true); - Authorization::reset(); + $this->authorization->reset(); $this->assertEquals($object->isValid($document->getRead()), true); - Authorization::enable(); + $this->authorization->enable(); $this->assertEquals($object->isValid($document->getRead()), false); - Authorization::setRole('textX'); + $this->authorization->setRole('textX'); - $this->assertContains('textX', Authorization::getRoles()); + $this->assertContains('textX', $this->authorization->getRoles()); - Authorization::unsetRole('textX'); + $this->authorization->unsetRole('textX'); - $this->assertNotContains('textX', Authorization::getRoles()); + $this->assertNotContains('textX', $this->authorization->getRoles()); // Test skip method $this->assertEquals($object->isValid($document->getRead()), false); - $this->assertEquals(Authorization::skip(function () use ($object, $document) { + $this->assertEquals($this->authorization->skip(function () use ($object, $document) { return $object->isValid($document->getRead()); }), true); } public function testNestedSkips(): void { - $this->assertEquals(true, Authorization::$status); + $this->assertEquals(true, $this->authorization->status); - Authorization::skip(function () { - $this->assertEquals(false, Authorization::$status); + $this->authorization->skip(function () { + $this->assertEquals(false, $this->authorization->status); - Authorization::skip(function () { - $this->assertEquals(false, Authorization::$status); + $this->authorization->skip(function () { + $this->assertEquals(false, $this->authorization->status); - Authorization::skip(function () { - $this->assertEquals(false, Authorization::$status); + $this->authorization->skip(function () { + $this->assertEquals(false, $this->authorization->status); }); - $this->assertEquals(false, Authorization::$status); + $this->assertEquals(false, $this->authorization->status); }); - $this->assertEquals(false, Authorization::$status); + $this->assertEquals(false, $this->authorization->status); }); - $this->assertEquals(true, Authorization::$status); + $this->assertEquals(true, $this->authorization->status); } } From a8bec8b1a783d94deb7a00fa01948abf389cf789 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 19 Oct 2023 14:41:17 +0200 Subject: [PATCH 005/103] Fix incorrect Auth instance in tests --- tests/Database/Adapter/MariaDBTest.php | 4 +- tests/Database/Adapter/MongoDBTest.php | 4 +- tests/Database/Adapter/MySQLTest.php | 4 +- tests/Database/Adapter/PostgresTest.php | 4 +- tests/Database/Adapter/SQLiteTest.php | 4 +- tests/Database/Base.php | 3074 +++++++++++------------ 6 files changed, 1547 insertions(+), 1547 deletions(-) diff --git a/tests/Database/Adapter/MariaDBTest.php b/tests/Database/Adapter/MariaDBTest.php index af616f260..813144894 100644 --- a/tests/Database/Adapter/MariaDBTest.php +++ b/tests/Database/Adapter/MariaDBTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -46,7 +46,7 @@ public static function getDatabase(): Database $redis->flushAll(); $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new MariaDB($pdo), $cache); + $database = new Database(new MariaDB($pdo), $cache, [], $this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/MongoDBTest.php b/tests/Database/Adapter/MongoDBTest.php index 62c48ae37..1042a6470 100644 --- a/tests/Database/Adapter/MongoDBTest.php +++ b/tests/Database/Adapter/MongoDBTest.php @@ -30,7 +30,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -51,7 +51,7 @@ public static function getDatabase(): Database false ); - $database = new Database(new Mongo($client), $cache); + $database = new Database(new Mongo($client), $cache, [], $this->authorization); $database->setDefaultDatabase($schema); $database->setNamespace('myapp_' . uniqid()); diff --git a/tests/Database/Adapter/MySQLTest.php b/tests/Database/Adapter/MySQLTest.php index 0faefca61..9397147c2 100644 --- a/tests/Database/Adapter/MySQLTest.php +++ b/tests/Database/Adapter/MySQLTest.php @@ -38,7 +38,7 @@ public static function getUsedIndexes(): int /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -57,7 +57,7 @@ public static function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new MySQL($pdo), $cache); + $database = new Database(new MySQL($pdo), $cache, [], $this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/PostgresTest.php b/tests/Database/Adapter/PostgresTest.php index 9965a8684..644725881 100644 --- a/tests/Database/Adapter/PostgresTest.php +++ b/tests/Database/Adapter/PostgresTest.php @@ -27,7 +27,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -44,7 +44,7 @@ public static function getDatabase(): Database $redis->flushAll(); $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new Postgres($pdo), $cache); + $database = new Database(new Postgres($pdo), $cache, [], $this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/SQLiteTest.php b/tests/Database/Adapter/SQLiteTest.php index 8a8d24199..0fc463ad8 100644 --- a/tests/Database/Adapter/SQLiteTest.php +++ b/tests/Database/Adapter/SQLiteTest.php @@ -38,7 +38,7 @@ public static function getUsedIndexes(): int /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -60,7 +60,7 @@ public static function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new SQLite($pdo), $cache); + $database = new Database(new SQLite($pdo), $cache, [], $this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Base.php b/tests/Database/Base.php index 75be1c0ae..9e19cfdd1 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -32,12 +32,12 @@ abstract class Base extends TestCase /** * @var Authorization */ - private Authorization $authorization; + protected Authorization $authorization; /** * @return Database */ - abstract protected static function getDatabase(): Database; + abstract protected function getDatabase(): Database; /** * @return string @@ -59,26 +59,26 @@ public function tearDown(): void public function testPing(): void { - $this->assertEquals(true, static::getDatabase()->ping()); + $this->assertEquals(true, $this->getDatabase()->ping()); } public function testCreateExistsDelete(): void { $schemaSupport = $this->getDatabase()->getAdapter()->getSupportForSchemas(); if (!$schemaSupport) { - $this->assertEquals(true, static::getDatabase()->setDefaultDatabase($this->testDatabase)); - $this->assertEquals(true, static::getDatabase()->create()); + $this->assertEquals(true, $this->getDatabase()->setDefaultDatabase($this->testDatabase)); + $this->assertEquals(true, $this->getDatabase()->create()); return; } - if (!static::getDatabase()->exists($this->testDatabase)) { - $this->assertEquals(true, static::getDatabase()->create()); + if (!$this->getDatabase()->exists($this->testDatabase)) { + $this->assertEquals(true, $this->getDatabase()->create()); } - $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase)); - $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); - $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase)); - $this->assertEquals(true, static::getDatabase()->setDefaultDatabase($this->testDatabase)); - $this->assertEquals(true, static::getDatabase()->create()); + $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase)); + $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); + $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase)); + $this->assertEquals(true, $this->getDatabase()->setDefaultDatabase($this->testDatabase)); + $this->assertEquals(true, $this->getDatabase()->create()); } /** @@ -128,14 +128,14 @@ public function testIndexValidation(): void 'indexes' => $indexes ]); - $validator = new Index(static::getDatabase()->getAdapter()->getMaxIndexLength()); + $validator = new Index($this->getDatabase()->getAdapter()->getMaxIndexLength()); $errorMessage = 'Index length 701 is larger than the size for title1: 700"'; $this->assertFalse($validator->isValid($collection)); $this->assertEquals($errorMessage, $validator->getDescription()); try { - static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -153,13 +153,13 @@ public function testIndexValidation(): void $collection->setAttribute('indexes', $indexes); - if (static::getDatabase()->getAdapter()->getMaxIndexLength() > 0) { - $errorMessage = 'Index length is longer than the maximum: ' . static::getDatabase()->getAdapter()->getMaxIndexLength(); + if ($this->getDatabase()->getAdapter()->getMaxIndexLength() > 0) { + $errorMessage = 'Index length is longer than the maximum: ' . $this->getDatabase()->getAdapter()->getMaxIndexLength(); $this->assertFalse($validator->isValid($collection)); $this->assertEquals($errorMessage, $validator->getDescription()); try { - static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -200,7 +200,7 @@ public function testIndexValidation(): void $this->assertEquals($errorMessage, $validator->getDescription()); try { - static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -209,9 +209,9 @@ public function testIndexValidation(): void public function testCreatedAtUpdatedAt(): void { - $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('created_at')); - static::getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); - $document = static::getDatabase()->createDocument('created_at', new Document([ + $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('created_at')); + $this->getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); + $document = $this->getDatabase()->createDocument('created_at', new Document([ '$id' => ID::custom('uid123'), '$permissions' => [ @@ -229,11 +229,11 @@ public function testCreatedAtUpdatedAt(): void public function testQueryTimeoutUsingStaticTimeout(): void { if ($this->getDatabase()->getAdapter()->getSupportForTimeouts()) { - static::getDatabase()->createCollection('global-timeouts'); - $this->assertEquals(true, static::getDatabase()->createAttribute('global-timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); + $this->getDatabase()->createCollection('global-timeouts'); + $this->assertEquals(true, $this->getDatabase()->createAttribute('global-timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); for ($i = 0 ; $i <= 5 ; $i++) { - static::getDatabase()->createDocument('global-timeouts', new Document([ + $this->getDatabase()->createDocument('global-timeouts', new Document([ 'longtext' => file_get_contents(__DIR__ . '/../resources/longtext.txt'), '$permissions' => [ Permission::read(Role::any()), @@ -244,15 +244,15 @@ public function testQueryTimeoutUsingStaticTimeout(): void } $this->expectException(Timeout::class); - static::getDatabase()->setTimeout(1); + $this->getDatabase()->setTimeout(1); try { - static::getDatabase()->find('global-timeouts', [ + $this->getDatabase()->find('global-timeouts', [ Query::notEqual('longtext', 'appwrite'), ]); } catch(Timeout $ex) { - static::getDatabase()->clearTimeout(); - static::getDatabase()->deleteCollection('global-timeouts'); + $this->getDatabase()->clearTimeout(); + $this->getDatabase()->deleteCollection('global-timeouts'); throw $ex; } } @@ -265,55 +265,55 @@ public function testQueryTimeoutUsingStaticTimeout(): void */ public function testCreateListExistsDeleteCollection(): void { - $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors')); - $this->assertCount(2, static::getDatabase()->listCollections()); - $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors')); + $this->assertCount(2, $this->getDatabase()->listCollections()); + $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors')); // Collection names should not be unique - $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors2')); - $this->assertCount(3, static::getDatabase()->listCollections()); - $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors2')); - $collection = static::getDatabase()->getCollection('actors2'); + $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors2')); + $this->assertCount(3, $this->getDatabase()->listCollections()); + $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors2')); + $collection = $this->getDatabase()->getCollection('actors2'); $collection->setAttribute('name', 'actors'); // change name to one that exists - $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->updateDocument($collection->getCollection(), $collection->getId(), $collection)); - $this->assertEquals(true, static::getDatabase()->deleteCollection('actors2')); // Delete collection when finished - $this->assertCount(2, static::getDatabase()->listCollections()); + $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->updateDocument($collection->getCollection(), $collection->getId(), $collection)); + $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors2')); // Delete collection when finished + $this->assertCount(2, $this->getDatabase()->listCollections()); - $this->assertEquals(false, static::getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(true, static::getDatabase()->deleteCollection('actors')); - $this->assertEquals(true, static::getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertEquals(false, $this->getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors')); + $this->assertEquals(true, $this->getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase, 'actors')); } public function testSizeCollection(): void { - static::getDatabase()->createCollection('sizeTest1'); - static::getDatabase()->createCollection('sizeTest2'); + $this->getDatabase()->createCollection('sizeTest1'); + $this->getDatabase()->createCollection('sizeTest2'); - $size1 = static::getDatabase()->getSizeOfCollection('sizeTest1'); - $size2 = static::getDatabase()->getSizeOfCollection('sizeTest2'); + $size1 = $this->getDatabase()->getSizeOfCollection('sizeTest1'); + $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); $sizeDifference = abs($size1 - $size2); // Size of an empty collection returns either 172032 or 167936 bytes randomly // Therefore asserting with a tolerance of 5000 bytes $byteDifference = 5000; $this->assertLessThan($byteDifference, $sizeDifference); - static::getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 128, true); - static::getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); - static::getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); - static::getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + $this->getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 128, true); + $this->getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 40; for ($i = 0; $i < $loopCount; $i++) { - static::getDatabase()->createDocument('sizeTest2', new Document([ + $this->getDatabase()->createDocument('sizeTest2', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, ])); } - $size2 = static::getDatabase()->getSizeOfCollection('sizeTest2'); + $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertGreaterThan($size1, $size2); } @@ -321,126 +321,126 @@ public function testSizeCollection(): void public function testSizeFullText(): void { // SQLite does not support fulltext indexes - if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('fullTextSizeTest'); + $this->getDatabase()->createCollection('fullTextSizeTest'); - $size1 = static::getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size1 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); - static::getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); - static::getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); - static::getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); - static::getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + $this->getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); + $this->getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); + $this->getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); + $this->getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 10; for ($i = 0; $i < $loopCount; $i++) { - static::getDatabase()->createDocument('fullTextSizeTest', new Document([ + $this->getDatabase()->createDocument('fullTextSizeTest', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, ])); } - $size2 = static::getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size2 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); $this->assertGreaterThan($size1, $size2); - static::getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); + $this->getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); - $size3 = static::getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size3 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); $this->assertGreaterThan($size2, $size3); } public function testCreateDeleteAttribute(): void { - static::getDatabase()->createCollection('attributes'); + $this->getDatabase()->createCollection('attributes'); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); - $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); - $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); + $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); + $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); + $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); - $collection = static::getDatabase()->getCollection('attributes'); + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(8, $collection->getAttribute('attributes')); $this->assertCount(3, $collection->getAttribute('indexes')); // Array - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); - $collection = static::getDatabase()->getCollection('attributes'); + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(12, $collection->getAttribute('attributes')); // Default values - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $collection = static::getDatabase()->getCollection('attributes'); + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(17, $collection->getAttribute('attributes')); // Delete - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string1')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string2')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string3')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string4')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'bigint')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean')); - - $collection = static::getDatabase()->getCollection('attributes'); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string1')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string2')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string3')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string4')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'bigint')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean')); + + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(9, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // Delete Array - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_list')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_list')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_list')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_list')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_list')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_list')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_list')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_list')); - $collection = static::getDatabase()->getCollection('attributes'); + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(5, $collection->getAttribute('attributes')); // Delete default - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_default')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_default')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_default')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_default')); - $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'datetime_default')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_default')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_default')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_default')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_default')); + $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'datetime_default')); - $collection = static::getDatabase()->getCollection('attributes'); + $collection = $this->getDatabase()->getCollection('attributes'); $this->assertCount(0, $collection->getAttribute('attributes')); // Test for custom chars in ID - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); // Using this collection to test invalid default values - // static::getDatabase()->deleteCollection('attributes'); + // $this->getDatabase()->deleteCollection('attributes'); } /** @@ -474,7 +474,7 @@ public function invalidDefaultValues(): array public function testInvalidDefaultValues(string $type, mixed $default): void { $this->expectException(\Exception::class); - $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); + $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); } /** @@ -482,18 +482,18 @@ public function testInvalidDefaultValues(string $type, mixed $default): void */ public function testAttributeCaseInsensitivity(): void { - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'caseSensitive', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'caseSensitive', Database::VAR_STRING, 128, true)); $this->expectException(DuplicateException::class); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); } public function testAttributeKeyWithSymbols(): void { - static::getDatabase()->createCollection('attributesWithKeys'); + $this->getDatabase()->createCollection('attributesWithKeys'); - $this->assertEquals(true, static::getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); - $document = static::getDatabase()->createDocument('attributesWithKeys', new Document([ + $document = $this->getDatabase()->createDocument('attributesWithKeys', new Document([ 'key_with.sym$bols' => 'value', '$permissions' => [ Permission::read(Role::any()), @@ -502,7 +502,7 @@ public function testAttributeKeyWithSymbols(): void $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); - $document = static::getDatabase()->getDocument('attributesWithKeys', $document->getId()); + $document = $this->getDatabase()->getDocument('attributesWithKeys', $document->getId()); $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); } @@ -510,7 +510,7 @@ public function testAttributeKeyWithSymbols(): void public function testCollectionNotFound(): void { try { - static::getDatabase()->find('not_exist', []); + $this->getDatabase()->find('not_exist', []); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Collection "not_exist" not found', $e->getMessage()); @@ -519,9 +519,9 @@ public function testCollectionNotFound(): void public function testAttributeNamesWithDots(): void { - static::getDatabase()->createCollection('dots.parent'); + $this->getDatabase()->createCollection('dots.parent'); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: 'dots.parent', id: 'dots.name', type: Database::VAR_STRING, @@ -529,14 +529,14 @@ public function testAttributeNamesWithDots(): void required: false )); - $document = static::getDatabase()->find('dots.parent', [ + $document = $this->getDatabase()->find('dots.parent', [ Query::select(['dots.name']), ]); $this->assertEmpty($document); - static::getDatabase()->createCollection('dots'); + $this->getDatabase()->createCollection('dots'); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: 'dots', id: 'name', type: Database::VAR_STRING, @@ -544,13 +544,13 @@ public function testAttributeNamesWithDots(): void required: false )); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'dots.parent', relatedCollection: 'dots', type: Database::RELATION_ONE_TO_ONE ); - static::getDatabase()->createDocument('dots.parent', new Document([ + $this->getDatabase()->createDocument('dots.parent', new Document([ '$id' => ID::custom('father'), 'dots.name' => 'Bill clinton', '$permissions' => [ @@ -570,7 +570,7 @@ public function testAttributeNamesWithDots(): void ] ])); - $documents = static::getDatabase()->find('dots.parent', [ + $documents = $this->getDatabase()->find('dots.parent', [ Query::select(['*']), ]); @@ -582,9 +582,9 @@ public function testAttributeNamesWithDots(): void */ public function testIndexCaseInsensitivity(): void { - $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); $this->expectException(DuplicateException::class); - $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); } /** @@ -594,7 +594,7 @@ public function testIndexCaseInsensitivity(): void */ public function testCleanupAttributeTests(): void { - static::getDatabase()->deleteCollection('attributes'); + $this->getDatabase()->deleteCollection('attributes'); $this->assertEquals(1, 1); } @@ -605,42 +605,42 @@ public function testCleanupAttributeTests(): void public function testUnknownFormat(): void { $this->expectException(\Exception::class); - $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); + $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); } public function testCreateDeleteIndex(): void { - static::getDatabase()->createCollection('indexes'); + $this->getDatabase()->createCollection('indexes'); - $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); // Indexes - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); - - $collection = static::getDatabase()->getCollection('indexes'); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); + + $collection = $this->getDatabase()->getCollection('indexes'); $this->assertCount(6, $collection->getAttribute('indexes')); // Delete Indexes - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index1')); - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index2')); - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index3')); - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index4')); - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index5')); - $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'order')); - - $collection = static::getDatabase()->getCollection('indexes'); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index1')); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index2')); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index3')); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index4')); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index5')); + $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'order')); + + $collection = $this->getDatabase()->getCollection('indexes'); $this->assertCount(0, $collection->getAttribute('indexes')); - static::getDatabase()->deleteCollection('indexes'); + $this->getDatabase()->deleteCollection('indexes'); } public function testCreateCollectionWithSchema(): void @@ -699,7 +699,7 @@ public function testCreateCollectionWithSchema(): void ]), ]; - $collection = static::getDatabase()->createCollection('withSchema', $attributes, $indexes); + $collection = $this->getDatabase()->createCollection('withSchema', $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals('withSchema', $collection->getId()); @@ -722,10 +722,10 @@ public function testCreateCollectionWithSchema(): void $this->assertEquals('index3', $collection->getAttribute('indexes')[2]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[2]['type']); - static::getDatabase()->deleteCollection('withSchema'); + $this->getDatabase()->deleteCollection('withSchema'); // Test collection with dash (+attribute +index) - $collection2 = static::getDatabase()->createCollection('with-dash', [ + $collection2 = $this->getDatabase()->createCollection('with-dash', [ new Document([ '$id' => ID::custom('attribute-one'), 'type' => Database::VAR_STRING, @@ -755,7 +755,7 @@ public function testCreateCollectionWithSchema(): void $this->assertCount(1, $collection2->getAttribute('indexes')); $this->assertEquals('index-one', $collection2->getAttribute('indexes')[0]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection2->getAttribute('indexes')[0]['type']); - static::getDatabase()->deleteCollection('with-dash'); + $this->getDatabase()->deleteCollection('with-dash'); } public function testCreateCollectionValidator(): void @@ -854,7 +854,7 @@ public function testCreateCollectionValidator(): void ]; foreach ($collections as $id) { - $collection = static::getDatabase()->createCollection($id, $attributes, $indexes); + $collection = $this->getDatabase()->createCollection($id, $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals($id, $collection->getId()); @@ -881,24 +881,24 @@ public function testCreateCollectionValidator(): void $this->assertEquals('index.4', $collection->getAttribute('indexes')[3]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[3]['type']); - static::getDatabase()->deleteCollection($id); + $this->getDatabase()->deleteCollection($id); } } public function testCreateDocument(): Document { - static::getDatabase()->createCollection('documents'); + $this->getDatabase()->createCollection('documents'); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'bigint', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); - $document = static::getDatabase()->createDocument('documents', new Document([ + $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user(ID::custom('1'))), @@ -940,7 +940,7 @@ public function testCreateDocument(): Document $this->assertEquals('Works', $document->getAttribute('with-dash')); // Test create document with manual internal id - $manualIdDocument = static::getDatabase()->createDocument('documents', new Document([ + $manualIdDocument = $this->getDatabase()->createDocument('documents', new Document([ '$id' => '56000', '$internalId' => '56000', '$permissions' => [ @@ -984,7 +984,7 @@ public function testCreateDocument(): Document $this->assertEquals([], $manualIdDocument->getAttribute('empty')); $this->assertEquals('Works', $manualIdDocument->getAttribute('with-dash')); - $manualIdDocument = static::getDatabase()->getDocument('documents', '56000'); + $manualIdDocument = $this->getDatabase()->getDocument('documents', '56000'); $this->assertEquals('56000', $manualIdDocument->getInternalId()); $this->assertNotEmpty(true, $manualIdDocument->getId()); @@ -1008,15 +1008,15 @@ public function testCreateDocument(): Document public function testRespectNulls(): Document { - static::getDatabase()->createCollection('documents_nulls'); + $this->getDatabase()->createCollection('documents_nulls'); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); - $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); - $document = static::getDatabase()->createDocument('documents_nulls', new Document([ + $document = $this->getDatabase()->createDocument('documents_nulls', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -1044,16 +1044,16 @@ public function testRespectNulls(): Document public function testCreateDocumentDefaults(): void { - static::getDatabase()->createCollection('defaults'); + $this->getDatabase()->createCollection('defaults'); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $document = static::getDatabase()->createDocument('defaults', new Document([ + $document = $this->getDatabase()->createDocument('defaults', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -1062,7 +1062,7 @@ public function testCreateDocumentDefaults(): void ], ])); - $document2 = static::getDatabase()->getDocument('defaults', $document->getId()); + $document2 = $this->getDatabase()->getDocument('defaults', $document->getId()); $this->assertCount(4, $document2->getPermissions()); $this->assertEquals('read("any")', $document2->getPermissions()[0]); $this->assertEquals('create("any")', $document2->getPermissions()[1]); @@ -1084,7 +1084,7 @@ public function testCreateDocumentDefaults(): void $this->assertEquals('2000-06-12T14:12:55.000+00:00', $document->getAttribute('datetime')); // cleanup collection - static::getDatabase()->deleteCollection('defaults'); + $this->getDatabase()->deleteCollection('defaults'); } /** @@ -1093,14 +1093,14 @@ public function testCreateDocumentDefaults(): void public function testIncreaseDecrease(): Document { $collection = 'increase_decrease'; - static::getDatabase()->createCollection($collection); + $this->getDatabase()->createCollection($collection); - $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); - $document = static::getDatabase()->createDocument($collection, new Document([ + $document = $this->getDatabase()->createDocument($collection, new Document([ 'increase' => 100, 'decrease' => 100, 'increase_float' => 100, @@ -1113,21 +1113,21 @@ public function testIncreaseDecrease(): Document ] ])); - $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase', 1, 101)); + $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase', 1, 101)); - $document = static::getDatabase()->getDocument($collection, $document->getId()); + $document = $this->getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(101, $document->getAttribute('increase')); - $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); - $document = static::getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); + $document = $this->getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(99, $document->getAttribute('decrease')); - $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); - $document = static::getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); + $document = $this->getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(105.5, $document->getAttribute('increase_float')); - $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); - $document = static::getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); + $document = $this->getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(104.4, $document->getAttribute('increase_float')); return $document; @@ -1139,7 +1139,7 @@ public function testIncreaseDecrease(): Document public function testIncreaseLimitMax(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); + $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); } /** @@ -1148,7 +1148,7 @@ public function testIncreaseLimitMax(Document $document): void public function testDecreaseLimitMin(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, static::getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); + $this->assertEquals(false, $this->getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); } /** @@ -1157,7 +1157,7 @@ public function testDecreaseLimitMin(Document $document): void public function testIncreaseTextAttribute(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); + $this->assertEquals(false, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); } /** @@ -1165,7 +1165,7 @@ public function testIncreaseTextAttribute(Document $document): void */ public function testGetDocument(Document $document): Document { - $document = static::getDatabase()->getDocument('documents', $document->getId()); + $document = $this->getDatabase()->getDocument('documents', $document->getId()); $this->assertNotEmpty(true, $document->getId()); $this->assertIsString($document->getAttribute('string')); @@ -1190,7 +1190,7 @@ public function testGetDocumentSelect(Document $document): Document { $documentId = $document->getId(); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer']), ]); @@ -1211,7 +1211,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$id']), ]); @@ -1222,7 +1222,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$permissions']), ]); @@ -1233,7 +1233,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$internalId']), ]); @@ -1244,7 +1244,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$collection']), ]); @@ -1255,7 +1255,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$createdAt']), ]); @@ -1266,7 +1266,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = static::getDatabase()->getDocument('documents', $documentId, [ + $document = $this->getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer', '$updatedAt']), ]); @@ -1293,7 +1293,7 @@ public function testFulltextIndexWithInteger(): void $this->expectExceptionMessage('Attribute "integer" cannot be part of a FULLTEXT index, must be of type string'); } - static::getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer']); + $this->getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer']); } public function testListDocumentSearch(): void @@ -1304,8 +1304,8 @@ public function testListDocumentSearch(): void return; } - static::getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); - static::getDatabase()->createDocument('documents', new Document([ + $this->getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); + $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -1324,7 +1324,7 @@ public function testListDocumentSearch(): void /** * Allow reserved keywords for search */ - $documents = static::getDatabase()->find('documents', [ + $documents = $this->getDatabase()->find('documents', [ Query::search('string', '*test+alias@email-provider.com'), ]); @@ -1339,17 +1339,17 @@ public function testEmptySearch(): void return; } - $documents = static::getDatabase()->find('documents', [ + $documents = $this->getDatabase()->find('documents', [ Query::search('string', ''), ]); $this->assertEquals(0, count($documents)); - $documents = static::getDatabase()->find('documents', [ + $documents = $this->getDatabase()->find('documents', [ Query::search('string', '*'), ]); $this->assertEquals(0, count($documents)); - $documents = static::getDatabase()->find('documents', [ + $documents = $this->getDatabase()->find('documents', [ Query::search('string', '<>'), ]); $this->assertEquals(0, count($documents)); @@ -1489,21 +1489,21 @@ public function testDeleteDocument(Document $document): void public function testFind(): array { $this->authorization->setRole(Role::any()->toString()); - static::getDatabase()->createCollection('movies', permissions: [ + $this->getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ], documentSecurity: true); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'generes', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'generes', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); - $document = static::getDatabase()->createDocument('movies', new Document([ + $document = $this->getDatabase()->createDocument('movies', new Document([ '$id' => ID::custom('frozen'), '$permissions' => [ Permission::read(Role::any()), @@ -1528,7 +1528,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -1552,7 +1552,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -1576,7 +1576,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -1600,7 +1600,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -1624,7 +1624,7 @@ public function testFind(): array 'with-dash' => 'Works3' ])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::user('x')), Permission::create(Role::any()), @@ -1654,7 +1654,7 @@ public function testFind(): array public function testFindBasicChecks(): void { - $documents = static::getDatabase()->find('movies'); + $documents = $this->getDatabase()->find('movies'); $movieDocuments = $documents; $this->assertEquals(5, count($documents)); @@ -1687,13 +1687,13 @@ public function testFindBasicChecks(): void /** * Check $id: Notice, this orders ID names alphabetically, not by internal numeric ID */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('$id'), ]); $this->assertEquals($lastDocumentId, $documents[0]->getId()); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc('$id'), @@ -1703,13 +1703,13 @@ public function testFindBasicChecks(): void /** * Check internal numeric ID sorting */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); $this->assertEquals($movieDocuments[\count($movieDocuments) - 1]->getId(), $documents[0]->getId()); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc(''), @@ -1723,7 +1723,7 @@ public function testFindCheckPermissions(): void * Check Permissions */ $this->authorization->setRole('user:x'); - $documents = static::getDatabase()->find('movies'); + $documents = $this->getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); } @@ -1733,13 +1733,13 @@ public function testFindCheckInteger(): void /** * Query with dash attribute */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('with-dash', ['Works']), ]); $this->assertEquals(2, count($documents)); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('with-dash', ['Works2', 'Works3']), ]); @@ -1748,7 +1748,7 @@ public function testFindCheckInteger(): void /** * Check an Integer condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('year', [2019]), ]); @@ -1762,7 +1762,7 @@ public function testFindBoolean(): void /** * Boolean condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('active', [true]), ]); @@ -1774,7 +1774,7 @@ public function testFindStringQueryEqual(): void /** * String condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('director', ['TBD']), ]); @@ -1786,7 +1786,7 @@ public function testFindNotEqual(): void /** * Not Equal query */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::notEqual('director', 'TBD'), ]); @@ -1800,22 +1800,22 @@ public function testFindNotEqual(): void public function testFindBetween(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::between('price', 25.94, 25.99), ]); $this->assertEquals(2, count($documents)); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::between('price', 30, 35), ]); $this->assertEquals(0, count($documents)); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::between('$createdAt', '1975-12-06', '2050-12-06'), ]); $this->assertEquals(6, count($documents)); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::between('$updatedAt', '1975-12-06T07:08:49.733+02:00', '2050-02-05T10:15:21.825+00:00'), ]); $this->assertEquals(6, count($documents)); @@ -1826,7 +1826,7 @@ public function testFindFloat(): void /** * Float condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::lessThan('price', 26.00), Query::greaterThan('price', 25.98), ]); @@ -1841,7 +1841,7 @@ public function testFindContains(): void return; } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::contains('generes', ['comics']) ]); @@ -1850,7 +1850,7 @@ public function testFindContains(): void /** * Array contains OR condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::contains('generes', ['comics', 'kids']), ]); @@ -1863,10 +1863,10 @@ public function testFindFulltext(): void * Fulltext search */ if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { - $success = static::getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); + $success = $this->getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); $this->assertEquals(true, $success); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::search('name', 'captain'), ]); @@ -1880,7 +1880,7 @@ public function testFindFulltext(): void // TODO: I think this needs a changes? how do we distinguish between regular full text and wildcard? if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildCardIndex()) { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::search('name', 'cap'), ]); @@ -1893,62 +1893,62 @@ public function testFindFulltext(): void public function testFindFulltextSpecialChars(): void { - if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } $collection = 'full_text'; - static::getDatabase()->createCollection($collection, permissions: [ + $this->getDatabase()->createCollection($collection, permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ]); - $this->assertTrue(static::getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); - $this->assertTrue(static::getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); + $this->assertTrue($this->getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); + $this->assertTrue($this->getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); - static::getDatabase()->createDocument($collection, new Document([ + $this->getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'Alf: chapter_4@nasa.com' ])); - $documents = static::getDatabase()->find($collection, [ + $documents = $this->getDatabase()->find($collection, [ Query::search('ft', 'chapter_4'), ]); $this->assertEquals(1, count($documents)); - static::getDatabase()->createDocument($collection, new Document([ + $this->getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'al@ba.io +-*)(<>~' ])); - $documents = static::getDatabase()->find($collection, [ + $documents = $this->getDatabase()->find($collection, [ Query::search('ft', 'al@ba.io'), // === al ba io* ]); - if (static::getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { + if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { $this->assertEquals(0, count($documents)); } else { $this->assertEquals(1, count($documents)); } - static::getDatabase()->createDocument($collection, new Document([ + $this->getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald duck' ])); - static::getDatabase()->createDocument($collection, new Document([ + $this->getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald trump' ])); - $documents = static::getDatabase()->find($collection, [ + $documents = $this->getDatabase()->find($collection, [ Query::search('ft', 'donald trump'), Query::orderAsc('ft'), ]); $this->assertEquals(2, count($documents)); - $documents = static::getDatabase()->find($collection, [ + $documents = $this->getDatabase()->find($collection, [ Query::search('ft', '"donald trump"'), // Exact match ]); @@ -1960,7 +1960,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('director', ['TBD']), Query::equal('year', [2026]), ]); @@ -1970,7 +1970,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions and OR values */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('name', ['Frozen II', 'Captain Marvel']), ]); @@ -1984,7 +1984,7 @@ public function testFindByID(): void /** * $id condition */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('$id', ['frozen']), ]); @@ -2004,7 +2004,7 @@ public function testFindByInternalID(array $data): void /** * Test that internal ID queries are handled correctly */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('$internalId', [$data['$internalId']]), ]); @@ -2016,7 +2016,7 @@ public function testFindOrderBy(): void /** * ORDER BY */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -2037,11 +2037,11 @@ public function testFindOrderByNatural(): void /** * ORDER BY natural */ - $base = array_reverse(static::getDatabase()->find('movies', [ + $base = array_reverse($this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), @@ -2061,7 +2061,7 @@ public function testFindOrderByMultipleAttributes(): void /** * ORDER BY - Multiple attributes */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -2082,12 +2082,12 @@ public function testFindOrderByCursorAfter(): void /** * ORDER BY - After */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[1]) @@ -2096,7 +2096,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[3]) @@ -2105,7 +2105,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[4]) @@ -2113,7 +2113,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[5]) @@ -2127,12 +2127,12 @@ public function testFindOrderByCursorBefore(): void /** * ORDER BY - Before */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[5]) @@ -2141,7 +2141,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[3]) @@ -2150,7 +2150,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[2]) @@ -2159,7 +2159,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[1]) @@ -2167,7 +2167,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[0]) @@ -2180,12 +2180,12 @@ public function testFindOrderByAfterNaturalOrder(): void /** * ORDER BY - After by natural order */ - $movies = array_reverse(static::getDatabase()->find('movies', [ + $movies = array_reverse($this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2195,7 +2195,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2205,7 +2205,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2214,7 +2214,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2228,13 +2228,13 @@ public function testFindOrderByBeforeNaturalOrder(): void /** * ORDER BY - Before by natural order */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2244,7 +2244,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2254,7 +2254,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2264,7 +2264,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2273,7 +2273,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -2287,13 +2287,13 @@ public function testFindOrderBySingleAttributeAfter(): void /** * ORDER BY - Single Attribute After */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2304,7 +2304,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2314,7 +2314,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2323,7 +2323,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2337,13 +2337,13 @@ public function testFindOrderBySingleAttributeBefore(): void /** * ORDER BY - Single Attribute Before */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2353,7 +2353,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2363,7 +2363,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2373,7 +2373,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2382,7 +2382,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -2396,14 +2396,14 @@ public function testFindOrderByMultipleAttributeAfter(): void /** * ORDER BY - Multiple Attribute After */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2414,7 +2414,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2425,7 +2425,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2435,7 +2435,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2450,14 +2450,14 @@ public function testFindOrderByMultipleAttributeBefore(): void /** * ORDER BY - Multiple Attribute Before */ - $movies = static::getDatabase()->find('movies', [ + $movies = $this->getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2469,7 +2469,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2480,7 +2480,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2491,7 +2491,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2501,7 +2501,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -2516,12 +2516,12 @@ public function testFindOrderByAndCursor(): void /** * ORDER BY + CURSOR */ - $documentsTest = static::getDatabase()->find('movies', [ + $documentsTest = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('price'), @@ -2536,12 +2536,12 @@ public function testFindOrderByIdAndCursor(): void /** * ORDER BY ID + CURSOR */ - $documentsTest = static::getDatabase()->find('movies', [ + $documentsTest = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$id'), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$id'), @@ -2556,13 +2556,13 @@ public function testFindOrderByCreateDateAndCursor(): void /** * ORDER BY CREATE DATE + CURSOR */ - $documentsTest = static::getDatabase()->find('movies', [ + $documentsTest = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$createdAt'), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$createdAt'), @@ -2577,12 +2577,12 @@ public function testFindOrderByUpdateDateAndCursor(): void /** * ORDER BY UPDATE DATE + CURSOR */ - $documentsTest = static::getDatabase()->find('movies', [ + $documentsTest = $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$updatedAt'), ]); - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$updatedAt'), @@ -2597,7 +2597,7 @@ public function testFindLimit(): void /** * Limit */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(4), Query::offset(0), Query::orderAsc('name') @@ -2615,7 +2615,7 @@ public function testFindLimitAndOffset(): void /** * Limit + Offset */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::limit(4), Query::offset(2), Query::orderAsc('name') @@ -2633,7 +2633,7 @@ public function testFindOrQueries(): void /** * Test that OR queries are handled correctly */ - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); @@ -2651,7 +2651,7 @@ public function testFindOrderByAfterException(): void ]); $this->expectException(Exception::class); - static::getDatabase()->find('movies', [ + $this->getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($document) @@ -2661,11 +2661,11 @@ public function testFindOrderByAfterException(): void public function testTimeout(): void { if ($this->getDatabase()->getAdapter()->getSupportForTimeouts()) { - static::getDatabase()->createCollection('timeouts'); - $this->assertEquals(true, static::getDatabase()->createAttribute('timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); + $this->getDatabase()->createCollection('timeouts'); + $this->assertEquals(true, $this->getDatabase()->createAttribute('timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); for ($i = 0 ; $i <= 5 ; $i++) { - static::getDatabase()->createDocument('timeouts', new Document([ + $this->getDatabase()->createDocument('timeouts', new Document([ 'longtext' => file_get_contents(__DIR__ . '/../resources/longtext.txt'), '$permissions' => [ Permission::read(Role::any()), @@ -2677,7 +2677,7 @@ public function testTimeout(): void $this->expectException(Timeout::class); - static::getDatabase()->find('timeouts', [ + $this->getDatabase()->find('timeouts', [ Query::notEqual('longtext', 'appwrite'), ], 1); } @@ -2692,9 +2692,9 @@ public function testFindEdgeCases(Document $document): void { $collection = 'edgeCases'; - static::getDatabase()->createCollection($collection); + $this->getDatabase()->createCollection($collection); - $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); $values = [ 'NormalString', @@ -2713,7 +2713,7 @@ public function testFindEdgeCases(Document $document): void ]; foreach ($values as $value) { - static::getDatabase()->createDocument($collection, new Document([ + $this->getDatabase()->createDocument($collection, new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -2727,7 +2727,7 @@ public function testFindEdgeCases(Document $document): void /** * Check Basic */ - $documents = static::getDatabase()->find($collection); + $documents = $this->getDatabase()->find($collection); $this->assertEquals(count($values), count($documents)); $this->assertNotEmpty($documents[0]->getId()); @@ -2741,7 +2741,7 @@ public function testFindEdgeCases(Document $document): void * Check `equals` query */ foreach ($values as $value) { - $documents = static::getDatabase()->find($collection, [ + $documents = $this->getDatabase()->find($collection, [ Query::limit(25), Query::equal('value', [$value]) ]); @@ -2756,7 +2756,7 @@ public function testFindEdgeCases(Document $document): void */ public function testFindOne(): void { - $document = static::getDatabase()->findOne('movies', [ + $document = $this->getDatabase()->findOne('movies', [ Query::offset(2), Query::orderAsc('name') ]); @@ -2764,7 +2764,7 @@ public function testFindOne(): void $this->assertTrue($document instanceof Document); $this->assertEquals('Frozen', $document->getAttribute('name')); - $document = static::getDatabase()->findOne('movies', [ + $document = $this->getDatabase()->findOne('movies', [ Query::offset(10) ]); $this->assertEquals(false, $document); @@ -2772,7 +2772,7 @@ public function testFindOne(): void public function testFindNull(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::isNull('nullable'), ]); @@ -2781,7 +2781,7 @@ public function testFindNull(): void public function testFindNotNull(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::isNotNull('nullable'), ]); @@ -2790,18 +2790,18 @@ public function testFindNotNull(): void public function testFindStartsWith(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::startsWith('name', 'Work'), ]); $this->assertEquals(2, count($documents)); if ($this->getDatabase()->getAdapter() instanceof SQL) { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::startsWith('name', '%ork'), ]); } else { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::startsWith('name', '.*ork'), ]); } @@ -2811,7 +2811,7 @@ public function testFindStartsWith(): void public function testFindStartsWithWords(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::startsWith('name', 'Work in Progress'), ]); @@ -2820,7 +2820,7 @@ public function testFindStartsWithWords(): void public function testFindEndsWith(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::endsWith('name', 'Marvel'), ]); @@ -2829,7 +2829,7 @@ public function testFindEndsWith(): void public function testFindSelect(): void { - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year']) ]); @@ -2847,7 +2847,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$id']) ]); @@ -2865,7 +2865,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$internalId']) ]); @@ -2883,7 +2883,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$collection']) ]); @@ -2901,7 +2901,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$createdAt']) ]); @@ -2919,7 +2919,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$updatedAt']) ]); @@ -2937,7 +2937,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = static::getDatabase()->find('movies', [ + $documents = $this->getDatabase()->find('movies', [ Query::select(['name', 'year', '$permissions']) ]); @@ -2961,26 +2961,26 @@ public function testFindSelect(): void */ public function testCount(): void { - $count = static::getDatabase()->count('movies'); + $count = $this->getDatabase()->count('movies'); $this->assertEquals(6, $count); - $count = static::getDatabase()->count('movies', [Query::equal('year', [2019])]); + $count = $this->getDatabase()->count('movies', [Query::equal('year', [2019])]); $this->assertEquals(2, $count); - $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); + $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); $this->assertEquals(2, $count); - $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); + $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); $this->authorization->unsetRole('user:x'); - $count = static::getDatabase()->count('movies'); + $count = $this->getDatabase()->count('movies'); $this->assertEquals(5, $count); $this->authorization->disable(); - $count = static::getDatabase()->count('movies'); + $count = $this->getDatabase()->count('movies'); $this->assertEquals(6, $count); $this->authorization->reset(); $this->authorization->disable(); - $count = static::getDatabase()->count('movies', [], 3); + $count = $this->getDatabase()->count('movies', [], 3); $this->assertEquals(3, $count); $this->authorization->reset(); @@ -2988,7 +2988,7 @@ public function testCount(): void * Test that OR queries are handled correctly */ $this->authorization->disable(); - $count = static::getDatabase()->count('movies', [ + $count = $this->getDatabase()->count('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); @@ -3002,27 +3002,27 @@ public function testCount(): void public function testSum(): void { $this->authorization->setRole('user:x'); - $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = static::getDatabase()->sum('movies', 'year'); + $sum = $this->getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025 + 2026, $sum); - $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); + $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); $this->authorization->unsetRole('user:x'); $this->authorization->unsetRole('userx'); - $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = static::getDatabase()->sum('movies', 'year'); + $sum = $this->getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025, $sum); - $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); } @@ -3217,7 +3217,7 @@ public function testEncodeDecode(): void ], ]); - $result = static::getDatabase()->encode($collection, $document); + $result = $this->getDatabase()->encode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -3241,7 +3241,7 @@ public function testEncodeDecode(): void $this->assertEquals(['admin', 'developer', 'tester',], $result->getAttribute('roles')); $this->assertEquals(['{"$id":"1","label":"x"}', '{"$id":"2","label":"y"}', '{"$id":"3","label":"z"}',], $result->getAttribute('tags')); - $result = static::getDatabase()->decode($collection, $document); + $result = $this->getDatabase()->decode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -3278,7 +3278,7 @@ public function testReadPermissionsSuccess(Document $document): Document $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $document = static::getDatabase()->createDocument('documents', new Document([ + $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -3297,7 +3297,7 @@ public function testReadPermissionsSuccess(Document $document): Document $this->authorization->cleanRoles(); - $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); $this->authorization->setRole(Role::any()->toString()); @@ -3310,7 +3310,7 @@ public function testReadPermissionsFailure(): Document $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $document = static::getDatabase()->createDocument('documents', new Document([ + $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::user('1')), Permission::create(Role::user('1')), @@ -3327,7 +3327,7 @@ public function testReadPermissionsFailure(): Document $this->authorization->cleanRoles(); - $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); @@ -3344,7 +3344,7 @@ public function testWritePermissionsSuccess(Document $document): void $this->authorization->cleanRoles(); $this->expectException(AuthorizationException::class); - static::getDatabase()->createDocument('documents', new Document([ + $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -3370,7 +3370,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $document = static::getDatabase()->createDocument('documents', new Document([ + $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -3387,7 +3387,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document $this->authorization->cleanRoles(); - $document = static::getDatabase()->updateDocument('documents', $document->getId(), new Document([ + $document = $this->getDatabase()->updateDocument('documents', $document->getId(), new Document([ '$id' => ID::custom($document->getId()), '$permissions' => [ Permission::read(Role::any()), @@ -3411,7 +3411,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document */ public function testNoChangeUpdateDocumentWithoutPermission(Document $document): Document { - $document = static::getDatabase()->createDocument('documents', new Document([ + $document = $this->getDatabase()->createDocument('documents', new Document([ '$id' => ID::unique(), '$permissions' => [], 'string' => 'text📝', @@ -3422,7 +3422,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(Document $document): 'colors' => ['pink', 'green', 'blue'], ])); - $updatedDocument = static::getDatabase()->updateDocument( + $updatedDocument = $this->getDatabase()->updateDocument( 'documents', $document->getId(), $document @@ -3437,7 +3437,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(Document $document): public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -3458,13 +3458,13 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void Permission::delete(Role::any()), ]; for ($i=1; $i < 6; $i++) { - static::getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); + $this->getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); } for ($i = 1; $i < 5; $i++) { $collectionId = $i; $relatedCollectionId = $i+1; - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: "level{$collectionId}", relatedCollection: "level{$relatedCollectionId}", type: Database::RELATION_ONE_TO_ONE, @@ -3473,7 +3473,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void } // Create document with relationship with nested data - $level1 = static::getDatabase()->createDocument('level1', new Document([ + $level1 = $this->getDatabase()->createDocument('level1', new Document([ '$id' => 'level1', '$permissions' => [], 'name' => 'Level 1', @@ -3498,18 +3498,18 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void ], ], ])); - static::getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); - $updatedLevel1 = static::getDatabase()->getDocument('level1', $level1->getId()); + $this->getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); + $updatedLevel1 = $this->getDatabase()->getDocument('level1', $level1->getId()); $this->assertEquals($level1, $updatedLevel1); try { - static::getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); + $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); } catch(Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); - static::getDatabase()->updateCollection('level3', [ + $this->getDatabase()->updateCollection('level3', [ Permission::read(Role::any()), Permission::create(Role::any()), Permission::update(Role::any()), @@ -3522,11 +3522,11 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void $level2->setAttribute('level3', $level3); $level1->setAttribute('level2', $level2); - $level1 = static::getDatabase()->updateDocument('level1', $level1->getId(), $level1); + $level1 = $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1); $this->assertEquals('updated value', $level1['level2']['level3']['name']); for ($i=1; $i < 6; $i++) { - static::getDatabase()->deleteCollection("level{$i}"); + $this->getDatabase()->deleteCollection("level{$i}"); } } @@ -3548,10 +3548,10 @@ public function testExceptionAttributeLimit(): void ]); } - static::getDatabase()->createCollection('attributeLimit', $attributes); + $this->getDatabase()->createCollection('attributeLimit', $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, static::getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); + $this->assertEquals(false, $this->getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); } // Default assertion for other adapters @@ -3564,7 +3564,7 @@ public function testExceptionAttributeLimit(): void public function testCheckAttributeCountLimit(): void { if ($this->getDatabase()->getLimitForAttributes() > 0) { - $collection = static::getDatabase()->getCollection('attributeLimit'); + $collection = $this->getDatabase()->getCollection('attributeLimit'); // create same attribute in testExceptionAttributeLimit $attribute = new Document([ @@ -3579,7 +3579,7 @@ public function testCheckAttributeCountLimit(): void ]); $this->expectException(LimitException::class); - $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -3615,7 +3615,7 @@ public function rowWidthExceedsMaximum(): array */ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if (static::getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { + if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { $attributes = []; // Load the collection up to the limit @@ -3675,10 +3675,10 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo ]); } - $collection = static::getDatabase()->createCollection("widthLimit{$key}", $attributes); + $collection = $this->getDatabase()->createCollection("widthLimit{$key}", $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, static::getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); + $this->assertEquals(false, $this->getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); } // Default assertion for other adapters @@ -3691,8 +3691,8 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo */ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if (static::getDatabase()->getAdapter()::getDocumentSizeLimit()> 0) { - $collection = static::getDatabase()->getCollection("widthLimit{$key}"); + if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit()> 0) { + $collection = $this->getDatabase()->getCollection("widthLimit{$key}"); // create same attribute in testExceptionWidthLimit $attribute = new Document([ @@ -3707,7 +3707,7 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str ]); $this->expectException(LimitException::class); - $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -3716,22 +3716,22 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str public function testExceptionIndexLimit(): void { - static::getDatabase()->createCollection('indexLimit'); + $this->getDatabase()->createCollection('indexLimit'); // add unique attributes for indexing for ($i = 0; $i < 64; $i++) { - $this->assertEquals(true, static::getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); + $this->assertEquals(true, $this->getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); } // Testing for indexLimit // Add up to the limit, then check if the next index throws IndexLimitException for ($i = 0; $i < ($this->getDatabase()->getLimitForIndexes()); $i++) { - $this->assertEquals(true, static::getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); + $this->assertEquals(true, $this->getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); } $this->expectException(LimitException::class); - $this->assertEquals(false, static::getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); + $this->assertEquals(false, $this->getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); - static::getDatabase()->deleteCollection('indexLimit'); + $this->getDatabase()->deleteCollection('indexLimit'); } /** @@ -3740,10 +3740,10 @@ public function testExceptionIndexLimit(): void public function testExceptionDuplicate(Document $document): void { $document->setAttribute('$id', 'duplicated'); - static::getDatabase()->createDocument($document->getCollection(), $document); + $this->getDatabase()->createDocument($document->getCollection(), $document); $this->expectException(DuplicateException::class); - static::getDatabase()->createDocument($document->getCollection(), $document); + $this->getDatabase()->createDocument($document->getCollection(), $document); } /** @@ -3753,12 +3753,12 @@ public function testExceptionCaseInsensitiveDuplicate(Document $document): Docum { $document->setAttribute('$id', 'caseSensitive'); $document->setAttribute('$internalId', '200'); - static::getDatabase()->createDocument($document->getCollection(), $document); + $this->getDatabase()->createDocument($document->getCollection(), $document); $document->setAttribute('$id', 'CaseSensitive'); $this->expectException(DuplicateException::class); - static::getDatabase()->createDocument($document->getCollection(), $document); + $this->getDatabase()->createDocument($document->getCollection(), $document); return $document; } @@ -3770,9 +3770,9 @@ public function testUniqueIndexDuplicate(): void { $this->expectException(DuplicateException::class); - $this->assertEquals(true, static::getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, $this->getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); - static::getDatabase()->createDocument('movies', new Document([ + $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -3804,7 +3804,7 @@ public function testUniqueIndexDuplicateUpdate(): void { $this->authorization->setRole(Role::users()->toString()); // create document then update to conflict with index - $document = static::getDatabase()->createDocument('movies', new Document([ + $document = $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -3830,7 +3830,7 @@ public function testUniqueIndexDuplicateUpdate(): void $this->expectException(DuplicateException::class); - static::getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); + $this->getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); } public function testGetAttributeLimit(): void @@ -3856,7 +3856,7 @@ public function testGetId(): void public function testRenameIndex(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $numbers = $database->createCollection('numbers'); $database->createAttribute('numbers', 'verbose', Database::VAR_STRING, 128, true); @@ -3882,7 +3882,7 @@ public function testRenameIndex(): void */ public function testRenameIndexMissing(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $this->expectExceptionMessage('Index not found'); $index = $database->renameIndex('numbers', 'index1', 'index4'); } @@ -3893,14 +3893,14 @@ public function testRenameIndexMissing(): void */ public function testRenameIndexExisting(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $this->expectExceptionMessage('Index name already used'); $index = $database->renameIndex('numbers', 'index3', 'index2'); } public function testRenameAttribute(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $colors = $database->createCollection('colors'); $database->createAttribute('colors', 'name', Database::VAR_STRING, 128, true); @@ -3946,7 +3946,7 @@ public function testRenameAttribute(): void */ public function textRenameAttributeMissing(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $this->expectExceptionMessage('Attribute not found'); $database->renameAttribute('colors', 'name2', 'name3'); } @@ -3957,14 +3957,14 @@ public function textRenameAttributeMissing(): void */ public function testRenameAttributeExisting(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $this->expectExceptionMessage('Attribute name already used'); $database->renameAttribute('colors', 'verbose', 'hex'); } public function testUpdateAttributeDefault(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $flowers = $database->createCollection('flowers'); $database->createAttribute('flowers', 'name', Database::VAR_STRING, 128, true); @@ -4019,7 +4019,7 @@ public function testUpdateAttributeDefault(): void */ public function testUpdateAttributeRequired(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $database->updateAttributeRequired('flowers', 'inStock', true); @@ -4041,7 +4041,7 @@ public function testUpdateAttributeRequired(): void */ public function testUpdateAttributeFilter(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $database->createAttribute('flowers', 'cartModel', Database::VAR_STRING, 2000, false); @@ -4074,7 +4074,7 @@ public function testUpdateAttributeFilter(): void */ public function testUpdateAttributeFormat(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $database->createAttribute('flowers', 'price', Database::VAR_INTEGER, 0, false); @@ -4135,7 +4135,7 @@ public function testUpdateAttributeStructure(): void return new Range($min, $max); }, Database::VAR_INTEGER); - $database = static::getDatabase(); + $database = $this->getDatabase(); // price attribute $collection = $database->getCollection('flowers'); @@ -4275,27 +4275,27 @@ public function testUpdateAttributeStructure(): void */ public function testCreatedAtUpdatedAtAssert(): void { - $document = static::getDatabase()->getDocument('created_at', 'uid123'); + $document = $this->getDatabase()->getDocument('created_at', 'uid123'); $this->assertEquals(true, !$document->isEmpty()); sleep(1); $document->setAttribute('title', 'new title'); - static::getDatabase()->updateDocument('created_at', 'uid123', $document); - $document = static::getDatabase()->getDocument('created_at', 'uid123'); + $this->getDatabase()->updateDocument('created_at', 'uid123', $document); + $document = $this->getDatabase()->getDocument('created_at', 'uid123'); $this->assertGreaterThan($document->getCreatedAt(), $document->getUpdatedAt()); $this->expectException(DuplicateException::class); - static::getDatabase()->createCollection('created_at'); + $this->getDatabase()->createCollection('created_at'); } public function testCreateDatetime(): void { - static::getDatabase()->createCollection('datetime'); + $this->getDatabase()->createCollection('datetime'); - $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); - $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); - $doc = static::getDatabase()->createDocument('datetime', new Document([ + $doc = $this->getDatabase()->createDocument('datetime', new Document([ '$id' => ID::custom('id1234'), '$permissions' => [ Permission::read(Role::any()), @@ -4313,13 +4313,13 @@ public function testCreateDatetime(): void $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getCreatedAt()); $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getUpdatedAt()); - $document = static::getDatabase()->getDocument('datetime', 'id1234'); + $document = $this->getDatabase()->getDocument('datetime', 'id1234'); $dateValidator = new DatetimeValidator(); $this->assertEquals(null, $document->getAttribute('date2')); $this->assertEquals(true, $dateValidator->isValid($document->getAttribute('date'))); $this->assertEquals(false, $dateValidator->isValid($document->getAttribute('date2'))); - $documents = static::getDatabase()->find('datetime', [ + $documents = $this->getDatabase()->find('datetime', [ Query::greaterThan('date', '1975-12-06 10:00:00+01:00'), Query::lessThan('date', '2030-12-06 10:00:00-01:00'), ]); @@ -4327,7 +4327,7 @@ public function testCreateDatetime(): void $this->assertEquals(1, count($documents)); $this->expectException(StructureException::class); - static::getDatabase()->createDocument('datetime', new Document([ + $this->getDatabase()->createDocument('datetime', new Document([ '$permissions' => [ Permission::create(Role::any()), Permission::update(Role::any()), @@ -4339,16 +4339,16 @@ public function testCreateDatetime(): void public function testCreateDateTimeAttributeFailure(): void { - static::getDatabase()->createCollection('datetime_fail'); + $this->getDatabase()->createCollection('datetime_fail'); /** Test for FAILURE */ $this->expectException(Exception::class); - static::getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); + $this->getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); } public function testKeywords(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $keywords = $database->getKeywords(); // Collection name tests @@ -4410,7 +4410,7 @@ public function testKeywords(): void $collection = $database->createCollection($collectionName); $this->assertEquals($collectionName, $collection->getId()); - $attribute = static::getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); + $attribute = $this->getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); $this->assertEquals(true, $attribute); $document = new Document([ @@ -4460,7 +4460,7 @@ public function testKeywords(): void public function testWritePermissions(): void { $this->authorization->setRole(Role::any()->toString()); - $database = static::getDatabase(); + $database = $this->getDatabase(); $database->createCollection('animals', permissions: [ Permission::create(Role::any()), @@ -4533,19 +4533,19 @@ public function testWritePermissions(): void public function testNoInvalidKeysWithRelationships(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('species'); - static::getDatabase()->createCollection('creatures'); - static::getDatabase()->createCollection('characterstics'); + $this->getDatabase()->createCollection('species'); + $this->getDatabase()->createCollection('creatures'); + $this->getDatabase()->createCollection('characterstics'); - static::getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('characterstics', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('characterstics', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'species', relatedCollection: 'creatures', type: Database::RELATION_ONE_TO_ONE, @@ -4553,7 +4553,7 @@ public function testNoInvalidKeysWithRelationships(): void id: 'creature', twoWayKey:'species' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'creatures', relatedCollection: 'characterstics', type: Database::RELATION_ONE_TO_ONE, @@ -4562,7 +4562,7 @@ public function testNoInvalidKeysWithRelationships(): void twoWayKey:'creature' ); - $species = static::getDatabase()->createDocument('species', new Document([ + $species = $this->getDatabase()->createDocument('species', new Document([ '$id' => ID::custom('1'), '$permissions' => [ Permission::read(Role::any()), @@ -4584,7 +4584,7 @@ public function testNoInvalidKeysWithRelationships(): void ] ] ])); - static::getDatabase()->updateDocument('species', $species->getId(), new Document([ + $this->getDatabase()->updateDocument('species', $species->getId(), new Document([ '$id' => ID::custom('1'), '$collection' => 'species', 'creature' => [ @@ -4597,33 +4597,33 @@ public function testNoInvalidKeysWithRelationships(): void ] ] ])); - $updatedSpecies = static::getDatabase()->getDocument('species', $species->getId()); + $updatedSpecies = $this->getDatabase()->getDocument('species', $species->getId()); $this->assertEquals($species, $updatedSpecies); } // Relationships public function testOneToOneOneWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('person'); - static::getDatabase()->createCollection('library'); + $this->getDatabase()->createCollection('person'); + $this->getDatabase()->createCollection('library'); - static::getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'person', relatedCollection: 'library', type: Database::RELATION_ONE_TO_ONE ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('person'); + $collection = $this->getDatabase()->getCollection('person'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -4639,14 +4639,14 @@ public function testOneToOneOneWayRelationship(): void } try { - static::getDatabase()->deleteAttribute('person', 'library'); + $this->getDatabase()->deleteAttribute('person', 'library'); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete relationship as an attribute', $e->getMessage()); } // Create document with relationship with nested data - $person1 = static::getDatabase()->createDocument('person', new Document([ + $person1 = $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -4667,24 +4667,24 @@ public function testOneToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'no-library') ); - $person1Document = static::getDatabase()->getDocument('person', 'person1'); + $person1Document = $this->getDatabase()->getDocument('person', 'person1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $person1Document->getAttribute('library')); - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'library1') ); // Update through create - $library10 = static::getDatabase()->createDocument('library', new Document([ + $library10 = $this->getDatabase()->createDocument('library', new Document([ '$id' => 'library10', '$permissions' => [ Permission::read(Role::any()), @@ -4693,7 +4693,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 10', 'area' => 'Area 10', ])); - $person10 = static::getDatabase()->createDocument('person', new Document([ + $person10 = $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person10', '$permissions' => [ Permission::read(Role::any()), @@ -4708,11 +4708,11 @@ public function testOneToOneOneWayRelationship(): void ], ])); $this->assertEquals('Library 10 Updated', $person10->getAttribute('library')->getAttribute('name')); - $library10 = static::getDatabase()->getDocument('library', $library10->getId()); + $library10 = $this->getDatabase()->getDocument('library', $library10->getId()); $this->assertEquals('Library 10 Updated', $library10->getAttribute('name')); // Create document with relationship with related ID - static::getDatabase()->createDocument('library', new Document([ + $this->getDatabase()->createDocument('library', new Document([ '$id' => 'library2', '$permissions' => [ Permission::read(Role::any()), @@ -4721,7 +4721,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 2', 'area' => 'Area 2', ])); - static::getDatabase()->createDocument('person', new Document([ + $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person2', '$permissions' => [ Permission::read(Role::any()), @@ -4733,34 +4733,34 @@ public function testOneToOneOneWayRelationship(): void ])); // Get documents with relationship - $person1 = static::getDatabase()->getDocument('person', 'person1'); + $person1 = $this->getDatabase()->getDocument('person', 'person1'); $library = $person1->getAttribute('library'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('person', $library); - $person = static::getDatabase()->getDocument('person', 'person2'); + $person = $this->getDatabase()->getDocument('person', 'person2'); $library = $person->getAttribute('library'); $this->assertEquals('library2', $library['$id']); $this->assertArrayNotHasKey('person', $library); // Get related documents - $library = static::getDatabase()->getDocument('library', 'library1'); + $library = $this->getDatabase()->getDocument('library', 'library1'); $this->assertArrayNotHasKey('person', $library); - $library = static::getDatabase()->getDocument('library', 'library2'); + $library = $this->getDatabase()->getDocument('library', 'library2'); $this->assertArrayNotHasKey('person', $library); - $people = static::getDatabase()->find('person', [ + $people = $this->getDatabase()->find('person', [ Query::select(['name']) ]); $this->assertArrayNotHasKey('library', $people[0]); - $people = static::getDatabase()->find('person'); + $people = $this->getDatabase()->find('person'); $this->assertEquals(3, \count($people)); // Select related document attributes - $person = static::getDatabase()->findOne('person', [ + $person = $this->getDatabase()->findOne('person', [ Query::select(['*', 'library.name']) ]); @@ -4771,7 +4771,7 @@ public function testOneToOneOneWayRelationship(): void $this->assertEquals('Library 1', $person->getAttribute('library')->getAttribute('name')); $this->assertArrayNotHasKey('area', $person->getAttribute('library')); - $person = static::getDatabase()->getDocument('person', 'person1', [ + $person = $this->getDatabase()->getDocument('person', 'person1', [ Query::select(['*', 'library.name', '$id']) ]); @@ -4780,36 +4780,36 @@ public function testOneToOneOneWayRelationship(): void - $document = static::getDatabase()->getDocument('person', $person->getId(), [ + $document = $this->getDatabase()->getDocument('person', $person->getId(), [ Query::select(['name']), ]); $this->assertArrayNotHasKey('library', $document); $this->assertEquals('Person 1', $document['name']); - $document = static::getDatabase()->getDocument('person', $person->getId(), [ + $document = $this->getDatabase()->getDocument('person', $person->getId(), [ Query::select(['*']), ]); $this->assertEquals('library1', $document['library']); - $document = static::getDatabase()->getDocument('person', $person->getId(), [ + $document = $this->getDatabase()->getDocument('person', $person->getId(), [ Query::select(['library.*']), ]); $this->assertEquals('Library 1', $document['library']['name']); $this->assertArrayNotHasKey('name', $document); // Update root document attribute without altering relationship - $person1 = static::getDatabase()->updateDocument( + $person1 = $this->getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('name', 'Person 1 Updated') ); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); - $person1 = static::getDatabase()->getDocument('person', 'person1'); + $person1 = $this->getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); // Update nested document attribute - $person1 = static::getDatabase()->updateDocument( + $person1 = $this->getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute( @@ -4821,11 +4821,11 @@ public function testOneToOneOneWayRelationship(): void ); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); - $person1 = static::getDatabase()->getDocument('person', 'person1'); + $person1 = $this->getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); // Create new document with no relationship - $person3 = static::getDatabase()->createDocument('person', new Document([ + $person3 = $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person3', '$permissions' => [ Permission::read(Role::any()), @@ -4836,7 +4836,7 @@ public function testOneToOneOneWayRelationship(): void ])); // Update to relate to created document - $person3 = static::getDatabase()->updateDocument( + $person3 = $this->getDatabase()->updateDocument( 'person', $person3->getId(), $person3->setAttribute('library', new Document([ @@ -4851,23 +4851,23 @@ public function testOneToOneOneWayRelationship(): void ); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); - $person3 = static::getDatabase()->getDocument('person', 'person3'); + $person3 = $this->getDatabase()->getDocument('person', 'person3'); $this->assertEquals('Library 3', $person3['library']['name']); - $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); + $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); $libraryDocument->setAttribute('name', 'Library 3 updated'); - static::getDatabase()->updateDocument('library', 'library3', $libraryDocument); - $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); + $this->getDatabase()->updateDocument('library', 'library3', $libraryDocument); + $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); $this->assertEquals('Library 3 updated', $libraryDocument['name']); - $person3 = static::getDatabase()->getDocument('person', 'person3'); + $person3 = $this->getDatabase()->getDocument('person', 'person3'); // Todo: This is failing $this->assertEquals($libraryDocument['name'], $person3['library']['name']); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library2') @@ -4878,7 +4878,7 @@ public function testOneToOneOneWayRelationship(): void } // Create new document - $library4 = static::getDatabase()->createDocument('library', new Document([ + $library4 = $this->getDatabase()->createDocument('library', new Document([ '$id' => 'library4', '$permissions' => [ Permission::read(Role::any()), @@ -4889,33 +4889,33 @@ public function testOneToOneOneWayRelationship(): void ])); // Relate existing document to new document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library4') ); // Relate existing document to new document as nested data - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', $library4) ); // Rename relationship key - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'person', id: 'library', newKey: 'newLibrary' ); // Get document with again - $person = static::getDatabase()->getDocument('person', 'person1'); + $person = $this->getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary'); $this->assertEquals('library4', $library['$id']); // Create person with no relationship - static::getDatabase()->createDocument('person', new Document([ + $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person4', '$permissions' => [ Permission::read(Role::any()), @@ -4926,22 +4926,22 @@ public function testOneToOneOneWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = static::getDatabase()->deleteDocument('person', 'person4'); + $deleted = $this->getDatabase()->deleteDocument('person', 'person4'); $this->assertEquals(true, $deleted); - $person4 = static::getDatabase()->getDocument('person', 'person4'); + $person4 = $this->getDatabase()->getDocument('person', 'person4'); $this->assertEquals(true, $person4->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - static::getDatabase()->deleteDocument('person', 'person1'); + $this->getDatabase()->deleteDocument('person', 'person1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Can delete child document while still related to another with on delete set to restrict - $person5 = static::getDatabase()->createDocument('person', new Document([ + $person5 = $this->getDatabase()->createDocument('person', new Document([ '$id' => 'person5', '$permissions' => [ Permission::read(Role::any()), @@ -4959,60 +4959,60 @@ public function testOneToOneOneWayRelationship(): void 'area' => 'Area 5', ], ])); - $deleted = static::getDatabase()->deleteDocument('library', 'library5'); + $deleted = $this->getDatabase()->deleteDocument('library', 'library5'); $this->assertEquals(true, $deleted); - $person5 = static::getDatabase()->getDocument('person', 'person5'); + $person5 = $this->getDatabase()->getDocument('person', 'person5'); $this->assertEquals(null, $person5->getAttribute('newLibrary')); // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, no effect on children for one-way - static::getDatabase()->deleteDocument('person', 'person1'); + $this->getDatabase()->deleteDocument('person', 'person1'); // Delete child, set parent relating attribute to null for one-way - static::getDatabase()->deleteDocument('library', 'library2'); + $this->getDatabase()->deleteDocument('library', 'library2'); // Check relation was set to null - $person2 = static::getDatabase()->getDocument('person', 'person2'); + $person2 = $this->getDatabase()->getDocument('person', 'person2'); $this->assertEquals(null, $person2->getAttribute('newLibrary', '')); // Relate to another document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'person', $person2->getId(), $person2->setAttribute('newLibrary', 'library4') ); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('person', 'person2'); + $this->getDatabase()->deleteDocument('person', 'person2'); // Check parent and child were deleted - $person = static::getDatabase()->getDocument('person', 'person2'); + $person = $this->getDatabase()->getDocument('person', 'person2'); $this->assertEquals(true, $person->isEmpty()); - $library = static::getDatabase()->getDocument('library', 'library4'); + $library = $this->getDatabase()->getDocument('library', 'library4'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'person', 'newLibrary' ); // Check parent doesn't have relationship anymore - $person = static::getDatabase()->getDocument('person', 'person1'); + $person = $this->getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary', ''); $this->assertEquals(null, $library); } @@ -5026,26 +5026,26 @@ public function testOneToOneOneWayRelationship(): void */ public function testOneToOneTwoWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('country'); - static::getDatabase()->createCollection('city'); + $this->getDatabase()->createCollection('country'); + $this->getDatabase()->createCollection('city'); - static::getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); - static::getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); + $this->getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'country', relatedCollection: 'city', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $collection = static::getDatabase()->getCollection('country'); + $collection = $this->getDatabase()->getCollection('country'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'city') { @@ -5059,7 +5059,7 @@ public function testOneToOneTwoWayRelationship(): void } } - $collection = static::getDatabase()->getCollection('city'); + $collection = $this->getDatabase()->getCollection('city'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'country') { @@ -5094,40 +5094,40 @@ public function testOneToOneTwoWayRelationship(): void ], ]); - static::getDatabase()->createDocument('country', $doc); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $this->getDatabase()->createDocument('country', $doc); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); + $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); - $country1Document = static::getDatabase()->getDocument('country', 'country1'); + $country1Document = $this->getDatabase()->getDocument('country', 'country1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $country1Document->getAttribute('city')); - static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); + $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); try { - static::getDatabase()->deleteDocument('country', 'country1'); + $this->getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertInstanceOf(RestrictedException::class, $e); } - $this->assertTrue(static::getDatabase()->deleteDocument('city', 'city1')); + $this->assertTrue($this->getDatabase()->deleteDocument('city', 'city1')); - $city1 = static::getDatabase()->getDocument('city', 'city1'); + $city1 = $this->getDatabase()->getDocument('city', 'city1'); $this->assertTrue($city1->isEmpty()); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); $this->assertTrue($country1->getAttribute('city')->isEmpty()); - $this->assertTrue(static::getDatabase()->deleteDocument('country', 'country1')); + $this->assertTrue($this->getDatabase()->deleteDocument('country', 'country1')); - static::getDatabase()->createDocument('country', $doc); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $this->getDatabase()->createDocument('country', $doc); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Create document with relationship with related ID - static::getDatabase()->createDocument('city', new Document([ + $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city2', '$permissions' => [ Permission::read(Role::any()), @@ -5137,7 +5137,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'Paris', 'code' => 'PAR', ])); - static::getDatabase()->createDocument('country', new Document([ + $this->getDatabase()->createDocument('country', new Document([ '$id' => 'country2', '$permissions' => [ Permission::read(Role::any()), @@ -5149,7 +5149,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Create from child side - static::getDatabase()->createDocument('city', new Document([ + $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city3', '$permissions' => [ Permission::read(Role::any()), @@ -5168,7 +5168,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'New Zealand', ], ])); - static::getDatabase()->createDocument('country', new Document([ + $this->getDatabase()->createDocument('country', new Document([ '$id' => 'country4', '$permissions' => [ Permission::read(Role::any()), @@ -5177,7 +5177,7 @@ public function testOneToOneTwoWayRelationship(): void ], 'name' => 'Australia', ])); - static::getDatabase()->createDocument('city', new Document([ + $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city4', '$permissions' => [ Permission::read(Role::any()), @@ -5190,53 +5190,53 @@ public function testOneToOneTwoWayRelationship(): void ])); // Get document with relationship - $city = static::getDatabase()->getDocument('city', 'city1'); + $city = $this->getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('country'); $this->assertEquals('country1', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = static::getDatabase()->getDocument('city', 'city2'); + $city = $this->getDatabase()->getDocument('city', 'city2'); $country = $city->getAttribute('country'); $this->assertEquals('country2', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = static::getDatabase()->getDocument('city', 'city3'); + $city = $this->getDatabase()->getDocument('city', 'city3'); $country = $city->getAttribute('country'); $this->assertEquals('country3', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = static::getDatabase()->getDocument('city', 'city4'); + $city = $this->getDatabase()->getDocument('city', 'city4'); $country = $city->getAttribute('country'); $this->assertEquals('country4', $country['$id']); $this->assertArrayNotHasKey('city', $country); // Get inverse document with relationship - $country = static::getDatabase()->getDocument('country', 'country1'); + $country = $this->getDatabase()->getDocument('country', 'country1'); $city = $country->getAttribute('city'); $this->assertEquals('city1', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = static::getDatabase()->getDocument('country', 'country2'); + $country = $this->getDatabase()->getDocument('country', 'country2'); $city = $country->getAttribute('city'); $this->assertEquals('city2', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = static::getDatabase()->getDocument('country', 'country3'); + $country = $this->getDatabase()->getDocument('country', 'country3'); $city = $country->getAttribute('city'); $this->assertEquals('city3', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = static::getDatabase()->getDocument('country', 'country4'); + $country = $this->getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('city'); $this->assertEquals('city4', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $countries = static::getDatabase()->find('country'); + $countries = $this->getDatabase()->find('country'); $this->assertEquals(4, \count($countries)); // Select related document attributes - $country = static::getDatabase()->findOne('country', [ + $country = $this->getDatabase()->findOne('country', [ Query::select(['*', 'city.name']) ]); @@ -5247,41 +5247,41 @@ public function testOneToOneTwoWayRelationship(): void $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country = static::getDatabase()->getDocument('country', 'country1', [ + $country = $this->getDatabase()->getDocument('country', 'country1', [ Query::select(['*', 'city.name']) ]); $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); // Update root document attribute without altering relationship - $country1 = static::getDatabase()->updateDocument( + $country1 = $this->getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('name', 'Country 1 Updated') ); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $city2 = static::getDatabase()->getDocument('city', 'city2'); + $city2 = $this->getDatabase()->getDocument('city', 'city2'); // Update inverse root document attribute without altering relationship - $city2 = static::getDatabase()->updateDocument( + $city2 = $this->getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute('name', 'City 2 Updated') ); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); - $city2 = static::getDatabase()->getDocument('city', 'city2'); + $city2 = $this->getDatabase()->getDocument('city', 'city2'); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); // Update nested document attribute - $country1 = static::getDatabase()->updateDocument( + $country1 = $this->getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute( @@ -5293,11 +5293,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); - $country1 = static::getDatabase()->getDocument('country', 'country1'); + $country1 = $this->getDatabase()->getDocument('country', 'country1'); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); // Update inverse nested document attribute - $city2 = static::getDatabase()->updateDocument( + $city2 = $this->getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute( @@ -5309,11 +5309,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); - $city2 = static::getDatabase()->getDocument('city', 'city2'); + $city2 = $this->getDatabase()->getDocument('city', 'city2'); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); // Create new document with no relationship - $country5 = static::getDatabase()->createDocument('country', new Document([ + $country5 = $this->getDatabase()->createDocument('country', new Document([ '$id' => 'country5', '$permissions' => [ Permission::read(Role::any()), @@ -5324,7 +5324,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $country5 = static::getDatabase()->updateDocument( + $country5 = $this->getDatabase()->updateDocument( 'country', $country5->getId(), $country5->setAttribute('city', new Document([ @@ -5339,11 +5339,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); - $country5 = static::getDatabase()->getDocument('country', 'country5'); + $country5 = $this->getDatabase()->getDocument('country', 'country5'); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); // Create new document with no relationship - $city6 = static::getDatabase()->createDocument('city', new Document([ + $city6 = $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city6', '$permissions' => [ Permission::read(Role::any()), @@ -5355,7 +5355,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $city6 = static::getDatabase()->updateDocument( + $city6 = $this->getDatabase()->updateDocument( 'city', $city6->getId(), $city6->setAttribute('country', new Document([ @@ -5369,12 +5369,12 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); - $city6 = static::getDatabase()->getDocument('city', 'city6'); + $city6 = $this->getDatabase()->getDocument('city', 'city6'); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city2') @@ -5384,21 +5384,21 @@ public function testOneToOneTwoWayRelationship(): void $this->assertInstanceOf(DuplicateException::class, $e); } - $city1 = static::getDatabase()->getDocument('city', 'city1'); + $city1 = $this->getDatabase()->getDocument('city', 'city1'); // Set relationship to null - $city1 = static::getDatabase()->updateDocument( + $city1 = $this->getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', null) ); $this->assertEquals(null, $city1->getAttribute('country')); - $city1 = static::getDatabase()->getDocument('city', 'city1'); + $city1 = $this->getDatabase()->getDocument('city', 'city1'); $this->assertEquals(null, $city1->getAttribute('country')); // Create a new city with no relation - $city7 = static::getDatabase()->createDocument('city', new Document([ + $city7 = $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -5410,21 +5410,21 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update document with relation to new document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city7') ); // Relate existing document to new document as nested data - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', $city7) ); // Create a new country with no relation - static::getDatabase()->createDocument('country', new Document([ + $this->getDatabase()->createDocument('country', new Document([ '$id' => 'country7', '$permissions' => [ Permission::read(Role::any()), @@ -5435,14 +5435,14 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update inverse document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', 'country7') ); // Rename relationship keys on both sides - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'country', 'city', 'newCity', @@ -5450,17 +5450,17 @@ public function testOneToOneTwoWayRelationship(): void ); // Get document with new relationship key - $city = static::getDatabase()->getDocument('city', 'city1'); + $city = $this->getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('newCountry'); $this->assertEquals('country7', $country['$id']); // Get inverse document with new relationship key - $country = static::getDatabase()->getDocument('country', 'country7'); + $country = $this->getDatabase()->getDocument('country', 'country7'); $city = $country->getAttribute('newCity'); $this->assertEquals('city1', $city['$id']); // Create a new country with no relation - static::getDatabase()->createDocument('country', new Document([ + $this->getDatabase()->createDocument('country', new Document([ '$id' => 'country8', '$permissions' => [ Permission::read(Role::any()), @@ -5471,78 +5471,78 @@ public function testOneToOneTwoWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = static::getDatabase()->deleteDocument('country', 'country8'); + $deleted = $this->getDatabase()->deleteDocument('country', 'country8'); $this->assertEquals(1, $deleted); - $country8 = static::getDatabase()->getDocument('country', 'country8'); + $country8 = $this->getDatabase()->getDocument('country', 'country8'); $this->assertEquals(true, $country8->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - static::getDatabase()->deleteDocument('country', 'country1'); + $this->getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, will set child relationship to null for two-way - static::getDatabase()->deleteDocument('country', 'country1'); + $this->getDatabase()->deleteDocument('country', 'country1'); // Check relation was set to null - $city7 = static::getDatabase()->getDocument('city', 'city7'); + $city7 = $this->getDatabase()->getDocument('city', 'city7'); $this->assertEquals(null, $city7->getAttribute('country', '')); // Delete child, set parent relationship to null for two-way - static::getDatabase()->deleteDocument('city', 'city2'); + $this->getDatabase()->deleteDocument('city', 'city2'); // Check relation was set to null - $country2 = static::getDatabase()->getDocument('country', 'country2'); + $country2 = $this->getDatabase()->getDocument('country', 'country2'); $this->assertEquals(null, $country2->getAttribute('city', '')); // Relate again - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'city', $city7->getId(), $city7->setAttribute('newCountry', 'country2') ); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('country', 'country7'); + $this->getDatabase()->deleteDocument('country', 'country7'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('country', 'country7'); + $library = $this->getDatabase()->getDocument('country', 'country7'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('city', 'city1'); + $library = $this->getDatabase()->getDocument('city', 'city1'); $this->assertEquals(true, $library->isEmpty()); // Delete child, will delete parent for two-way - static::getDatabase()->deleteDocument('city', 'city7'); + $this->getDatabase()->deleteDocument('city', 'city7'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('city', 'city7'); + $library = $this->getDatabase()->getDocument('city', 'city7'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('country', 'country2'); + $library = $this->getDatabase()->getDocument('country', 'country2'); $this->assertEquals(true, $library->isEmpty()); // Create new document to check after deleting relationship - static::getDatabase()->createDocument('city', new Document([ + $this->getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -5558,33 +5558,33 @@ public function testOneToOneTwoWayRelationship(): void ])); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'country', 'newCity' ); // Try to get document again - $country = static::getDatabase()->getDocument('country', 'country4'); + $country = $this->getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('newCity'); $this->assertEquals(null, $city); // Try to get inverse document again - $city = static::getDatabase()->getDocument('city', 'city7'); + $city = $this->getDatabase()->getDocument('city', 'city7'); $country = $city->getAttribute('newCountry'); $this->assertEquals(null, $country); } public function testIdenticalTwoWayKeyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('parent'); - static::getDatabase()->createCollection('child'); + $this->getDatabase()->createCollection('parent'); + $this->getDatabase()->createCollection('child'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_ONE, @@ -5592,7 +5592,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ); try { - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -5603,7 +5603,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('Related attribute already exists', $e->getMessage()); } - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -5611,7 +5611,7 @@ public function testIdenticalTwoWayKeyRelationship(): void twoWayKey: 'parent_id' ); - $collection = static::getDatabase()->getCollection('parent'); + $collection = $this->getDatabase()->getCollection('parent'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'child1') { @@ -5623,7 +5623,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } } - static::getDatabase()->createDocument('parent', new Document([ + $this->getDatabase()->createDocument('parent', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -5641,7 +5641,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ], ])); - $documents = static::getDatabase()->find('parent', []); + $documents = $this->getDatabase()->find('parent', []); $document = array_pop($documents); $this->assertArrayHasKey('child1', $document); $this->assertEquals('foo', $document->getAttribute('child1')->getId()); @@ -5649,7 +5649,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('bar', $document->getAttribute('children')[0]->getId()); try { - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'parent', id: 'children', newKey: 'child1' @@ -5660,7 +5660,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } try { - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'parent', id: 'children', newTwoWayKey: 'parent' @@ -5673,19 +5673,19 @@ public function testIdenticalTwoWayKeyRelationship(): void public function testOneToManyOneWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('artist'); - static::getDatabase()->createCollection('album'); + $this->getDatabase()->createCollection('artist'); + $this->getDatabase()->createCollection('album'); - static::getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); + $this->getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'artist', relatedCollection: 'album', type: Database::RELATION_ONE_TO_MANY, @@ -5693,7 +5693,7 @@ public function testOneToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('artist'); + $collection = $this->getDatabase()->getCollection('artist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -5709,7 +5709,7 @@ public function testOneToManyOneWayRelationship(): void } // Create document with relationship with nested data - $artist1 = static::getDatabase()->createDocument('artist', new Document([ + $artist1 = $this->getDatabase()->createDocument('artist', new Document([ '$id' => 'artist1', '$permissions' => [ Permission::read(Role::any()), @@ -5731,14 +5731,14 @@ public function testOneToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); + $this->getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); - $artist1Document = static::getDatabase()->getDocument('artist', 'artist1'); + $artist1Document = $this->getDatabase()->getDocument('artist', 'artist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($artist1Document->getAttribute('albums'))); // Create document with relationship with related ID - static::getDatabase()->createDocument('album', new Document([ + $this->getDatabase()->createDocument('album', new Document([ '$id' => 'album2', '$permissions' => [ Permission::read(Role::any()), @@ -5748,7 +5748,7 @@ public function testOneToManyOneWayRelationship(): void 'name' => 'Album 2', 'price' => 19.99, ])); - static::getDatabase()->createDocument('artist', new Document([ + $this->getDatabase()->createDocument('artist', new Document([ '$id' => 'artist2', '$permissions' => [ Permission::read(Role::any()), @@ -5770,19 +5770,19 @@ public function testOneToManyOneWayRelationship(): void ] ])); - $documents = static::getDatabase()->find('artist', [ + $documents = $this->getDatabase()->find('artist', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayNotHasKey('albums', $documents[0]); // Get document with relationship - $artist = static::getDatabase()->getDocument('artist', 'artist1'); + $artist = $this->getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album1', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); - $artist = static::getDatabase()->getDocument('artist', 'artist2'); + $artist = $this->getDatabase()->getDocument('artist', 'artist2'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album2', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); @@ -5790,18 +5790,18 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(2, $albums); // Get related document - $album = static::getDatabase()->getDocument('album', 'album1'); + $album = $this->getDatabase()->getDocument('album', 'album1'); $this->assertArrayNotHasKey('artist', $album); - $album = static::getDatabase()->getDocument('album', 'album2'); + $album = $this->getDatabase()->getDocument('album', 'album2'); $this->assertArrayNotHasKey('artist', $album); - $artists = static::getDatabase()->find('artist'); + $artists = $this->getDatabase()->find('artist'); $this->assertEquals(2, \count($artists)); // Select related document attributes - $artist = static::getDatabase()->findOne('artist', [ + $artist = $this->getDatabase()->findOne('artist', [ Query::select(['*', 'albums.name']) ]); @@ -5812,7 +5812,7 @@ public function testOneToManyOneWayRelationship(): void $this->assertEquals('Album 1', $artist->getAttribute('albums')[0]->getAttribute('name')); $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); - $artist = static::getDatabase()->getDocument('artist', 'artist1', [ + $artist = $this->getDatabase()->getDocument('artist', 'artist1', [ Query::select(['*', 'albums.name']) ]); @@ -5820,36 +5820,36 @@ public function testOneToManyOneWayRelationship(): void $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); // Update root document attribute without altering relationship - $artist1 = static::getDatabase()->updateDocument( + $artist1 = $this->getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('name', 'Artist 1 Updated') ); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); - $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); + $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); // Update nested document attribute $albums = $artist1->getAttribute('albums', []); $albums[0]->setAttribute('name', 'Album 1 Updated'); - $artist1 = static::getDatabase()->updateDocument( + $artist1 = $this->getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', $albums) ); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); - $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); + $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); $albumId = $artist1->getAttribute('albums')[0]->getAttribute('$id'); - $albumDocument = static::getDatabase()->getDocument('album', $albumId); + $albumDocument = $this->getDatabase()->getDocument('album', $albumId); $albumDocument->setAttribute('name', 'Album 1 Updated!!!'); - static::getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); - $albumDocument = static::getDatabase()->getDocument('album', $albumDocument->getId()); - $artist1 = static::getDatabase()->getDocument('artist', $artist1->getId()); + $this->getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); + $albumDocument = $this->getDatabase()->getDocument('album', $albumDocument->getId()); + $artist1 = $this->getDatabase()->getDocument('artist', $artist1->getId()); $this->assertEquals('Album 1 Updated!!!', $albumDocument['name']); $this->assertEquals($albumDocument->getId(), $artist1->getAttribute('albums')[0]->getId()); @@ -5857,7 +5857,7 @@ public function testOneToManyOneWayRelationship(): void $this->assertEquals($albumDocument->getAttribute('name'), $artist1->getAttribute('albums')[0]->getAttribute('name')); // Create new document with no relationship - $artist3 = static::getDatabase()->createDocument('artist', new Document([ + $artist3 = $this->getDatabase()->createDocument('artist', new Document([ '$id' => 'artist3', '$permissions' => [ Permission::read(Role::any()), @@ -5868,7 +5868,7 @@ public function testOneToManyOneWayRelationship(): void ])); // Update to relate to created document - $artist3 = static::getDatabase()->updateDocument( + $artist3 = $this->getDatabase()->updateDocument( 'artist', $artist3->getId(), $artist3->setAttribute('albums', [new Document([ @@ -5884,37 +5884,37 @@ public function testOneToManyOneWayRelationship(): void ); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); - $artist3 = static::getDatabase()->getDocument('artist', 'artist3'); + $artist3 = $this->getDatabase()->getDocument('artist', 'artist3'); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); // Update document with new related documents, will remove existing relations - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album2']) ); // Update document with new related documents, will remove existing relations - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album1', 'album2']) ); // Rename relationship key - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'artist', 'albums', 'newAlbums' ); // Get document with new relationship key - $artist = static::getDatabase()->getDocument('artist', 'artist1'); + $artist = $this->getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums'); $this->assertEquals('album1', $albums[0]['$id']); // Create new document with no relationship - static::getDatabase()->createDocument('artist', new Document([ + $this->getDatabase()->createDocument('artist', new Document([ '$id' => 'artist4', '$permissions' => [ Permission::read(Role::any()), @@ -5925,56 +5925,56 @@ public function testOneToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('artist', 'artist4'); + $deleted = $this->getDatabase()->deleteDocument('artist', 'artist4'); $this->assertEquals(true, $deleted); - $artist4 = static::getDatabase()->getDocument('artist', 'artist4'); + $artist4 = $this->getDatabase()->getDocument('artist', 'artist4'); $this->assertEquals(true, $artist4->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('artist', 'artist1'); + $this->getDatabase()->deleteDocument('artist', 'artist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - static::getDatabase()->deleteDocument('artist', 'artist1'); + $this->getDatabase()->deleteDocument('artist', 'artist1'); // Check relation was set to null - $album2 = static::getDatabase()->getDocument('album', 'album2'); + $album2 = $this->getDatabase()->getDocument('album', 'album2'); $this->assertEquals(null, $album2->getAttribute('artist', '')); // Relate again - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'album', $album2->getId(), $album2->setAttribute('artist', 'artist2') ); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('artist', 'artist2'); + $this->getDatabase()->deleteDocument('artist', 'artist2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('artist', 'artist2'); + $library = $this->getDatabase()->getDocument('artist', 'artist2'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('album', 'album2'); + $library = $this->getDatabase()->getDocument('album', 'album2'); $this->assertEquals(true, $library->isEmpty()); $albums = []; @@ -5991,7 +5991,7 @@ public function testOneToManyOneWayRelationship(): void ]; } - $artist = static::getDatabase()->createDocument('artist', new Document([ + $artist = $this->getDatabase()->createDocument('artist', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::delete(Role::any()), @@ -6000,29 +6000,29 @@ public function testOneToManyOneWayRelationship(): void 'newAlbums' => $albums ])); - $artist = static::getDatabase()->getDocument('artist', $artist->getId()); + $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(50, $artist->getAttribute('newAlbums')); - $albums = static::getDatabase()->find('album', [ + $albums = $this->getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); $this->assertCount(50, $albums); - $count = static::getDatabase()->count('album', [ + $count = $this->getDatabase()->count('album', [ Query::equal('artist', [$artist->getId()]), ]); $this->assertEquals(50, $count); - static::getDatabase()->deleteDocument('album', 'album_1'); - $artist = static::getDatabase()->getDocument('artist', $artist->getId()); + $this->getDatabase()->deleteDocument('album', 'album_1'); + $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(49, $artist->getAttribute('newAlbums')); - static::getDatabase()->deleteDocument('artist', $artist->getId()); + $this->getDatabase()->deleteDocument('artist', $artist->getId()); - $albums = static::getDatabase()->find('album', [ + $albums = $this->getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); @@ -6030,32 +6030,32 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(0, $albums); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'artist', 'newAlbums' ); // Try to get document again - $artist = static::getDatabase()->getDocument('artist', 'artist1'); + $artist = $this->getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums', ''); $this->assertEquals(null, $albums); } public function testOneToManyTwoWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('customer'); - static::getDatabase()->createCollection('account'); + $this->getDatabase()->createCollection('customer'); + $this->getDatabase()->createCollection('account'); - static::getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'customer', relatedCollection: 'account', type: Database::RELATION_ONE_TO_MANY, @@ -6064,7 +6064,7 @@ public function testOneToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('customer'); + $collection = $this->getDatabase()->getCollection('customer'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'accounts') { @@ -6079,7 +6079,7 @@ public function testOneToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = static::getDatabase()->getCollection('account'); + $collection = $this->getDatabase()->getCollection('account'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'customer') { @@ -6094,7 +6094,7 @@ public function testOneToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $customer1 = static::getDatabase()->createDocument('customer', new Document([ + $customer1 = $this->getDatabase()->createDocument('customer', new Document([ '$id' => 'customer1', '$permissions' => [ Permission::read(Role::any()), @@ -6117,14 +6117,14 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); + $this->getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); - $customer1Document = static::getDatabase()->getDocument('customer', 'customer1'); + $customer1Document = $this->getDatabase()->getDocument('customer', 'customer1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($customer1Document->getAttribute('accounts'))); // Create document with relationship with related ID - $account2 = static::getDatabase()->createDocument('account', new Document([ + $account2 = $this->getDatabase()->createDocument('account', new Document([ '$id' => 'account2', '$permissions' => [ Permission::read(Role::any()), @@ -6134,7 +6134,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Account 2', 'number' => '987654321', ])); - static::getDatabase()->createDocument('customer', new Document([ + $this->getDatabase()->createDocument('customer', new Document([ '$id' => 'customer2', '$permissions' => [ Permission::read(Role::any()), @@ -6148,7 +6148,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Create from child side - static::getDatabase()->createDocument('account', new Document([ + $this->getDatabase()->createDocument('account', new Document([ '$id' => 'account3', '$permissions' => [ Permission::read(Role::any()), @@ -6167,7 +6167,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Customer 3' ] ])); - static::getDatabase()->createDocument('customer', new Document([ + $this->getDatabase()->createDocument('customer', new Document([ '$id' => 'customer4', '$permissions' => [ Permission::read(Role::any()), @@ -6176,7 +6176,7 @@ public function testOneToManyTwoWayRelationship(): void ], 'name' => 'Customer 4', ])); - static::getDatabase()->createDocument('account', new Document([ + $this->getDatabase()->createDocument('account', new Document([ '$id' => 'account4', '$permissions' => [ Permission::read(Role::any()), @@ -6189,53 +6189,53 @@ public function testOneToManyTwoWayRelationship(): void ])); // Get documents with relationship - $customer = static::getDatabase()->getDocument('customer', 'customer1'); + $customer = $this->getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account1', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = static::getDatabase()->getDocument('customer', 'customer2'); + $customer = $this->getDatabase()->getDocument('customer', 'customer2'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account2', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = static::getDatabase()->getDocument('customer', 'customer3'); + $customer = $this->getDatabase()->getDocument('customer', 'customer3'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account3', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = static::getDatabase()->getDocument('customer', 'customer4'); + $customer = $this->getDatabase()->getDocument('customer', 'customer4'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account4', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); // Get related documents - $account = static::getDatabase()->getDocument('account', 'account1'); + $account = $this->getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer1', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = static::getDatabase()->getDocument('account', 'account2'); + $account = $this->getDatabase()->getDocument('account', 'account2'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer2', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = static::getDatabase()->getDocument('account', 'account3'); + $account = $this->getDatabase()->getDocument('account', 'account3'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer3', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = static::getDatabase()->getDocument('account', 'account4'); + $account = $this->getDatabase()->getDocument('account', 'account4'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer4', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $customers = static::getDatabase()->find('customer'); + $customers = $this->getDatabase()->find('customer'); $this->assertEquals(4, \count($customers)); // Select related document attributes - $customer = static::getDatabase()->findOne('customer', [ + $customer = $this->getDatabase()->findOne('customer', [ Query::select(['*', 'accounts.name']) ]); @@ -6246,7 +6246,7 @@ public function testOneToManyTwoWayRelationship(): void $this->assertEquals('Account 1', $customer->getAttribute('accounts')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); - $customer = static::getDatabase()->getDocument('customer', 'customer1', [ + $customer = $this->getDatabase()->getDocument('customer', 'customer1', [ Query::select(['*', 'accounts.name']) ]); @@ -6254,45 +6254,45 @@ public function testOneToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); // Update root document attribute without altering relationship - $customer1 = static::getDatabase()->updateDocument( + $customer1 = $this->getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('name', 'Customer 1 Updated') ); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); + $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $account2 = static::getDatabase()->getDocument('account', 'account2'); + $account2 = $this->getDatabase()->getDocument('account', 'account2'); // Update inverse root document attribute without altering relationship - $account2 = static::getDatabase()->updateDocument( + $account2 = $this->getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('name', 'Account 2 Updated') ); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); - $account2 = static::getDatabase()->getDocument('account', 'account2'); + $account2 = $this->getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); // Update nested document attribute $accounts = $customer1->getAttribute('accounts', []); $accounts[0]->setAttribute('name', 'Account 1 Updated'); - $customer1 = static::getDatabase()->updateDocument( + $customer1 = $this->getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', $accounts) ); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); - $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); + $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); // Update inverse nested document attribute - $account2 = static::getDatabase()->updateDocument( + $account2 = $this->getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute( @@ -6304,11 +6304,11 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); - $account2 = static::getDatabase()->getDocument('account', 'account2'); + $account2 = $this->getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); // Create new document with no relationship - $customer5 = static::getDatabase()->createDocument('customer', new Document([ + $customer5 = $this->getDatabase()->createDocument('customer', new Document([ '$id' => 'customer5', '$permissions' => [ Permission::read(Role::any()), @@ -6319,7 +6319,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update to relate to created document - $customer5 = static::getDatabase()->updateDocument( + $customer5 = $this->getDatabase()->updateDocument( 'customer', $customer5->getId(), $customer5->setAttribute('accounts', [new Document([ @@ -6335,11 +6335,11 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); - $customer5 = static::getDatabase()->getDocument('customer', 'customer5'); + $customer5 = $this->getDatabase()->getDocument('customer', 'customer5'); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); // Create new child document with no relationship - $account6 = static::getDatabase()->createDocument('account', new Document([ + $account6 = $this->getDatabase()->createDocument('account', new Document([ '$id' => 'account6', '$permissions' => [ Permission::read(Role::any()), @@ -6351,7 +6351,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update inverse to relate to created document - $account6 = static::getDatabase()->updateDocument( + $account6 = $this->getDatabase()->updateDocument( 'account', $account6->getId(), $account6->setAttribute('customer', new Document([ @@ -6366,32 +6366,32 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); - $account6 = static::getDatabase()->getDocument('account', 'account6'); + $account6 = $this->getDatabase()->getDocument('account', 'account6'); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); // Update document with new related document, will remove existing relations - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account2']) ); // Update document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account1', 'account2']) ); // Update inverse document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('customer', 'customer2') ); // Rename relationship keys on both sides - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'customer', 'accounts', 'newAccounts', @@ -6399,17 +6399,17 @@ public function testOneToManyTwoWayRelationship(): void ); // Get document with new relationship key - $customer = static::getDatabase()->getDocument('customer', 'customer1'); + $customer = $this->getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals('account1', $accounts[0]['$id']); // Get inverse document with new relationship key - $account = static::getDatabase()->getDocument('account', 'account1'); + $account = $this->getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('newCustomer'); $this->assertEquals('customer1', $customer['$id']); // Create new document with no relationship - static::getDatabase()->createDocument('customer', new Document([ + $this->getDatabase()->createDocument('customer', new Document([ '$id' => 'customer7', '$permissions' => [ Permission::read(Role::any()), @@ -6420,91 +6420,91 @@ public function testOneToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('customer', 'customer7'); + $deleted = $this->getDatabase()->deleteDocument('customer', 'customer7'); $this->assertEquals(true, $deleted); - $customer7 = static::getDatabase()->getDocument('customer', 'customer7'); + $customer7 = $this->getDatabase()->getDocument('customer', 'customer7'); $this->assertEquals(true, $customer7->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('customer', 'customer1'); + $this->getDatabase()->deleteDocument('customer', 'customer1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - static::getDatabase()->deleteDocument('customer', 'customer1'); + $this->getDatabase()->deleteDocument('customer', 'customer1'); // Check relation was set to null - $account1 = static::getDatabase()->getDocument('account', 'account1'); + $account1 = $this->getDatabase()->getDocument('account', 'account1'); $this->assertEquals(null, $account2->getAttribute('newCustomer', '')); // Relate again - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'account', $account1->getId(), $account1->setAttribute('newCustomer', 'customer2') ); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('customer', 'customer2'); + $this->getDatabase()->deleteDocument('customer', 'customer2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('customer', 'customer2'); + $library = $this->getDatabase()->getDocument('customer', 'customer2'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('account', 'account2'); + $library = $this->getDatabase()->getDocument('account', 'account2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'customer', 'newAccounts' ); // Try to get document again - $customer = static::getDatabase()->getDocument('customer', 'customer1'); + $customer = $this->getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals(null, $accounts); // Try to get inverse document again - $accounts = static::getDatabase()->getDocument('account', 'account1'); + $accounts = $this->getDatabase()->getDocument('account', 'account1'); $customer = $accounts->getAttribute('newCustomer'); $this->assertEquals(null, $customer); } public function testManyToOneOneWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('review'); - static::getDatabase()->createCollection('movie'); + $this->getDatabase()->createCollection('review'); + $this->getDatabase()->createCollection('movie'); - static::getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); - static::getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - static::getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - static::getDatabase()->createRelationship( + $this->getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); + $this->getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + $this->getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + $this->getDatabase()->createRelationship( collection: 'review', relatedCollection: 'movie', type: Database::RELATION_MANY_TO_ONE, @@ -6512,7 +6512,7 @@ public function testManyToOneOneWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('review'); + $collection = $this->getDatabase()->getCollection('review'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'movie') { @@ -6527,7 +6527,7 @@ public function testManyToOneOneWayRelationship(): void } // Check metadata for related collection - $collection = static::getDatabase()->getCollection('movie'); + $collection = $this->getDatabase()->getCollection('movie'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'reviews') { @@ -6542,7 +6542,7 @@ public function testManyToOneOneWayRelationship(): void } // Create document with relationship with nested data - $review1 = static::getDatabase()->createDocument('review', new Document([ + $review1 = $this->getDatabase()->createDocument('review', new Document([ '$id' => 'review1', '$permissions' => [ Permission::read(Role::any()), @@ -6565,16 +6565,16 @@ public function testManyToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); + $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); - $review1Document = static::getDatabase()->getDocument('review', 'review1'); + $review1Document = $this->getDatabase()->getDocument('review', 'review1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $review1Document->getAttribute('movie')); - static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); + $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); // Create document with relationship to existing document by ID - $review10 = static::getDatabase()->createDocument('review', new Document([ + $review10 = $this->getDatabase()->createDocument('review', new Document([ '$id' => 'review10', '$permissions' => [ Permission::read(Role::any()), @@ -6587,7 +6587,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Create document with relationship with related ID - static::getDatabase()->createDocument('movie', new Document([ + $this->getDatabase()->createDocument('movie', new Document([ '$id' => 'movie2', '$permissions' => [ Permission::read(Role::any()), @@ -6598,7 +6598,7 @@ public function testManyToOneOneWayRelationship(): void 'length' => 90, 'date' => '2023-04-03 10:35:27.390', ])); - static::getDatabase()->createDocument('review', new Document([ + $this->getDatabase()->createDocument('review', new Document([ '$id' => 'review2', '$permissions' => [ Permission::read(Role::any()), @@ -6611,12 +6611,12 @@ public function testManyToOneOneWayRelationship(): void ])); // Get document with relationship - $review = static::getDatabase()->getDocument('review', 'review1'); + $review = $this->getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie1', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); - $documents = static::getDatabase()->find('review', [ + $documents = $this->getDatabase()->find('review', [ Query::select(['date', 'movie.date']) ]); @@ -6630,24 +6630,24 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals(29, strlen($document['date'])); // checks filter $this->assertEquals(29, strlen($document['movie']['date'])); - $review = static::getDatabase()->getDocument('review', 'review2'); + $review = $this->getDatabase()->getDocument('review', 'review2'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie2', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); // Get related document - $movie = static::getDatabase()->getDocument('movie', 'movie1'); + $movie = $this->getDatabase()->getDocument('movie', 'movie1'); $this->assertArrayNotHasKey('reviews', $movie); - $movie = static::getDatabase()->getDocument('movie', 'movie2'); + $movie = $this->getDatabase()->getDocument('movie', 'movie2'); $this->assertArrayNotHasKey('reviews', $movie); - $reviews = static::getDatabase()->find('review'); + $reviews = $this->getDatabase()->find('review'); $this->assertEquals(3, \count($reviews)); // Select related document attributes - $review = static::getDatabase()->findOne('review', [ + $review = $this->getDatabase()->findOne('review', [ Query::select(['*', 'movie.name']) ]); @@ -6658,7 +6658,7 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals('Movie 1', $review->getAttribute('movie')->getAttribute('name')); $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); - $review = static::getDatabase()->getDocument('review', 'review1', [ + $review = $this->getDatabase()->getDocument('review', 'review1', [ Query::select(['*', 'movie.name']) ]); @@ -6666,32 +6666,32 @@ public function testManyToOneOneWayRelationship(): void $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); // Update root document attribute without altering relationship - $review1 = static::getDatabase()->updateDocument( + $review1 = $this->getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('name', 'Review 1 Updated') ); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); - $review1 = static::getDatabase()->getDocument('review', 'review1'); + $review1 = $this->getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); // Update nested document attribute $movie = $review1->getAttribute('movie'); $movie->setAttribute('name', 'Movie 1 Updated'); - $review1 = static::getDatabase()->updateDocument( + $review1 = $this->getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', $movie) ); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); - $review1 = static::getDatabase()->getDocument('review', 'review1'); + $review1 = $this->getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); // Create new document with no relationship - $review5 = static::getDatabase()->createDocument('review', new Document([ + $review5 = $this->getDatabase()->createDocument('review', new Document([ '$id' => 'review5', '$permissions' => [ Permission::read(Role::any()), @@ -6702,7 +6702,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Update to relate to created document - $review5 = static::getDatabase()->updateDocument( + $review5 = $this->getDatabase()->updateDocument( 'review', $review5->getId(), $review5->setAttribute('movie', new Document([ @@ -6718,39 +6718,39 @@ public function testManyToOneOneWayRelationship(): void ); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); - $review5 = static::getDatabase()->getDocument('review', 'review5'); + $review5 = $this->getDatabase()->getDocument('review', 'review5'); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); // Update document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', 'movie2') ); // Rename relationship keys on both sides - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'review', 'movie', 'newMovie', ); // Get document with new relationship key - $review = static::getDatabase()->getDocument('review', 'review1'); + $review = $this->getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals('movie2', $movie['$id']); // Reset values - $review1 = static::getDatabase()->getDocument('review', 'review1'); + $review1 = $this->getDatabase()->getDocument('review', 'review1'); - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('newMovie', 'movie1') ); // Create new document with no relationship - static::getDatabase()->createDocument('movie', new Document([ + $this->getDatabase()->createDocument('movie', new Document([ '$id' => 'movie3', '$permissions' => [ Permission::read(Role::any()), @@ -6762,78 +6762,78 @@ public function testManyToOneOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('movie', 'movie3'); + $deleted = $this->getDatabase()->deleteDocument('movie', 'movie3'); $this->assertEquals(true, $deleted); - $movie3 = static::getDatabase()->getDocument('movie', 'movie3'); + $movie3 = $this->getDatabase()->getDocument('movie', 'movie3'); $this->assertEquals(true, $movie3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('movie', 'movie1'); + $this->getDatabase()->deleteDocument('movie', 'movie1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - static::getDatabase()->deleteDocument('movie', 'movie1'); + $this->getDatabase()->deleteDocument('movie', 'movie1'); // Check relation was set to null - $review1 = static::getDatabase()->getDocument('review', 'review1'); + $review1 = $this->getDatabase()->getDocument('review', 'review1'); $this->assertEquals(null, $review1->getAttribute('newMovie')); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - static::getDatabase()->deleteDocument('movie', 'movie2'); + $this->getDatabase()->deleteDocument('movie', 'movie2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('movie', 'movie2'); + $library = $this->getDatabase()->getDocument('movie', 'movie2'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('review', 'review2'); + $library = $this->getDatabase()->getDocument('review', 'review2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'review', 'newMovie' ); // Try to get document again - $review = static::getDatabase()->getDocument('review', 'review1'); + $review = $this->getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals(null, $movie); } public function testManyToOneTwoWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('product'); - static::getDatabase()->createCollection('store'); + $this->getDatabase()->createCollection('product'); + $this->getDatabase()->createCollection('store'); - static::getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); + $this->getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); - static::getDatabase()->createAttribute( + $this->getDatabase()->createAttribute( collection: 'product', id: 'name', type: Database::VAR_STRING, @@ -6841,7 +6841,7 @@ public function testManyToOneTwoWayRelationship(): void required: true ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'product', relatedCollection: 'store', type: Database::RELATION_MANY_TO_ONE, @@ -6850,7 +6850,7 @@ public function testManyToOneTwoWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('product'); + $collection = $this->getDatabase()->getCollection('product'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'store') { @@ -6865,7 +6865,7 @@ public function testManyToOneTwoWayRelationship(): void } // Check metadata for related collection - $collection = static::getDatabase()->getCollection('store'); + $collection = $this->getDatabase()->getCollection('store'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'products') { @@ -6880,7 +6880,7 @@ public function testManyToOneTwoWayRelationship(): void } // Create document with relationship with nested data - $product1 = static::getDatabase()->createDocument('product', new Document([ + $product1 = $this->getDatabase()->createDocument('product', new Document([ '$id' => 'product1', '$permissions' => [ Permission::read(Role::any()), @@ -6901,16 +6901,16 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); + $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); - $product1Document = static::getDatabase()->getDocument('product', 'product1'); + $product1Document = $this->getDatabase()->getDocument('product', 'product1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $product1Document->getAttribute('store')); - static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); + $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); // Create document with relationship with related ID - static::getDatabase()->createDocument('store', new Document([ + $this->getDatabase()->createDocument('store', new Document([ '$id' => 'store2', '$permissions' => [ Permission::read(Role::any()), @@ -6920,7 +6920,7 @@ public function testManyToOneTwoWayRelationship(): void 'name' => 'Store 2', 'opensAt' => '09:30', ])); - static::getDatabase()->createDocument('product', new Document([ + $this->getDatabase()->createDocument('product', new Document([ '$id' => 'product2', '$permissions' => [ Permission::read(Role::any()), @@ -6932,7 +6932,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Create from child side - static::getDatabase()->createDocument('store', new Document([ + $this->getDatabase()->createDocument('store', new Document([ '$id' => 'store3', '$permissions' => [ Permission::read(Role::any()), @@ -6954,7 +6954,7 @@ public function testManyToOneTwoWayRelationship(): void ], ])); - static::getDatabase()->createDocument('product', new Document([ + $this->getDatabase()->createDocument('product', new Document([ '$id' => 'product4', '$permissions' => [ Permission::read(Role::any()), @@ -6963,7 +6963,7 @@ public function testManyToOneTwoWayRelationship(): void ], 'name' => 'Product 4', ])); - static::getDatabase()->createDocument('store', new Document([ + $this->getDatabase()->createDocument('store', new Document([ '$id' => 'store4', '$permissions' => [ Permission::read(Role::any()), @@ -6978,53 +6978,53 @@ public function testManyToOneTwoWayRelationship(): void ])); // Get document with relationship - $product = static::getDatabase()->getDocument('product', 'product1'); + $product = $this->getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('store', []); $this->assertEquals('store1', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = static::getDatabase()->getDocument('product', 'product2'); + $product = $this->getDatabase()->getDocument('product', 'product2'); $store = $product->getAttribute('store', []); $this->assertEquals('store2', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = static::getDatabase()->getDocument('product', 'product3'); + $product = $this->getDatabase()->getDocument('product', 'product3'); $store = $product->getAttribute('store', []); $this->assertEquals('store3', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = static::getDatabase()->getDocument('product', 'product4'); + $product = $this->getDatabase()->getDocument('product', 'product4'); $store = $product->getAttribute('store', []); $this->assertEquals('store4', $store['$id']); $this->assertArrayNotHasKey('products', $store); // Get related document - $store = static::getDatabase()->getDocument('store', 'store1'); + $store = $this->getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('products'); $this->assertEquals('product1', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = static::getDatabase()->getDocument('store', 'store2'); + $store = $this->getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('products'); $this->assertEquals('product2', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = static::getDatabase()->getDocument('store', 'store3'); + $store = $this->getDatabase()->getDocument('store', 'store3'); $products = $store->getAttribute('products'); $this->assertEquals('product3', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = static::getDatabase()->getDocument('store', 'store4'); + $store = $this->getDatabase()->getDocument('store', 'store4'); $products = $store->getAttribute('products'); $this->assertEquals('product4', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $products = static::getDatabase()->find('product'); + $products = $this->getDatabase()->find('product'); $this->assertEquals(4, \count($products)); // Select related document attributes - $product = static::getDatabase()->findOne('product', [ + $product = $this->getDatabase()->findOne('product', [ Query::select(['*', 'store.name']) ]); @@ -7035,7 +7035,7 @@ public function testManyToOneTwoWayRelationship(): void $this->assertEquals('Store 1', $product->getAttribute('store')->getAttribute('name')); $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); - $product = static::getDatabase()->getDocument('product', 'product1', [ + $product = $this->getDatabase()->getDocument('product', 'product1', [ Query::select(['*', 'store.name']) ]); @@ -7043,58 +7043,58 @@ public function testManyToOneTwoWayRelationship(): void $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); // Update root document attribute without altering relationship - $product1 = static::getDatabase()->updateDocument( + $product1 = $this->getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('name', 'Product 1 Updated') ); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); - $product1 = static::getDatabase()->getDocument('product', 'product1'); + $product1 = $this->getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); // Update inverse document attribute without altering relationship - $store1 = static::getDatabase()->getDocument('store', 'store1'); - $store1 = static::getDatabase()->updateDocument( + $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = $this->getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('name', 'Store 1 Updated') ); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); - $store1 = static::getDatabase()->getDocument('store', 'store1'); + $store1 = $this->getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); // Update nested document attribute $store = $product1->getAttribute('store'); $store->setAttribute('name', 'Store 1 Updated'); - $product1 = static::getDatabase()->updateDocument( + $product1 = $this->getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', $store) ); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); - $product1 = static::getDatabase()->getDocument('product', 'product1'); + $product1 = $this->getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); // Update inverse nested document attribute $product = $store1->getAttribute('products')[0]; $product->setAttribute('name', 'Product 1 Updated'); - $store1 = static::getDatabase()->updateDocument( + $store1 = $this->getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', [$product]) ); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); - $store1 = static::getDatabase()->getDocument('store', 'store1'); + $store1 = $this->getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); // Create new document with no relationship - $product5 = static::getDatabase()->createDocument('product', new Document([ + $product5 = $this->getDatabase()->createDocument('product', new Document([ '$id' => 'product5', '$permissions' => [ Permission::read(Role::any()), @@ -7105,7 +7105,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update to relate to created document - $product5 = static::getDatabase()->updateDocument( + $product5 = $this->getDatabase()->updateDocument( 'product', $product5->getId(), $product5->setAttribute('store', new Document([ @@ -7121,11 +7121,11 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); - $product5 = static::getDatabase()->getDocument('product', 'product5'); + $product5 = $this->getDatabase()->getDocument('product', 'product5'); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); // Create new child document with no relationship - $store6 = static::getDatabase()->createDocument('store', new Document([ + $store6 = $this->getDatabase()->createDocument('store', new Document([ '$id' => 'store6', '$permissions' => [ Permission::read(Role::any()), @@ -7137,7 +7137,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update inverse to related to newly created document - $store6 = static::getDatabase()->updateDocument( + $store6 = $this->getDatabase()->updateDocument( 'store', $store6->getId(), $store6->setAttribute('products', [new Document([ @@ -7152,36 +7152,36 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); - $store6 = static::getDatabase()->getDocument('store', 'store6'); + $store6 = $this->getDatabase()->getDocument('store', 'store6'); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); // Update document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', 'store2') ); - $store1 = static::getDatabase()->getDocument('store', 'store1'); + $store1 = $this->getDatabase()->getDocument('store', 'store1'); // Update inverse document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', ['product1']) ); - $store2 = static::getDatabase()->getDocument('store', 'store2'); + $store2 = $this->getDatabase()->getDocument('store', 'store2'); // Update inverse document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'store', $store2->getId(), $store2->setAttribute('products', ['product1', 'product2']) ); // Rename relationship keys on both sides - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'product', 'store', 'newStore', @@ -7189,25 +7189,25 @@ public function testManyToOneTwoWayRelationship(): void ); // Get document with new relationship key - $store = static::getDatabase()->getDocument('store', 'store2'); + $store = $this->getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('newProducts'); $this->assertEquals('product1', $products[0]['$id']); // Get inverse document with new relationship key - $product = static::getDatabase()->getDocument('product', 'product1'); + $product = $this->getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('newStore'); $this->assertEquals('store2', $store['$id']); // Reset relationships - $store1 = static::getDatabase()->getDocument('store', 'store1'); - static::getDatabase()->updateDocument( + $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $this->getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('newProducts', ['product1']) ); // Create new document with no relationship - static::getDatabase()->createDocument('store', new Document([ + $this->getDatabase()->createDocument('store', new Document([ '$id' => 'store7', '$permissions' => [ Permission::read(Role::any()), @@ -7219,87 +7219,87 @@ public function testManyToOneTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('store', 'store7'); + $deleted = $this->getDatabase()->deleteDocument('store', 'store7'); $this->assertEquals(true, $deleted); - $store7 = static::getDatabase()->getDocument('store', 'store7'); + $store7 = $this->getDatabase()->getDocument('store', 'store7'); $this->assertEquals(true, $store7->isEmpty()); // Try to delete child while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('store', 'store1'); + $this->getDatabase()->deleteDocument('store', 'store1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Delete parent while still related to another with on delete: restrict - $result = static::getDatabase()->deleteDocument('product', 'product5'); + $result = $this->getDatabase()->deleteDocument('product', 'product5'); $this->assertEquals(true, $result); // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - static::getDatabase()->deleteDocument('store', 'store1'); + $this->getDatabase()->deleteDocument('store', 'store1'); // Check relation was set to null - static::getDatabase()->getDocument('product', 'product1'); + $this->getDatabase()->getDocument('product', 'product1'); $this->assertEquals(null, $product1->getAttribute('newStore')); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - static::getDatabase()->deleteDocument('store', 'store2'); + $this->getDatabase()->deleteDocument('store', 'store2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('store', 'store2'); + $library = $this->getDatabase()->getDocument('store', 'store2'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('product', 'product2'); + $library = $this->getDatabase()->getDocument('product', 'product2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'product', 'newStore' ); // Try to get document again - $products = static::getDatabase()->getDocument('product', 'product1'); + $products = $this->getDatabase()->getDocument('product', 'product1'); $store = $products->getAttribute('newStore'); $this->assertEquals(null, $store); // Try to get inverse document again - $store = static::getDatabase()->getDocument('store', 'store1'); + $store = $this->getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('newProducts'); $this->assertEquals(null, $products); } public function testManyToManyOneWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('playlist'); - static::getDatabase()->createCollection('song'); + $this->getDatabase()->createCollection('playlist'); + $this->getDatabase()->createCollection('song'); - static::getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); + $this->getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'playlist', relatedCollection: 'song', type: Database::RELATION_MANY_TO_MANY, @@ -7307,7 +7307,7 @@ public function testManyToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('playlist'); + $collection = $this->getDatabase()->getCollection('playlist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -7323,7 +7323,7 @@ public function testManyToManyOneWayRelationship(): void } // Create document with relationship with nested data - $playlist1 = static::getDatabase()->createDocument('playlist', new Document([ + $playlist1 = $this->getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist1', '$permissions' => [ Permission::read(Role::any()), @@ -7346,7 +7346,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Create document with relationship with related ID - static::getDatabase()->createDocument('song', new Document([ + $this->getDatabase()->createDocument('song', new Document([ '$id' => 'song2', '$permissions' => [ Permission::read(Role::any()), @@ -7356,7 +7356,7 @@ public function testManyToManyOneWayRelationship(): void 'name' => 'Song 2', 'length' => 140, ])); - static::getDatabase()->createDocument('playlist', new Document([ + $this->getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist2', '$permissions' => [ Permission::read(Role::any()), @@ -7370,13 +7370,13 @@ public function testManyToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); + $this->getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); - $playlist1Document = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1Document = $this->getDatabase()->getDocument('playlist', 'playlist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($playlist1Document->getAttribute('songs'))); - $documents = static::getDatabase()->find('playlist', [ + $documents = $this->getDatabase()->find('playlist', [ Query::select(['name']), Query::limit(1) ]); @@ -7384,29 +7384,29 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('songs', $documents[0]); // Get document with relationship - $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song1', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); - $playlist = static::getDatabase()->getDocument('playlist', 'playlist2'); + $playlist = $this->getDatabase()->getDocument('playlist', 'playlist2'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song2', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); // Get related document - $library = static::getDatabase()->getDocument('song', 'song1'); + $library = $this->getDatabase()->getDocument('song', 'song1'); $this->assertArrayNotHasKey('songs', $library); - $library = static::getDatabase()->getDocument('song', 'song2'); + $library = $this->getDatabase()->getDocument('song', 'song2'); $this->assertArrayNotHasKey('songs', $library); - $playlists = static::getDatabase()->find('playlist'); + $playlists = $this->getDatabase()->find('playlist'); $this->assertEquals(2, \count($playlists)); // Select related document attributes - $playlist = static::getDatabase()->findOne('playlist', [ + $playlist = $this->getDatabase()->findOne('playlist', [ Query::select(['*', 'songs.name']) ]); @@ -7417,7 +7417,7 @@ public function testManyToManyOneWayRelationship(): void $this->assertEquals('Song 1', $playlist->getAttribute('songs')[0]->getAttribute('name')); $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); - $playlist = static::getDatabase()->getDocument('playlist', 'playlist1', [ + $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1', [ Query::select(['*', 'songs.name']) ]); @@ -7425,32 +7425,32 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); // Update root document attribute without altering relationship - $playlist1 = static::getDatabase()->updateDocument( + $playlist1 = $this->getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('name', 'Playlist 1 Updated') ); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); - $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); // Update nested document attribute $songs = $playlist1->getAttribute('songs', []); $songs[0]->setAttribute('name', 'Song 1 Updated'); - $playlist1 = static::getDatabase()->updateDocument( + $playlist1 = $this->getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', $songs) ); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); - $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); // Create new document with no relationship - $playlist5 = static::getDatabase()->createDocument('playlist', new Document([ + $playlist5 = $this->getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist5', '$permissions' => [ Permission::read(Role::any()), @@ -7461,7 +7461,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Update to relate to created document - $playlist5 = static::getDatabase()->updateDocument( + $playlist5 = $this->getDatabase()->updateDocument( 'playlist', $playlist5->getId(), $playlist5->setAttribute('songs', [new Document([ @@ -7477,7 +7477,7 @@ public function testManyToManyOneWayRelationship(): void ); // Playlist relating to existing songs that belong to other playlists - static::getDatabase()->createDocument('playlist', new Document([ + $this->getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist6', '$permissions' => [ Permission::read(Role::any()), @@ -7493,30 +7493,30 @@ public function testManyToManyOneWayRelationship(): void ])); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); - $playlist5 = static::getDatabase()->getDocument('playlist', 'playlist5'); + $playlist5 = $this->getDatabase()->getDocument('playlist', 'playlist5'); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); // Update document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', ['song2']) ); // Rename relationship key - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'playlist', 'songs', 'newSongs' ); // Get document with new relationship key - $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals('song2', $songs[0]['$id']); // Create new document with no relationship - static::getDatabase()->createDocument('playlist', new Document([ + $this->getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist3', '$permissions' => [ Permission::read(Role::any()), @@ -7527,87 +7527,87 @@ public function testManyToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('playlist', 'playlist3'); + $deleted = $this->getDatabase()->deleteDocument('playlist', 'playlist3'); $this->assertEquals(true, $deleted); - $playlist3 = static::getDatabase()->getDocument('playlist', 'playlist3'); + $playlist3 = $this->getDatabase()->getDocument('playlist', 'playlist3'); $this->assertEquals(true, $playlist3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('playlist', 'playlist1'); + $this->getDatabase()->deleteDocument('playlist', 'playlist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); // Reset relationships - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('newSongs', ['song1']) ); // Delete child, will delete junction - static::getDatabase()->deleteDocument('song', 'song1'); + $this->getDatabase()->deleteDocument('song', 'song1'); // Check relation was set to null - $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals(0, \count($playlist1->getAttribute('newSongs'))); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('playlist', 'playlist2'); + $this->getDatabase()->deleteDocument('playlist', 'playlist2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('playlist', 'playlist2'); + $library = $this->getDatabase()->getDocument('playlist', 'playlist2'); $this->assertEquals(true, $library->isEmpty()); - $library = static::getDatabase()->getDocument('song', 'song2'); + $library = $this->getDatabase()->getDocument('song', 'song2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'playlist', 'newSongs' ); // Try to get document again - $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals(null, $songs); } public function testManyToManyTwoWayRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('students'); - static::getDatabase()->createCollection('classes'); + $this->getDatabase()->createCollection('students'); + $this->getDatabase()->createCollection('classes'); - static::getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); + $this->getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'students', relatedCollection: 'classes', type: Database::RELATION_MANY_TO_MANY, @@ -7615,7 +7615,7 @@ public function testManyToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = static::getDatabase()->getCollection('students'); + $collection = $this->getDatabase()->getCollection('students'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'students') { @@ -7630,7 +7630,7 @@ public function testManyToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = static::getDatabase()->getCollection('classes'); + $collection = $this->getDatabase()->getCollection('classes'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'classes') { @@ -7645,7 +7645,7 @@ public function testManyToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $student1 = static::getDatabase()->createDocument('students', new Document([ + $student1 = $this->getDatabase()->createDocument('students', new Document([ '$id' => 'student1', '$permissions' => [ Permission::read(Role::any()), @@ -7668,14 +7668,14 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - static::getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); + $this->getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); - $student1Document = static::getDatabase()->getDocument('students', 'student1'); + $student1Document = $this->getDatabase()->getDocument('students', 'student1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($student1Document->getAttribute('classes'))); // Create document with relationship with related ID - static::getDatabase()->createDocument('classes', new Document([ + $this->getDatabase()->createDocument('classes', new Document([ '$id' => 'class2', '$permissions' => [ Permission::read(Role::any()), @@ -7686,7 +7686,7 @@ public function testManyToManyTwoWayRelationship(): void 'name' => 'Class 2', 'number' => 2, ])); - static::getDatabase()->createDocument('students', new Document([ + $this->getDatabase()->createDocument('students', new Document([ '$id' => 'student2', '$permissions' => [ Permission::read(Role::any()), @@ -7700,7 +7700,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Create from child side - static::getDatabase()->createDocument('classes', new Document([ + $this->getDatabase()->createDocument('classes', new Document([ '$id' => 'class3', '$permissions' => [ Permission::read(Role::any()), @@ -7721,7 +7721,7 @@ public function testManyToManyTwoWayRelationship(): void ] ], ])); - static::getDatabase()->createDocument('students', new Document([ + $this->getDatabase()->createDocument('students', new Document([ '$id' => 'student4', '$permissions' => [ Permission::read(Role::any()), @@ -7730,7 +7730,7 @@ public function testManyToManyTwoWayRelationship(): void ], 'name' => 'Student 4' ])); - static::getDatabase()->createDocument('classes', new Document([ + $this->getDatabase()->createDocument('classes', new Document([ '$id' => 'class4', '$permissions' => [ Permission::read(Role::any()), @@ -7746,49 +7746,49 @@ public function testManyToManyTwoWayRelationship(): void ])); // Get document with relationship - $student = static::getDatabase()->getDocument('students', 'student1'); + $student = $this->getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class1', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = static::getDatabase()->getDocument('students', 'student2'); + $student = $this->getDatabase()->getDocument('students', 'student2'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class2', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = static::getDatabase()->getDocument('students', 'student3'); + $student = $this->getDatabase()->getDocument('students', 'student3'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class3', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = static::getDatabase()->getDocument('students', 'student4'); + $student = $this->getDatabase()->getDocument('students', 'student4'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class4', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); // Get related document - $class = static::getDatabase()->getDocument('classes', 'class1'); + $class = $this->getDatabase()->getDocument('classes', 'class1'); $student = $class->getAttribute('students'); $this->assertEquals('student1', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = static::getDatabase()->getDocument('classes', 'class2'); + $class = $this->getDatabase()->getDocument('classes', 'class2'); $student = $class->getAttribute('students'); $this->assertEquals('student2', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = static::getDatabase()->getDocument('classes', 'class3'); + $class = $this->getDatabase()->getDocument('classes', 'class3'); $student = $class->getAttribute('students'); $this->assertEquals('student3', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = static::getDatabase()->getDocument('classes', 'class4'); + $class = $this->getDatabase()->getDocument('classes', 'class4'); $student = $class->getAttribute('students'); $this->assertEquals('student4', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); // Select related document attributes - $student = static::getDatabase()->findOne('students', [ + $student = $this->getDatabase()->findOne('students', [ Query::select(['*', 'classes.name']) ]); @@ -7799,7 +7799,7 @@ public function testManyToManyTwoWayRelationship(): void $this->assertEquals('Class 1', $student->getAttribute('classes')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); - $student = static::getDatabase()->getDocument('students', 'student1', [ + $student = $this->getDatabase()->getDocument('students', 'student1', [ Query::select(['*', 'classes.name']) ]); @@ -7807,58 +7807,58 @@ public function testManyToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); // Update root document attribute without altering relationship - $student1 = static::getDatabase()->updateDocument( + $student1 = $this->getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('name', 'Student 1 Updated') ); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); - $student1 = static::getDatabase()->getDocument('students', 'student1'); + $student1 = $this->getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); // Update inverse root document attribute without altering relationship - $class2 = static::getDatabase()->getDocument('classes', 'class2'); - $class2 = static::getDatabase()->updateDocument( + $class2 = $this->getDatabase()->getDocument('classes', 'class2'); + $class2 = $this->getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('name', 'Class 2 Updated') ); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); - $class2 = static::getDatabase()->getDocument('classes', 'class2'); + $class2 = $this->getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); // Update nested document attribute $classes = $student1->getAttribute('classes', []); $classes[0]->setAttribute('name', 'Class 1 Updated'); - $student1 = static::getDatabase()->updateDocument( + $student1 = $this->getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', $classes) ); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); - $student1 = static::getDatabase()->getDocument('students', 'student1'); + $student1 = $this->getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); // Update inverse nested document attribute $students = $class2->getAttribute('students', []); $students[0]->setAttribute('name', 'Student 2 Updated'); - $class2 = static::getDatabase()->updateDocument( + $class2 = $this->getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('students', $students) ); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); - $class2 = static::getDatabase()->getDocument('classes', 'class2'); + $class2 = $this->getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); // Create new document with no relationship - $student5 = static::getDatabase()->createDocument('students', new Document([ + $student5 = $this->getDatabase()->createDocument('students', new Document([ '$id' => 'student5', '$permissions' => [ Permission::read(Role::any()), @@ -7869,7 +7869,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $student5 = static::getDatabase()->updateDocument( + $student5 = $this->getDatabase()->updateDocument( 'students', $student5->getId(), $student5->setAttribute('classes', [new Document([ @@ -7885,11 +7885,11 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); - $student5 = static::getDatabase()->getDocument('students', 'student5'); + $student5 = $this->getDatabase()->getDocument('students', 'student5'); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); // Create child document with no relationship - $class6 = static::getDatabase()->createDocument('classes', new Document([ + $class6 = $this->getDatabase()->createDocument('classes', new Document([ '$id' => 'class6', '$permissions' => [ Permission::read(Role::any()), @@ -7901,7 +7901,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $class6 = static::getDatabase()->updateDocument( + $class6 = $this->getDatabase()->updateDocument( 'classes', $class6->getId(), $class6->setAttribute('students', [new Document([ @@ -7916,27 +7916,27 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); - $class6 = static::getDatabase()->getDocument('classes', 'class6'); + $class6 = $this->getDatabase()->getDocument('classes', 'class6'); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); // Update document with new related document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', ['class2']) ); - $class1 = static::getDatabase()->getDocument('classes', 'class1'); + $class1 = $this->getDatabase()->getDocument('classes', 'class1'); // Update inverse document - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'classes', $class1->getId(), $class1->setAttribute('students', ['student1']) ); // Rename relationship keys on both sides - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( 'students', 'classes', 'newClasses', @@ -7944,17 +7944,17 @@ public function testManyToManyTwoWayRelationship(): void ); // Get document with new relationship key - $students = static::getDatabase()->getDocument('students', 'student1'); + $students = $this->getDatabase()->getDocument('students', 'student1'); $classes = $students->getAttribute('newClasses'); $this->assertEquals('class2', $classes[0]['$id']); // Get inverse document with new relationship key - $class = static::getDatabase()->getDocument('classes', 'class1'); + $class = $this->getDatabase()->getDocument('classes', 'class1'); $students = $class->getAttribute('newStudents'); $this->assertEquals('student1', $students[0]['$id']); // Create new document with no relationship - static::getDatabase()->createDocument('students', new Document([ + $this->getDatabase()->createDocument('students', new Document([ '$id' => 'student7', '$permissions' => [ Permission::read(Role::any()), @@ -7965,107 +7965,107 @@ public function testManyToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = static::getDatabase()->deleteDocument('students', 'student7'); + $deleted = $this->getDatabase()->deleteDocument('students', 'student7'); $this->assertEquals(true, $deleted); - $student6 = static::getDatabase()->getDocument('students', 'student7'); + $student6 = $this->getDatabase()->getDocument('students', 'student7'); $this->assertEquals(true, $student6->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - static::getDatabase()->deleteDocument('students', 'student1'); + $this->getDatabase()->deleteDocument('students', 'student1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $student1 = static::getDatabase()->getDocument('students', 'student1'); + $student1 = $this->getDatabase()->getDocument('students', 'student1'); // Reset relationships - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('newClasses', ['class1']) ); // Delete child, will delete junction - static::getDatabase()->deleteDocument('classes', 'class1'); + $this->getDatabase()->deleteDocument('classes', 'class1'); // Check relation was set to null - $student1 = static::getDatabase()->getDocument('students', 'student1'); + $student1 = $this->getDatabase()->getDocument('students', 'student1'); $this->assertEquals(0, \count($student1->getAttribute('newClasses'))); // Change on delete to cascade - static::getDatabase()->updateRelationship( + $this->getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - static::getDatabase()->deleteDocument('students', 'student2'); + $this->getDatabase()->deleteDocument('students', 'student2'); // Check parent and child were deleted - $library = static::getDatabase()->getDocument('students', 'student2'); + $library = $this->getDatabase()->getDocument('students', 'student2'); $this->assertEquals(true, $library->isEmpty()); // Delete child, should not delete parent - static::getDatabase()->deleteDocument('classes', 'class6'); + $this->getDatabase()->deleteDocument('classes', 'class6'); // Check only child was deleted - $student6 = static::getDatabase()->getDocument('students', 'student6'); + $student6 = $this->getDatabase()->getDocument('students', 'student6'); $this->assertEquals(false, $student6->isEmpty()); $this->assertEmpty($student6->getAttribute('newClasses')); - $library = static::getDatabase()->getDocument('classes', 'class2'); + $library = $this->getDatabase()->getDocument('classes', 'class2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - static::getDatabase()->deleteRelationship( + $this->getDatabase()->deleteRelationship( 'students', 'newClasses' ); // Try to get documents again - $student = static::getDatabase()->getDocument('students', 'student1'); + $student = $this->getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('newClasses'); $this->assertEquals(null, $classes); // Try to get inverse documents again - $classes = static::getDatabase()->getDocument('classes', 'class1'); + $classes = $this->getDatabase()->getDocument('classes', 'class1'); $students = $classes->getAttribute('newStudents'); $this->assertEquals(null, $students); } public function testSelectRelationshipAttributes(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('make'); - static::getDatabase()->createCollection('model'); + $this->getDatabase()->createCollection('make'); + $this->getDatabase()->createCollection('model'); - static::getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); + $this->getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'make', relatedCollection: 'model', type: Database::RELATION_ONE_TO_MANY, id: 'models' ); - static::getDatabase()->createDocument('make', new Document([ + $this->getDatabase()->createDocument('make', new Document([ '$id' => 'ford', '$permissions' => [ Permission::read(Role::any()), @@ -8092,7 +8092,7 @@ public function testSelectRelationshipAttributes(): void ])); // Select some parent attributes, some child attributes - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', 'models.name']), ]); @@ -8114,7 +8114,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); // Select internal attributes - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$id']), ]); @@ -8129,7 +8129,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$internalId']), ]); @@ -8144,7 +8144,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$collection']), ]); @@ -8159,7 +8159,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$createdAt']), ]); @@ -8174,7 +8174,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$updatedAt']), ]); @@ -8189,7 +8189,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name', '$permissions']), ]); @@ -8205,7 +8205,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$permissions', $make); // Select all parent attributes, some child attributes - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['*', 'models.year']), ]); @@ -8221,7 +8221,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, all child attributes - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['*', 'models.*']), ]); @@ -8238,7 +8238,7 @@ public function testSelectRelationshipAttributes(): void // Select all parent attributes, all child attributes // Must select parent if selecting children - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['models.*']), ]); @@ -8254,7 +8254,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, no child attributes - $make = static::getDatabase()->findOne('make', [ + $make = $this->getDatabase()->findOne('make', [ Query::select(['name']), ]); @@ -8268,20 +8268,20 @@ public function testSelectRelationshipAttributes(): void public function testNestedOneToOne_OneToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('pattern'); - static::getDatabase()->createCollection('shirt'); - static::getDatabase()->createCollection('team'); + $this->getDatabase()->createCollection('pattern'); + $this->getDatabase()->createCollection('shirt'); + $this->getDatabase()->createCollection('team'); - static::getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'pattern', relatedCollection: 'shirt', type: Database::RELATION_ONE_TO_ONE, @@ -8289,7 +8289,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void id: 'shirt', twoWayKey: 'pattern' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'shirt', relatedCollection: 'team', type: Database::RELATION_ONE_TO_ONE, @@ -8298,7 +8298,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void twoWayKey: 'shirt' ); - static::getDatabase()->createDocument('pattern', new Document([ + $this->getDatabase()->createDocument('pattern', new Document([ '$id' => 'stripes', '$permissions' => [ Permission::read(Role::any()), @@ -8320,13 +8320,13 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $pattern = static::getDatabase()->getDocument('pattern', 'stripes'); + $pattern = $this->getDatabase()->getDocument('pattern', 'stripes'); $this->assertEquals('red', $pattern['shirt']['$id']); $this->assertArrayNotHasKey('pattern', $pattern['shirt']); $this->assertEquals('reds', $pattern['shirt']['team']['$id']); $this->assertArrayNotHasKey('shirt', $pattern['shirt']['team']); - static::getDatabase()->createDocument('team', new Document([ + $this->getDatabase()->createDocument('team', new Document([ '$id' => 'blues', '$permissions' => [ Permission::read(Role::any()), @@ -8348,7 +8348,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $team = static::getDatabase()->getDocument('team', 'blues'); + $team = $this->getDatabase()->getDocument('team', 'blues'); $this->assertEquals('blue', $team['shirt']['$id']); $this->assertArrayNotHasKey('team', $team['shirt']); $this->assertEquals('plain', $team['shirt']['pattern']['$id']); @@ -8357,20 +8357,20 @@ public function testNestedOneToOne_OneToOneRelationship(): void public function testNestedOneToOne_OneToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('teachers'); - static::getDatabase()->createCollection('classrooms'); - static::getDatabase()->createCollection('children'); + $this->getDatabase()->createCollection('teachers'); + $this->getDatabase()->createCollection('classrooms'); + $this->getDatabase()->createCollection('children'); - static::getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'teachers', relatedCollection: 'classrooms', type: Database::RELATION_ONE_TO_ONE, @@ -8378,7 +8378,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void id: 'classroom', twoWayKey: 'teacher' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'classrooms', relatedCollection: 'children', type: Database::RELATION_ONE_TO_MANY, @@ -8386,7 +8386,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void twoWayKey: 'classroom' ); - static::getDatabase()->createDocument('teachers', new Document([ + $this->getDatabase()->createDocument('teachers', new Document([ '$id' => 'teacher1', '$permissions' => [ Permission::read(Role::any()), @@ -8417,14 +8417,14 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $teacher1 = static::getDatabase()->getDocument('teachers', 'teacher1'); + $teacher1 = $this->getDatabase()->getDocument('teachers', 'teacher1'); $this->assertEquals('classroom1', $teacher1['classroom']['$id']); $this->assertArrayNotHasKey('teacher', $teacher1['classroom']); $this->assertEquals(2, \count($teacher1['classroom']['children'])); $this->assertEquals('Child 1', $teacher1['classroom']['children'][0]['name']); $this->assertEquals('Child 2', $teacher1['classroom']['children'][1]['name']); - static::getDatabase()->createDocument('children', new Document([ + $this->getDatabase()->createDocument('children', new Document([ '$id' => 'child3', '$permissions' => [ Permission::read(Role::any()), @@ -8446,7 +8446,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $child3 = static::getDatabase()->getDocument('children', 'child3'); + $child3 = $this->getDatabase()->getDocument('children', 'child3'); $this->assertEquals('classroom2', $child3['classroom']['$id']); $this->assertArrayNotHasKey('children', $child3['classroom']); $this->assertEquals('teacher2', $child3['classroom']['teacher']['$id']); @@ -8455,20 +8455,20 @@ public function testNestedOneToOne_OneToManyRelationship(): void public function testNestedOneToOne_ManyToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('users'); - static::getDatabase()->createCollection('profiles'); - static::getDatabase()->createCollection('avatars'); + $this->getDatabase()->createCollection('users'); + $this->getDatabase()->createCollection('profiles'); + $this->getDatabase()->createCollection('avatars'); - static::getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'users', relatedCollection: 'profiles', type: Database::RELATION_ONE_TO_ONE, @@ -8476,7 +8476,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'profile', twoWayKey: 'user' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'profiles', relatedCollection: 'avatars', type: Database::RELATION_MANY_TO_ONE, @@ -8484,7 +8484,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'avatar', ); - static::getDatabase()->createDocument('users', new Document([ + $this->getDatabase()->createDocument('users', new Document([ '$id' => 'user1', '$permissions' => [ Permission::read(Role::any()), @@ -8506,13 +8506,13 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $user1 = static::getDatabase()->getDocument('users', 'user1'); + $user1 = $this->getDatabase()->getDocument('users', 'user1'); $this->assertEquals('profile1', $user1['profile']['$id']); $this->assertArrayNotHasKey('user', $user1['profile']); $this->assertEquals('avatar1', $user1['profile']['avatar']['$id']); $this->assertArrayNotHasKey('profile', $user1['profile']['avatar']); - static::getDatabase()->createDocument('avatars', new Document([ + $this->getDatabase()->createDocument('avatars', new Document([ '$id' => 'avatar2', '$permissions' => [ Permission::read(Role::any()), @@ -8536,7 +8536,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $avatar2 = static::getDatabase()->getDocument('avatars', 'avatar2'); + $avatar2 = $this->getDatabase()->getDocument('avatars', 'avatar2'); $this->assertEquals('profile2', $avatar2['profiles'][0]['$id']); $this->assertArrayNotHasKey('avatars', $avatar2['profiles'][0]); $this->assertEquals('user2', $avatar2['profiles'][0]['user']['$id']); @@ -8545,20 +8545,20 @@ public function testNestedOneToOne_ManyToOneRelationship(): void public function testNestedOneToOne_ManyToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('addresses'); - static::getDatabase()->createCollection('houses'); - static::getDatabase()->createCollection('buildings'); + $this->getDatabase()->createCollection('addresses'); + $this->getDatabase()->createCollection('houses'); + $this->getDatabase()->createCollection('buildings'); - static::getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'addresses', relatedCollection: 'houses', type: Database::RELATION_ONE_TO_ONE, @@ -8566,14 +8566,14 @@ public function testNestedOneToOne_ManyToManyRelationship(): void id: 'house', twoWayKey: 'address' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'houses', relatedCollection: 'buildings', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createDocument('addresses', new Document([ + $this->getDatabase()->createDocument('addresses', new Document([ '$id' => 'address1', '$permissions' => [ Permission::read(Role::any()), @@ -8604,7 +8604,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void ], ])); - $address1 = static::getDatabase()->getDocument('addresses', 'address1'); + $address1 = $this->getDatabase()->getDocument('addresses', 'address1'); $this->assertEquals('house1', $address1['house']['$id']); $this->assertArrayNotHasKey('address', $address1['house']); $this->assertEquals('building1', $address1['house']['buildings'][0]['$id']); @@ -8612,7 +8612,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][0]); $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][1]); - static::getDatabase()->createDocument('buildings', new Document([ + $this->getDatabase()->createDocument('buildings', new Document([ '$id' => 'building3', '$permissions' => [ Permission::read(Role::any()), @@ -8639,27 +8639,27 @@ public function testNestedOneToOne_ManyToManyRelationship(): void public function testNestedOneToMany_OneToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('countries'); - static::getDatabase()->createCollection('cities'); - static::getDatabase()->createCollection('mayors'); + $this->getDatabase()->createCollection('countries'); + $this->getDatabase()->createCollection('cities'); + $this->getDatabase()->createCollection('mayors'); - static::getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'countries', relatedCollection: 'cities', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'country' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'cities', relatedCollection: 'mayors', type: Database::RELATION_ONE_TO_ONE, @@ -8668,7 +8668,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void twoWayKey: 'city' ); - static::getDatabase()->createDocument('countries', new Document([ + $this->getDatabase()->createDocument('countries', new Document([ '$id' => 'country1', '$permissions' => [ Permission::read(Role::any()), @@ -8709,26 +8709,26 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $documents = static::getDatabase()->find('countries', [ + $documents = $this->getDatabase()->find('countries', [ Query::limit(1) ]); $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); - $documents = static::getDatabase()->find('countries', [ + $documents = $this->getDatabase()->find('countries', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = static::getDatabase()->find('countries', [ + $documents = $this->getDatabase()->find('countries', [ Query::select(['*']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = static::getDatabase()->find('countries', [ + $documents = $this->getDatabase()->find('countries', [ Query::select(['*', 'cities.*', 'cities.mayor.*']), Query::limit(1) ]); @@ -8736,12 +8736,12 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); // Insert docs to cache: - $country1 = static::getDatabase()->getDocument('countries', 'country1'); - $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = $this->getDatabase()->getDocument('countries', 'country1'); + $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); $this->assertEquals('City 1', $mayor1['city']['name']); $this->assertEquals('City 1', $country1['cities'][0]['name']); - static::getDatabase()->updateDocument('cities', 'city1', new Document([ + $this->getDatabase()->updateDocument('cities', 'city1', new Document([ '$id' => 'city1', '$collection' => 'cities', 'name' => 'City 1 updated', @@ -8752,8 +8752,8 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); - $country1 = static::getDatabase()->getDocument('countries', 'country1'); + $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = $this->getDatabase()->getDocument('countries', 'country1'); $this->assertEquals('City 1 updated', $mayor1['city']['name']); $this->assertEquals('City 1 updated', $country1['cities'][0]['name']); @@ -8764,7 +8764,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertArrayNotHasKey('city', $country1['cities'][0]['mayor']); $this->assertArrayNotHasKey('city', $country1['cities'][1]['mayor']); - static::getDatabase()->createDocument('mayors', new Document([ + $this->getDatabase()->createDocument('mayors', new Document([ '$id' => 'mayor3', '$permissions' => [ Permission::read(Role::any()), @@ -8786,7 +8786,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $country2 = static::getDatabase()->getDocument('countries', 'country2'); + $country2 = $this->getDatabase()->getDocument('countries', 'country2'); $this->assertEquals('city3', $country2['cities'][0]['$id']); $this->assertEquals('mayor3', $country2['cities'][0]['mayor']['$id']); $this->assertArrayNotHasKey('country', $country2['cities'][0]); @@ -8795,27 +8795,27 @@ public function testNestedOneToMany_OneToOneRelationship(): void public function testNestedOneToMany_OneToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('dormitories'); - static::getDatabase()->createCollection('occupants'); - static::getDatabase()->createCollection('pets'); + $this->getDatabase()->createCollection('dormitories'); + $this->getDatabase()->createCollection('occupants'); + $this->getDatabase()->createCollection('pets'); - static::getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'dormitories', relatedCollection: 'occupants', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'dormitory' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'occupants', relatedCollection: 'pets', type: Database::RELATION_ONE_TO_MANY, @@ -8823,7 +8823,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void twoWayKey: 'occupant' ); - static::getDatabase()->createDocument('dormitories', new Document([ + $this->getDatabase()->createDocument('dormitories', new Document([ '$id' => 'dormitory1', '$permissions' => [ Permission::read(Role::any()), @@ -8879,7 +8879,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $dormitory1 = static::getDatabase()->getDocument('dormitories', 'dormitory1'); + $dormitory1 = $this->getDatabase()->getDocument('dormitories', 'dormitory1'); $this->assertEquals('occupant1', $dormitory1['occupants'][0]['$id']); $this->assertEquals('occupant2', $dormitory1['occupants'][1]['$id']); $this->assertEquals('pet1', $dormitory1['occupants'][0]['pets'][0]['$id']); @@ -8893,7 +8893,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][0]); $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][1]); - static::getDatabase()->createDocument('pets', new Document([ + $this->getDatabase()->createDocument('pets', new Document([ '$id' => 'pet5', '$permissions' => [ Permission::read(Role::any()), @@ -8915,7 +8915,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $pet5 = static::getDatabase()->getDocument('pets', 'pet5'); + $pet5 = $this->getDatabase()->getDocument('pets', 'pet5'); $this->assertEquals('occupant3', $pet5['occupant']['$id']); $this->assertEquals('dormitory2', $pet5['occupant']['dormitory']['$id']); $this->assertArrayNotHasKey('pets', $pet5['occupant']); @@ -8924,26 +8924,26 @@ public function testNestedOneToMany_OneToManyRelationship(): void public function testNestedOneToMany_ManyToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('home'); - static::getDatabase()->createCollection('renters'); - static::getDatabase()->createCollection('floors'); + $this->getDatabase()->createCollection('home'); + $this->getDatabase()->createCollection('renters'); + $this->getDatabase()->createCollection('floors'); - static::getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'home', relatedCollection: 'renters', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'renters', relatedCollection: 'floors', type: Database::RELATION_MANY_TO_ONE, @@ -8951,7 +8951,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void id: 'floor' ); - static::getDatabase()->createDocument('home', new Document([ + $this->getDatabase()->createDocument('home', new Document([ '$id' => 'home1', '$permissions' => [ Permission::read(Role::any()), @@ -8975,13 +8975,13 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $home1 = static::getDatabase()->getDocument('home', 'home1'); + $home1 = $this->getDatabase()->getDocument('home', 'home1'); $this->assertEquals('renter1', $home1['renters'][0]['$id']); $this->assertEquals('floor1', $home1['renters'][0]['floor']['$id']); $this->assertArrayNotHasKey('home', $home1['renters'][0]); $this->assertArrayNotHasKey('renters', $home1['renters'][0]['floor']); - static::getDatabase()->createDocument('floors', new Document([ + $this->getDatabase()->createDocument('floors', new Document([ '$id' => 'floor2', '$permissions' => [ Permission::read(Role::any()), @@ -9005,7 +9005,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $floor2 = static::getDatabase()->getDocument('floors', 'floor2'); + $floor2 = $this->getDatabase()->getDocument('floors', 'floor2'); $this->assertEquals('renter2', $floor2['renters'][0]['$id']); $this->assertArrayNotHasKey('floor', $floor2['renters'][0]); $this->assertEquals('home2', $floor2['renters'][0]['home']['$id']); @@ -9014,34 +9014,34 @@ public function testNestedOneToMany_ManyToOneRelationship(): void public function testNestedOneToMany_ManyToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('owners'); - static::getDatabase()->createCollection('cats'); - static::getDatabase()->createCollection('toys'); + $this->getDatabase()->createCollection('owners'); + $this->getDatabase()->createCollection('cats'); + $this->getDatabase()->createCollection('toys'); - static::getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'owners', relatedCollection: 'cats', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'owner' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'cats', relatedCollection: 'toys', type: Database::RELATION_MANY_TO_MANY, twoWay: true ); - static::getDatabase()->createDocument('owners', new Document([ + $this->getDatabase()->createDocument('owners', new Document([ '$id' => 'owner1', '$permissions' => [ Permission::read(Role::any()), @@ -9067,13 +9067,13 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $owner1 = static::getDatabase()->getDocument('owners', 'owner1'); + $owner1 = $this->getDatabase()->getDocument('owners', 'owner1'); $this->assertEquals('cat1', $owner1['cats'][0]['$id']); $this->assertArrayNotHasKey('owner', $owner1['cats'][0]); $this->assertEquals('toy1', $owner1['cats'][0]['toys'][0]['$id']); $this->assertArrayNotHasKey('cats', $owner1['cats'][0]['toys'][0]); - static::getDatabase()->createDocument('toys', new Document([ + $this->getDatabase()->createDocument('toys', new Document([ '$id' => 'toy2', '$permissions' => [ Permission::read(Role::any()), @@ -9097,7 +9097,7 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $toy2 = static::getDatabase()->getDocument('toys', 'toy2'); + $toy2 = $this->getDatabase()->getDocument('toys', 'toy2'); $this->assertEquals('cat2', $toy2['cats'][0]['$id']); $this->assertArrayNotHasKey('toys', $toy2['cats'][0]); $this->assertEquals('owner2', $toy2['cats'][0]['owner']['$id']); @@ -9106,27 +9106,27 @@ public function testNestedOneToMany_ManyToManyRelationship(): void public function testNestedManyToOne_OneToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('towns'); - static::getDatabase()->createCollection('homelands'); - static::getDatabase()->createCollection('capitals'); + $this->getDatabase()->createCollection('towns'); + $this->getDatabase()->createCollection('homelands'); + $this->getDatabase()->createCollection('capitals'); - static::getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'towns', relatedCollection: 'homelands', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'homeland' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'homelands', relatedCollection: 'capitals', type: Database::RELATION_ONE_TO_ONE, @@ -9135,7 +9135,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void twoWayKey: 'homeland' ); - static::getDatabase()->createDocument('towns', new Document([ + $this->getDatabase()->createDocument('towns', new Document([ '$id' => 'town1', '$permissions' => [ Permission::read(Role::any()), @@ -9157,13 +9157,13 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $town1 = static::getDatabase()->getDocument('towns', 'town1'); + $town1 = $this->getDatabase()->getDocument('towns', 'town1'); $this->assertEquals('homeland1', $town1['homeland']['$id']); $this->assertArrayNotHasKey('towns', $town1['homeland']); $this->assertEquals('capital1', $town1['homeland']['capital']['$id']); $this->assertArrayNotHasKey('homeland', $town1['homeland']['capital']); - static::getDatabase()->createDocument('capitals', new Document([ + $this->getDatabase()->createDocument('capitals', new Document([ '$id' => 'capital2', '$permissions' => [ Permission::read(Role::any()), @@ -9194,7 +9194,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $capital2 = static::getDatabase()->getDocument('capitals', 'capital2'); + $capital2 = $this->getDatabase()->getDocument('capitals', 'capital2'); $this->assertEquals('homeland2', $capital2['homeland']['$id']); $this->assertArrayNotHasKey('capital', $capital2['homeland']); $this->assertEquals(2, \count($capital2['homeland']['towns'])); @@ -9204,27 +9204,27 @@ public function testNestedManyToOne_OneToOneRelationship(): void public function testNestedManyToOne_OneToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('players'); - static::getDatabase()->createCollection('teams'); - static::getDatabase()->createCollection('supporters'); + $this->getDatabase()->createCollection('players'); + $this->getDatabase()->createCollection('teams'); + $this->getDatabase()->createCollection('supporters'); - static::getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'players', relatedCollection: 'teams', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'team' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'teams', relatedCollection: 'supporters', type: Database::RELATION_ONE_TO_MANY, @@ -9233,7 +9233,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void twoWayKey: 'team' ); - static::getDatabase()->createDocument('players', new Document([ + $this->getDatabase()->createDocument('players', new Document([ '$id' => 'player1', '$permissions' => [ Permission::read(Role::any()), @@ -9264,14 +9264,14 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $player1 = static::getDatabase()->getDocument('players', 'player1'); + $player1 = $this->getDatabase()->getDocument('players', 'player1'); $this->assertEquals('team1', $player1['team']['$id']); $this->assertArrayNotHasKey('players', $player1['team']); $this->assertEquals(2, \count($player1['team']['supporters'])); $this->assertEquals('supporter1', $player1['team']['supporters'][0]['$id']); $this->assertEquals('supporter2', $player1['team']['supporters'][1]['$id']); - static::getDatabase()->createDocument('supporters', new Document([ + $this->getDatabase()->createDocument('supporters', new Document([ '$id' => 'supporter3', '$permissions' => [ Permission::read(Role::any()), @@ -9302,7 +9302,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $supporter3 = static::getDatabase()->getDocument('supporters', 'supporter3'); + $supporter3 = $this->getDatabase()->getDocument('supporters', 'supporter3'); $this->assertEquals('team2', $supporter3['team']['$id']); $this->assertArrayNotHasKey('supporters', $supporter3['team']); $this->assertEquals(2, \count($supporter3['team']['players'])); @@ -9312,27 +9312,27 @@ public function testNestedManyToOne_OneToManyRelationship(): void public function testNestedManyToOne_ManyToOne(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('cows'); - static::getDatabase()->createCollection('farms'); - static::getDatabase()->createCollection('farmer'); + $this->getDatabase()->createCollection('cows'); + $this->getDatabase()->createCollection('farms'); + $this->getDatabase()->createCollection('farmer'); - static::getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'cows', relatedCollection: 'farms', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'farm' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'farms', relatedCollection: 'farmer', type: Database::RELATION_MANY_TO_ONE, @@ -9340,7 +9340,7 @@ public function testNestedManyToOne_ManyToOne(): void id: 'farmer' ); - static::getDatabase()->createDocument('cows', new Document([ + $this->getDatabase()->createDocument('cows', new Document([ '$id' => 'cow1', '$permissions' => [ Permission::read(Role::any()), @@ -9362,13 +9362,13 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $cow1 = static::getDatabase()->getDocument('cows', 'cow1'); + $cow1 = $this->getDatabase()->getDocument('cows', 'cow1'); $this->assertEquals('farm1', $cow1['farm']['$id']); $this->assertArrayNotHasKey('cows', $cow1['farm']); $this->assertEquals('farmer1', $cow1['farm']['farmer']['$id']); $this->assertArrayNotHasKey('farms', $cow1['farm']['farmer']); - static::getDatabase()->createDocument('farmer', new Document([ + $this->getDatabase()->createDocument('farmer', new Document([ '$id' => 'farmer2', '$permissions' => [ Permission::read(Role::any()), @@ -9401,7 +9401,7 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $farmer2 = static::getDatabase()->getDocument('farmer', 'farmer2'); + $farmer2 = $this->getDatabase()->getDocument('farmer', 'farmer2'); $this->assertEquals('farm2', $farmer2['farms'][0]['$id']); $this->assertArrayNotHasKey('farmer', $farmer2['farms'][0]); $this->assertEquals(2, \count($farmer2['farms'][0]['cows'])); @@ -9411,34 +9411,34 @@ public function testNestedManyToOne_ManyToOne(): void public function testNestedManyToOne_ManyToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('books'); - static::getDatabase()->createCollection('entrants'); - static::getDatabase()->createCollection('rooms'); + $this->getDatabase()->createCollection('books'); + $this->getDatabase()->createCollection('entrants'); + $this->getDatabase()->createCollection('rooms'); - static::getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'books', relatedCollection: 'entrants', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'entrant' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'entrants', relatedCollection: 'rooms', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createDocument('books', new Document([ + $this->getDatabase()->createDocument('books', new Document([ '$id' => 'book1', '$permissions' => [ Permission::read(Role::any()), @@ -9469,7 +9469,7 @@ public function testNestedManyToOne_ManyToManyRelationship(): void ], ])); - $book1 = static::getDatabase()->getDocument('books', 'book1'); + $book1 = $this->getDatabase()->getDocument('books', 'book1'); $this->assertEquals('entrant1', $book1['entrant']['$id']); $this->assertArrayNotHasKey('books', $book1['entrant']); $this->assertEquals(2, \count($book1['entrant']['rooms'])); @@ -9479,26 +9479,26 @@ public function testNestedManyToOne_ManyToManyRelationship(): void public function testNestedManyToMany_OneToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('stones'); - static::getDatabase()->createCollection('hearths'); - static::getDatabase()->createCollection('plots'); + $this->getDatabase()->createCollection('stones'); + $this->getDatabase()->createCollection('hearths'); + $this->getDatabase()->createCollection('plots'); - static::getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'stones', relatedCollection: 'hearths', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'hearths', relatedCollection: 'plots', type: Database::RELATION_ONE_TO_ONE, @@ -9507,7 +9507,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void twoWayKey: 'hearth' ); - static::getDatabase()->createDocument('stones', new Document([ + $this->getDatabase()->createDocument('stones', new Document([ '$id' => 'stone1', '$permissions' => [ Permission::read(Role::any()), @@ -9545,7 +9545,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $stone1 = static::getDatabase()->getDocument('stones', 'stone1'); + $stone1 = $this->getDatabase()->getDocument('stones', 'stone1'); $this->assertEquals(2, \count($stone1['hearths'])); $this->assertEquals('hearth1', $stone1['hearths'][0]['$id']); $this->assertEquals('hearth2', $stone1['hearths'][1]['$id']); @@ -9554,7 +9554,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void $this->assertEquals('plot2', $stone1['hearths'][1]['plot']['$id']); $this->assertArrayNotHasKey('hearth', $stone1['hearths'][0]['plot']); - static::getDatabase()->createDocument('plots', new Document([ + $this->getDatabase()->createDocument('plots', new Document([ '$id' => 'plot3', '$permissions' => [ Permission::read(Role::any()), @@ -9578,7 +9578,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $plot3 = static::getDatabase()->getDocument('plots', 'plot3'); + $plot3 = $this->getDatabase()->getDocument('plots', 'plot3'); $this->assertEquals('hearth3', $plot3['hearth']['$id']); $this->assertArrayNotHasKey('plot', $plot3['hearth']); $this->assertEquals('stone2', $plot3['hearth']['stones'][0]['$id']); @@ -9587,26 +9587,26 @@ public function testNestedManyToMany_OneToOneRelationship(): void public function testNestedManyToMany_OneToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('groups'); - static::getDatabase()->createCollection('tounaments'); - static::getDatabase()->createCollection('prizes'); + $this->getDatabase()->createCollection('groups'); + $this->getDatabase()->createCollection('tounaments'); + $this->getDatabase()->createCollection('prizes'); - static::getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'groups', relatedCollection: 'tounaments', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'tounaments', relatedCollection: 'prizes', type: Database::RELATION_ONE_TO_MANY, @@ -9615,7 +9615,7 @@ public function testNestedManyToMany_OneToManyRelationship(): void twoWayKey: 'tounament' ); - static::getDatabase()->createDocument('groups', new Document([ + $this->getDatabase()->createDocument('groups', new Document([ '$id' => 'group1', '$permissions' => [ Permission::read(Role::any()), @@ -9671,7 +9671,7 @@ public function testNestedManyToMany_OneToManyRelationship(): void ], ])); - $group1 = static::getDatabase()->getDocument('groups', 'group1'); + $group1 = $this->getDatabase()->getDocument('groups', 'group1'); $this->assertEquals(2, \count($group1['tounaments'])); $this->assertEquals('tounament1', $group1['tounaments'][0]['$id']); $this->assertEquals('tounament2', $group1['tounaments'][1]['$id']); @@ -9684,26 +9684,26 @@ public function testNestedManyToMany_OneToManyRelationship(): void public function testNestedManyToMany_ManyToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('platforms'); - static::getDatabase()->createCollection('games'); - static::getDatabase()->createCollection('publishers'); + $this->getDatabase()->createCollection('platforms'); + $this->getDatabase()->createCollection('games'); + $this->getDatabase()->createCollection('publishers'); - static::getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'platforms', relatedCollection: 'games', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'games', relatedCollection: 'publishers', type: Database::RELATION_MANY_TO_ONE, @@ -9712,7 +9712,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void twoWayKey: 'games' ); - static::getDatabase()->createDocument('platforms', new Document([ + $this->getDatabase()->createDocument('platforms', new Document([ '$id' => 'platform1', '$permissions' => [ Permission::read(Role::any()), @@ -9750,7 +9750,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ] ])); - $platform1 = static::getDatabase()->getDocument('platforms', 'platform1'); + $platform1 = $this->getDatabase()->getDocument('platforms', 'platform1'); $this->assertEquals(2, \count($platform1['games'])); $this->assertEquals('game1', $platform1['games'][0]['$id']); $this->assertEquals('game2', $platform1['games'][1]['$id']); @@ -9759,7 +9759,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void $this->assertEquals('publisher2', $platform1['games'][1]['publisher']['$id']); $this->assertArrayNotHasKey('games', $platform1['games'][0]['publisher']); - static::getDatabase()->createDocument('publishers', new Document([ + $this->getDatabase()->createDocument('publishers', new Document([ '$id' => 'publisher3', '$permissions' => [ Permission::read(Role::any()), @@ -9785,7 +9785,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ], ])); - $publisher3 = static::getDatabase()->getDocument('publishers', 'publisher3'); + $publisher3 = $this->getDatabase()->getDocument('publishers', 'publisher3'); $this->assertEquals(1, \count($publisher3['games'])); $this->assertEquals('game3', $publisher3['games'][0]['$id']); $this->assertArrayNotHasKey('publisher', $publisher3['games'][0]); @@ -9795,26 +9795,26 @@ public function testNestedManyToMany_ManyToOneRelationship(): void public function testNestedManyToMany_ManyToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('sauces'); - static::getDatabase()->createCollection('pizzas'); - static::getDatabase()->createCollection('toppings'); + $this->getDatabase()->createCollection('sauces'); + $this->getDatabase()->createCollection('pizzas'); + $this->getDatabase()->createCollection('toppings'); - static::getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'sauces', relatedCollection: 'pizzas', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'pizzas', relatedCollection: 'toppings', type: Database::RELATION_MANY_TO_MANY, @@ -9823,7 +9823,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void twoWayKey: 'pizzas' ); - static::getDatabase()->createDocument('sauces', new Document([ + $this->getDatabase()->createDocument('sauces', new Document([ '$id' => 'sauce1', '$permissions' => [ Permission::read(Role::any()), @@ -9879,7 +9879,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void ] ])); - $sauce1 = static::getDatabase()->getDocument('sauces', 'sauce1'); + $sauce1 = $this->getDatabase()->getDocument('sauces', 'sauce1'); $this->assertEquals(2, \count($sauce1['pizzas'])); $this->assertEquals('pizza1', $sauce1['pizzas'][0]['$id']); $this->assertEquals('pizza2', $sauce1['pizzas'][1]['$id']); @@ -9896,20 +9896,20 @@ public function testNestedManyToMany_ManyToManyRelationship(): void public function testInheritRelationshipPermissions(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); - static::getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); - static::getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); + $this->getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); + $this->getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); + $this->getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); - static::getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'lawns', relatedCollection: 'trees', type: Database::RELATION_ONE_TO_MANY, @@ -9917,7 +9917,7 @@ public function testInheritRelationshipPermissions(): void twoWayKey: 'lawn', onDelete: Database::RELATION_MUTATE_CASCADE, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'trees', relatedCollection: 'birds', type: Database::RELATION_MANY_TO_MANY, @@ -9932,7 +9932,7 @@ public function testInheritRelationshipPermissions(): void Permission::delete(Role::user('user2')), ]; - static::getDatabase()->createDocument('lawns', new Document([ + $this->getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn1', '$permissions' => $permissions, 'name' => 'Lawn 1', @@ -9954,13 +9954,13 @@ public function testInheritRelationshipPermissions(): void ], ])); - $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals($permissions, $lawn1->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][1]->getPermissions()); - $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); + $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals($permissions, $tree1->getPermissions()); $this->assertEquals($permissions, $tree1['lawn']->getPermissions()); $this->assertEquals($permissions, $tree1['birds'][0]->getPermissions()); @@ -9972,18 +9972,18 @@ public function testInheritRelationshipPermissions(): void */ public function testEnforceRelationshipPermissions(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); // Try update root document try { - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'lawns', $lawn1->getId(), $lawn1->setAttribute('name', 'Lawn 1 Updated') @@ -9995,7 +9995,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete root document try { - static::getDatabase()->deleteDocument( + $this->getDatabase()->deleteDocument( 'lawns', $lawn1->getId(), ); @@ -10004,11 +10004,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); + $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); // Try update nested document try { - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -10020,7 +10020,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete nested document try { - static::getDatabase()->deleteDocument( + $this->getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); @@ -10029,11 +10029,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); + $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document try { - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -10045,7 +10045,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete multi-level nested document try { - static::getDatabase()->deleteDocument( + $this->getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); @@ -10056,10 +10056,10 @@ public function testEnforceRelationshipPermissions(): void $this->authorization->setRole(Role::user('user1')->toString()); - $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); + $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document - $bird1 = static::getDatabase()->updateDocument( + $bird1 = $this->getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -10070,17 +10070,17 @@ public function testEnforceRelationshipPermissions(): void $this->authorization->setRole(Role::user('user2')->toString()); // Try delete multi-level nested document - $deleted = static::getDatabase()->deleteDocument( + $deleted = $this->getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); $this->assertEquals(true, $deleted); - $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); + $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals(1, count($tree1['birds'])); // Try update nested document - $tree1 = static::getDatabase()->updateDocument( + $tree1 = $this->getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -10089,17 +10089,17 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Tree 1 Updated', $tree1['name']); // Try delete nested document - $deleted = static::getDatabase()->deleteDocument( + $deleted = $this->getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); $this->assertEquals(true, $deleted); - $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals(0, count($lawn1['trees'])); // Create document with no permissions - static::getDatabase()->createDocument('lawns', new Document([ + $this->getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn2', 'name' => 'Lawn 2', 'trees' => [ @@ -10116,19 +10116,19 @@ public function testEnforceRelationshipPermissions(): void ], ])); - $lawn2 = static::getDatabase()->getDocument('lawns', 'lawn2'); + $lawn2 = $this->getDatabase()->getDocument('lawns', 'lawn2'); $this->assertEquals(true, $lawn2->isEmpty()); - $tree2 = static::getDatabase()->getDocument('trees', 'tree2'); + $tree2 = $this->getDatabase()->getDocument('trees', 'tree2'); $this->assertEquals(true, $tree2->isEmpty()); - $bird3 = static::getDatabase()->getDocument('birds', 'bird3'); + $bird3 = $this->getDatabase()->getDocument('birds', 'bird3'); $this->assertEquals(true, $bird3->isEmpty()); } public function testExceedMaxDepthOneToMany(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10138,24 +10138,24 @@ public function testExceedMaxDepthOneToMany(): void $level3Collection = 'level3OneToMany'; $level4Collection = 'level4OneToMany'; - static::getDatabase()->createCollection($level1Collection); - static::getDatabase()->createCollection($level2Collection); - static::getDatabase()->createCollection($level3Collection); - static::getDatabase()->createCollection($level4Collection); + $this->getDatabase()->createCollection($level1Collection); + $this->getDatabase()->createCollection($level2Collection); + $this->getDatabase()->createCollection($level3Collection); + $this->getDatabase()->createCollection($level4Collection); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, @@ -10163,7 +10163,7 @@ public function testExceedMaxDepthOneToMany(): void ); // Exceed create depth - $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ + $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -10192,13 +10192,13 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey('level4', $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); $this->assertTrue($level4->isEmpty()); // Exceed fetch depth - $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); $this->assertEquals(1, count($level1[$level2Collection])); $this->assertEquals('level2', $level1[$level2Collection][0]->getId()); $this->assertEquals(1, count($level1[$level2Collection][0][$level3Collection])); @@ -10207,7 +10207,7 @@ public function testExceedMaxDepthOneToMany(): void // Exceed update depth - $level1 = static::getDatabase()->updateDocument( + $level1 = $this->getDatabase()->updateDocument( $level1Collection, 'level1', $level1 @@ -10232,15 +10232,15 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3new'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3new'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = static::getDatabase()->getDocument($level4Collection, 'level4new'); + $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4new'); $this->assertTrue($level4->isEmpty()); } public function testExceedMaxDepthOneToOne(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10250,24 +10250,24 @@ public function testExceedMaxDepthOneToOne(): void $level3Collection = 'level3OneToOne'; $level4Collection = 'level4OneToOne'; - static::getDatabase()->createCollection($level1Collection); - static::getDatabase()->createCollection($level2Collection); - static::getDatabase()->createCollection($level3Collection); - static::getDatabase()->createCollection($level4Collection); + $this->getDatabase()->createCollection($level1Collection); + $this->getDatabase()->createCollection($level2Collection); + $this->getDatabase()->createCollection($level3Collection); + $this->getDatabase()->createCollection($level4Collection); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, @@ -10275,7 +10275,7 @@ public function testExceedMaxDepthOneToOne(): void ); // Exceed create depth - $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ + $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -10298,18 +10298,18 @@ public function testExceedMaxDepthOneToOne(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -10319,7 +10319,7 @@ public function testExceedMaxDepthOneToOne(): void public function testExceedMaxDepthOneToOneNull(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10329,31 +10329,31 @@ public function testExceedMaxDepthOneToOneNull(): void $level3Collection = 'level3OneToOneNull'; $level4Collection = 'level4OneToOneNull'; - static::getDatabase()->createCollection($level1Collection); - static::getDatabase()->createCollection($level2Collection); - static::getDatabase()->createCollection($level3Collection); - static::getDatabase()->createCollection($level4Collection); + $this->getDatabase()->createCollection($level1Collection); + $this->getDatabase()->createCollection($level2Collection); + $this->getDatabase()->createCollection($level3Collection); + $this->getDatabase()->createCollection($level4Collection); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ + $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -10376,20 +10376,20 @@ public function testExceedMaxDepthOneToOneNull(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -10399,7 +10399,7 @@ public function testExceedMaxDepthOneToOneNull(): void public function testExceedMaxDepthManyToOneParent(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10409,31 +10409,31 @@ public function testExceedMaxDepthManyToOneParent(): void $level3Collection = 'level3ManyToOneParent'; $level4Collection = 'level4ManyToOneParent'; - static::getDatabase()->createCollection($level1Collection); - static::getDatabase()->createCollection($level2Collection); - static::getDatabase()->createCollection($level3Collection); - static::getDatabase()->createCollection($level4Collection); + $this->getDatabase()->createCollection($level1Collection); + $this->getDatabase()->createCollection($level2Collection); + $this->getDatabase()->createCollection($level3Collection); + $this->getDatabase()->createCollection($level4Collection); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ + $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -10456,20 +10456,20 @@ public function testExceedMaxDepthManyToOneParent(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -10479,7 +10479,7 @@ public function testExceedMaxDepthManyToOneParent(): void public function testExceedMaxDepthOneToManyChild(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10489,31 +10489,31 @@ public function testExceedMaxDepthOneToManyChild(): void $level3Collection = 'level3OneToManyChild'; $level4Collection = 'level4OneToManyChild'; - static::getDatabase()->createCollection($level1Collection); - static::getDatabase()->createCollection($level2Collection); - static::getDatabase()->createCollection($level3Collection); - static::getDatabase()->createCollection($level4Collection); + $this->getDatabase()->createCollection($level1Collection); + $this->getDatabase()->createCollection($level2Collection); + $this->getDatabase()->createCollection($level3Collection); + $this->getDatabase()->createCollection($level4Collection); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ + $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -10542,23 +10542,23 @@ public function testExceedMaxDepthOneToManyChild(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Confirm the 4th level document does not exist - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); // Create level 4 document $level3->setAttribute($level4Collection, [new Document([ '$id' => 'level4', ])]); - $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Verify level 4 document is set - $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); $this->assertArrayHasKey($level4Collection, $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Exceed fetch depth - $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); $this->assertArrayHasKey($level3Collection, $level4); $this->assertEquals('level3', $level4[$level3Collection]->getId()); $this->assertArrayHasKey($level2Collection, $level4[$level3Collection]); @@ -10568,7 +10568,7 @@ public function testExceedMaxDepthOneToManyChild(): void public function testCreateRelationshipMissingCollection(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10576,7 +10576,7 @@ public function testCreateRelationshipMissingCollection(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Collection not found'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'missing', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -10586,17 +10586,17 @@ public function testCreateRelationshipMissingCollection(): void public function testCreateRelationshipMissingRelatedCollection(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('test'); + $this->getDatabase()->createCollection('test'); $this->expectException(Exception::class); $this->expectExceptionMessage('Related collection not found'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'test', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -10606,15 +10606,15 @@ public function testCreateRelationshipMissingRelatedCollection(): void public function testCreateDuplicateRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('test1'); - static::getDatabase()->createCollection('test2'); + $this->getDatabase()->createCollection('test1'); + $this->getDatabase()->createCollection('test2'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -10624,7 +10624,7 @@ public function testCreateDuplicateRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute already exists'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -10634,18 +10634,18 @@ public function testCreateDuplicateRelationship(): void public function testCreateInvalidRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('test3'); - static::getDatabase()->createCollection('test4'); + $this->getDatabase()->createCollection('test3'); + $this->getDatabase()->createCollection('test4'); $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship type'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'test3', relatedCollection: 'test4', type: 'invalid', @@ -10655,7 +10655,7 @@ public function testCreateInvalidRelationship(): void public function testDeleteMissingRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10663,20 +10663,20 @@ public function testDeleteMissingRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute not found'); - static::getDatabase()->deleteRelationship('test', 'test2'); + $this->getDatabase()->deleteRelationship('test', 'test2'); } public function testCreateInvalidIntValueRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('invalid1'); - static::getDatabase()->createCollection('invalid2'); + $this->getDatabase()->createCollection('invalid1'); + $this->getDatabase()->createCollection('invalid2'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_ONE, @@ -10686,7 +10686,7 @@ public function testCreateInvalidIntValueRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - static::getDatabase()->createDocument('invalid1', new Document([ + $this->getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => 10, ])); @@ -10697,7 +10697,7 @@ public function testCreateInvalidIntValueRelationship(): void */ public function testCreateInvalidObjectValueRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -10705,7 +10705,7 @@ public function testCreateInvalidObjectValueRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - static::getDatabase()->createDocument('invalid1', new Document([ + $this->getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => new \stdClass(), ])); @@ -10716,12 +10716,12 @@ public function testCreateInvalidObjectValueRelationship(): void */ public function testCreateInvalidArrayIntValueRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_MANY, @@ -10733,7 +10733,7 @@ public function testCreateInvalidArrayIntValueRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - static::getDatabase()->createDocument('invalid1', new Document([ + $this->getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid3' => [10], ])); @@ -10741,21 +10741,21 @@ public function testCreateInvalidArrayIntValueRelationship(): void public function testCreateEmptyValueRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('null1'); - static::getDatabase()->createCollection('null2'); + $this->getDatabase()->createCollection('null1'); + $this->getDatabase()->createCollection('null2'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_MANY, @@ -10763,7 +10763,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null3', twoWayKey: 'null4', ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_ONE, @@ -10771,7 +10771,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null4', twoWayKey: 'null5', ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_MANY, @@ -10780,21 +10780,21 @@ public function testCreateEmptyValueRelationship(): void twoWayKey: 'null7', ); - $document = static::getDatabase()->createDocument('null1', new Document([ + $document = $this->getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null2' => null, ])); $this->assertEquals(null, $document->getAttribute('null2')); - $document = static::getDatabase()->createDocument('null2', new Document([ + $document = $this->getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null1' => null, ])); $this->assertEquals(null, $document->getAttribute('null1')); - $document = static::getDatabase()->createDocument('null1', new Document([ + $document = $this->getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null3' => null, ])); @@ -10802,35 +10802,35 @@ public function testCreateEmptyValueRelationship(): void // One to many will be empty array instead of null $this->assertEquals([], $document->getAttribute('null3')); - $document = static::getDatabase()->createDocument('null2', new Document([ + $document = $this->getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = static::getDatabase()->createDocument('null1', new Document([ + $document = $this->getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = static::getDatabase()->createDocument('null2', new Document([ + $document = $this->getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null5' => null, ])); $this->assertEquals([], $document->getAttribute('null5')); - $document = static::getDatabase()->createDocument('null1', new Document([ + $document = $this->getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null6' => null, ])); $this->assertEquals([], $document->getAttribute('null6')); - $document = static::getDatabase()->createDocument('null2', new Document([ + $document = $this->getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null7' => null, ])); @@ -10840,15 +10840,15 @@ public function testCreateEmptyValueRelationship(): void public function testDeleteCollectionDeletesRelationships(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('testers'); - static::getDatabase()->createCollection('devices'); + $this->getDatabase()->createCollection('testers'); + $this->getDatabase()->createCollection('devices'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'testers', relatedCollection: 'devices', type: Database::RELATION_ONE_TO_MANY, @@ -10856,17 +10856,17 @@ public function testDeleteCollectionDeletesRelationships(): void twoWayKey: 'tester' ); - $testers = static::getDatabase()->getCollection('testers'); - $devices = static::getDatabase()->getCollection('devices'); + $testers = $this->getDatabase()->getCollection('testers'); + $devices = $this->getDatabase()->getCollection('devices'); $this->assertEquals(1, \count($testers->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('indexes'))); - static::getDatabase()->deleteCollection('testers'); + $this->getDatabase()->deleteCollection('testers'); - $testers = static::getDatabase()->getCollection('testers'); - $devices = static::getDatabase()->getCollection('devices'); + $testers = $this->getDatabase()->getCollection('testers'); + $devices = $this->getDatabase()->getCollection('devices'); $this->assertEquals(true, $testers->isEmpty()); $this->assertEquals(0, \count($devices->getAttribute('attributes'))); @@ -10875,15 +10875,15 @@ public function testDeleteCollectionDeletesRelationships(): void public function testDeleteTwoWayRelationshipFromChild(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('drivers'); - static::getDatabase()->createCollection('licenses'); + $this->getDatabase()->createCollection('drivers'); + $this->getDatabase()->createCollection('licenses'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_ONE, @@ -10892,25 +10892,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(1, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->deleteRelationship('licenses', 'driver'); + $this->getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_MANY, @@ -10919,25 +10919,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->deleteRelationship('licenses', 'driver'); + $this->getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_ONE, @@ -10946,25 +10946,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->deleteRelationship('drivers', 'licenses'); + $this->getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_MANY, @@ -10973,9 +10973,9 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); - $junction = static::getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); + $junction = $this->getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -10984,11 +10984,11 @@ public function testDeleteTwoWayRelationshipFromChild(): void $this->assertEquals(2, \count($junction->getAttribute('attributes'))); $this->assertEquals(2, \count($junction->getAttribute('indexes'))); - static::getDatabase()->deleteRelationship('drivers', 'licenses'); + $this->getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = static::getDatabase()->getCollection('drivers'); - $licenses = static::getDatabase()->getCollection('licenses'); - $junction = static::getDatabase()->getCollection('_licenses_drivers'); + $drivers = $this->getDatabase()->getCollection('drivers'); + $licenses = $this->getDatabase()->getCollection('licenses'); + $junction = $this->getDatabase()->getCollection('_licenses_drivers'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -11000,20 +11000,20 @@ public function testDeleteTwoWayRelationshipFromChild(): void public function testUpdateRelationshipToExistingKey(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('ovens'); - static::getDatabase()->createCollection('cakes'); + $this->getDatabase()->createCollection('ovens'); + $this->getDatabase()->createCollection('cakes'); - static::getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); - static::getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); - static::getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); - static::getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); + $this->getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); + $this->getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'ovens', relatedCollection: 'cakes', type: Database::RELATION_ONE_TO_MANY, @@ -11023,14 +11023,14 @@ public function testUpdateRelationshipToExistingKey(): void ); try { - static::getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); + $this->getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Attribute already exists', $e->getMessage()); } try { - static::getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); + $this->getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Related attribute already exists', $e->getMessage()); @@ -11039,29 +11039,29 @@ public function testUpdateRelationshipToExistingKey(): void public function testOneToOneRelationshipKeyWithSymbols(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('$symbols_coll.ection1'); - static::getDatabase()->createCollection('$symbols_coll.ection2'); + $this->getDatabase()->createCollection('$symbols_coll.ection1'); + $this->getDatabase()->createCollection('$symbols_coll.ection2'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: '$symbols_coll.ection1', relatedCollection: '$symbols_coll.ection2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection2', new Document([ + $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection2', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection1', new Document([ + $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection1', new Document([ '$id' => ID::unique(), '$symbols_coll.ection2' => $doc1->getId(), '$permissions' => [ @@ -11070,8 +11070,8 @@ public function testOneToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); - $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); + $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); + $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection1')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection2')->getId()); @@ -11079,29 +11079,29 @@ public function testOneToOneRelationshipKeyWithSymbols(): void public function testOneToManyRelationshipKeyWithSymbols(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('$symbols_coll.ection3'); - static::getDatabase()->createCollection('$symbols_coll.ection4'); + $this->getDatabase()->createCollection('$symbols_coll.ection3'); + $this->getDatabase()->createCollection('$symbols_coll.ection4'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: '$symbols_coll.ection3', relatedCollection: '$symbols_coll.ection4', type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection4', new Document([ + $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection4', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection3', new Document([ + $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection3', new Document([ '$id' => ID::unique(), '$symbols_coll.ection4' => [$doc1->getId()], '$permissions' => [ @@ -11110,8 +11110,8 @@ public function testOneToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); - $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); + $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); + $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection3')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection4')[0]->getId()); @@ -11119,29 +11119,29 @@ public function testOneToManyRelationshipKeyWithSymbols(): void public function testManyToOneRelationshipKeyWithSymbols(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('$symbols_coll.ection5'); - static::getDatabase()->createCollection('$symbols_coll.ection6'); + $this->getDatabase()->createCollection('$symbols_coll.ection5'); + $this->getDatabase()->createCollection('$symbols_coll.ection6'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: '$symbols_coll.ection5', relatedCollection: '$symbols_coll.ection6', type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection6', new Document([ + $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection6', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection5', new Document([ + $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection5', new Document([ '$id' => ID::unique(), '$symbols_coll.ection6' => $doc1->getId(), '$permissions' => [ @@ -11150,8 +11150,8 @@ public function testManyToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); - $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); + $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); + $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection5')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection6')->getId()); @@ -11159,29 +11159,29 @@ public function testManyToOneRelationshipKeyWithSymbols(): void public function testManyToManyRelationshipKeyWithSymbols(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('$symbols_coll.ection7'); - static::getDatabase()->createCollection('$symbols_coll.ection8'); + $this->getDatabase()->createCollection('$symbols_coll.ection7'); + $this->getDatabase()->createCollection('$symbols_coll.ection8'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: '$symbols_coll.ection7', relatedCollection: '$symbols_coll.ection8', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection8', new Document([ + $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection8', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection7', new Document([ + $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection7', new Document([ '$id' => ID::unique(), '$symbols_coll.ection8' => [$doc1->getId()], '$permissions' => [ @@ -11190,8 +11190,8 @@ public function testManyToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); - $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); + $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); + $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection7')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection8')[0]->getId()); @@ -11199,16 +11199,16 @@ public function testManyToManyRelationshipKeyWithSymbols(): void public function testCascadeMultiDelete(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('cascadeMultiDelete1'); - static::getDatabase()->createCollection('cascadeMultiDelete2'); - static::getDatabase()->createCollection('cascadeMultiDelete3'); + $this->getDatabase()->createCollection('cascadeMultiDelete1'); + $this->getDatabase()->createCollection('cascadeMultiDelete2'); + $this->getDatabase()->createCollection('cascadeMultiDelete3'); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'cascadeMultiDelete1', relatedCollection: 'cascadeMultiDelete2', type: Database::RELATION_ONE_TO_MANY, @@ -11216,7 +11216,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'cascadeMultiDelete2', relatedCollection: 'cascadeMultiDelete3', type: Database::RELATION_ONE_TO_MANY, @@ -11224,7 +11224,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - $root = static::getDatabase()->createDocument('cascadeMultiDelete1', new Document([ + $root = $this->getDatabase()->createDocument('cascadeMultiDelete1', new Document([ '$id' => 'cascadeMultiDelete1', '$permissions' => [ Permission::read(Role::any()), @@ -11253,18 +11253,18 @@ public function testCascadeMultiDelete(): void $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')); $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')[0]->getAttribute('cascadeMultiDelete3')); - $this->assertEquals(true, static::getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); + $this->assertEquals(true, $this->getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); - $multi2 = static::getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); + $multi2 = $this->getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); $this->assertEquals(true, $multi2->isEmpty()); - $multi3 = static::getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); + $multi3 = $this->getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); $this->assertEquals(true, $multi3->isEmpty()); } public function testCollectionUpdate(): Document { - $collection = static::getDatabase()->createCollection('collectionUpdate', permissions: [ + $collection = $this->getDatabase()->createCollection('collectionUpdate', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -11273,19 +11273,19 @@ public function testCollectionUpdate(): Document $this->assertInstanceOf(Document::class, $collection); - $collection = static::getDatabase()->getCollection('collectionUpdate'); + $collection = $this->getDatabase()->getCollection('collectionUpdate'); $this->assertFalse($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertCount(4, $collection->getPermissions()); - $collection = static::getDatabase()->updateCollection('collectionUpdate', [], true); + $collection = $this->getDatabase()->updateCollection('collectionUpdate', [], true); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertEmpty($collection->getPermissions()); - $collection = static::getDatabase()->getCollection('collectionUpdate'); + $collection = $this->getDatabase()->getCollection('collectionUpdate'); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); @@ -11300,14 +11300,14 @@ public function testCollectionUpdate(): Document public function testCollectionUpdatePermissionsThrowException(Document $collection): void { $this->expectException(InvalidArgumentException::class); - static::getDatabase()->updateCollection($collection->getId(), permissions: [ + $this->getDatabase()->updateCollection($collection->getId(), permissions: [ 'i dont work' ], documentSecurity: false); } public function testCollectionPermissions(): Document { - $collection = static::getDatabase()->createCollection('collectionSecurity', permissions: [ + $collection = $this->getDatabase()->createCollection('collectionSecurity', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -11316,7 +11316,7 @@ public function testCollectionPermissions(): Document $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -11330,7 +11330,7 @@ public function testCollectionPermissions(): Document public function testCollectionPermissionsExceptions(): void { $this->expectException(InvalidArgumentException::class); - static::getDatabase()->createCollection('collectionSecurity', permissions: [ + $this->getDatabase()->createCollection('collectionSecurity', permissions: [ 'i dont work' ]); } @@ -11344,7 +11344,7 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $document = static::getDatabase()->createDocument($collection->getId(), new Document([ + $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -11368,7 +11368,7 @@ public function testCollectionPermissionsCreateThrowsException(Document $collect $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - static::getDatabase()->createDocument($collection->getId(), new Document([ + $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -11391,7 +11391,7 @@ public function testCollectionPermissionsGetWorks(array $data): array $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $document = static::getDatabase()->getDocument( + $document = $this->getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -11412,7 +11412,7 @@ public function testCollectionPermissionsGetThrowsException(array $data): void $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $document = static::getDatabase()->getDocument( + $document = $this->getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -11432,14 +11432,14 @@ public function testCollectionPermissionsFindWorks(array $data): array $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $documents = static::getDatabase()->find($collection->getId()); + $documents = $this->getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('random')->toString()); try { - static::getDatabase()->find($collection->getId()); + $this->getDatabase()->find($collection->getId()); $this->fail('Failed to throw exception'); } catch (AuthorizationException) { } @@ -11459,7 +11459,7 @@ public function testCollectionPermissionsFindThrowsException(array $data): void $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - static::getDatabase()->find($collection->getId()); + $this->getDatabase()->find($collection->getId()); } /** @@ -11474,7 +11474,7 @@ public function testCollectionPermissionsCountWorks(array $data): array $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $count = static::getDatabase()->count( + $count = $this->getDatabase()->count( $collection->getId() ); @@ -11494,7 +11494,7 @@ public function testCollectionPermissionsCountThrowsException(array $data): void $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $count = static::getDatabase()->count( + $count = $this->getDatabase()->count( $collection->getId() ); $this->assertEmpty($count); @@ -11512,7 +11512,7 @@ public function testCollectionPermissionsUpdateWorks(array $data): array $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $this->assertInstanceOf(Document::class, static::getDatabase()->updateDocument( + $this->assertInstanceOf(Document::class, $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -11532,7 +11532,7 @@ public function testCollectionPermissionsUpdateThrowsException(array $data): voi $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = static::getDatabase()->updateDocument( + $document = $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'lorem') @@ -11551,7 +11551,7 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - static::getDatabase()->deleteDocument( + $this->getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -11568,7 +11568,7 @@ public function testCollectionPermissionsDeleteWorks(array $data): void $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $this->assertTrue(static::getDatabase()->deleteDocument( + $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -11579,7 +11579,7 @@ public function testCollectionPermissionsDeleteWorks(array $data): void */ public function testCollectionPermissionsRelationships(): array { - $collection = static::getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ + $collection = $this->getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -11588,7 +11588,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -11596,7 +11596,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $collectionOneToOne = static::getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ + $collectionOneToOne = $this->getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -11605,7 +11605,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToOne); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: $collectionOneToOne->getId(), id: 'test', type: Database::VAR_STRING, @@ -11613,7 +11613,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue(static::getDatabase()->createRelationship( + $this->assertTrue($this->getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToOne->getId(), type: Database::RELATION_ONE_TO_ONE, @@ -11621,7 +11621,7 @@ public function testCollectionPermissionsRelationships(): array onDelete: Database::RELATION_MUTATE_CASCADE )); - $collectionOneToMany = static::getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ + $collectionOneToMany = $this->getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -11630,7 +11630,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToMany); - $this->assertTrue(static::getDatabase()->createAttribute( + $this->assertTrue($this->getDatabase()->createAttribute( collection: $collectionOneToMany->getId(), id: 'test', type: Database::VAR_STRING, @@ -11638,7 +11638,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue(static::getDatabase()->createRelationship( + $this->assertTrue($this->getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToMany->getId(), type: Database::RELATION_ONE_TO_MANY, @@ -11660,7 +11660,7 @@ public function testCollectionPermissionsRelationshipsCreateWorks(array $data): $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $document = static::getDatabase()->createDocument($collection->getId(), new Document([ + $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -11714,7 +11714,7 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - static::getDatabase()->createDocument($collection->getId(), new Document([ + $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -11736,7 +11736,7 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $document = static::getDatabase()->getDocument( + $document = $this->getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -11750,7 +11750,7 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('random')->toString()); - $document = static::getDatabase()->getDocument( + $document = $this->getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -11775,7 +11775,7 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ $this->authorization->cleanRoles(); $this->authorization->setRole(Role::any()->toString()); - $document = static::getDatabase()->getDocument( + $document = $this->getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -11794,7 +11794,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $documents = static::getDatabase()->find( + $documents = $this->getDatabase()->find( $collection->getId() ); @@ -11810,7 +11810,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('random')->toString()); - $documents = static::getDatabase()->find( + $documents = $this->getDatabase()->find( $collection->getId() ); @@ -11826,7 +11826,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('unknown')->toString()); - $documents = static::getDatabase()->find( + $documents = $this->getDatabase()->find( $collection->getId() ); @@ -11845,7 +11845,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $documents = static::getDatabase()->count( + $documents = $this->getDatabase()->count( $collection->getId() ); @@ -11854,7 +11854,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('random')->toString()); - $documents = static::getDatabase()->count( + $documents = $this->getDatabase()->count( $collection->getId() ); @@ -11863,7 +11863,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('unknown')->toString()); - $documents = static::getDatabase()->count( + $documents = $this->getDatabase()->count( $collection->getId() ); @@ -11881,7 +11881,7 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document @@ -11892,7 +11892,7 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('random')->toString()); - static::getDatabase()->updateDocument( + $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -11915,7 +11915,7 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = static::getDatabase()->updateDocument( + $document = $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', $document->getAttribute('test').'new_value') @@ -11934,7 +11934,7 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra $this->authorization->setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = static::getDatabase()->deleteDocument( + $document = $this->getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -11951,7 +11951,7 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): $this->authorization->cleanRoles(); $this->authorization->setRole(Role::users()->toString()); - $this->assertTrue(static::getDatabase()->deleteDocument( + $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -11959,7 +11959,7 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): public function testCreateRelationDocumentWithoutUpdatePermission(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -11967,20 +11967,20 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void $this->authorization->cleanRoles(); $this->authorization->setRole(Role::user('a')->toString()); - static::getDatabase()->createCollection('parentRelationTest', [], [], [ + $this->getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), Permission::create(Role::user('a')), Permission::update(Role::user('a')), Permission::delete(Role::user('a')) ]); - static::getDatabase()->createCollection('childRelationTest', [], [], [ + $this->getDatabase()->createCollection('childRelationTest', [], [], [ Permission::create(Role::user('a')), Permission::read(Role::user('a')), ]); - static::getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); - static::getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); + $this->getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); + $this->getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'parentRelationTest', relatedCollection: 'childRelationTest', type: Database::RELATION_ONE_TO_MANY, @@ -11988,7 +11988,7 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void ); // Create document with relationship with nested data - $parent = static::getDatabase()->createDocument('parentRelationTest', new Document([ + $parent = $this->getDatabase()->createDocument('parentRelationTest', new Document([ '$id' => 'parent1', 'name' => 'Parent 1', 'children' => [ @@ -12004,21 +12004,21 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void '$id' => 'child2', ], ]); - $updatedParent = static::getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); + $updatedParent = $this->getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); $this->assertEquals('child2', $updatedParent->getAttribute('children')[0]->getId()); - static::getDatabase()->deleteCollection('parentRelationTest'); - static::getDatabase()->deleteCollection('childRelationTest'); + $this->getDatabase()->deleteCollection('parentRelationTest'); + $this->getDatabase()->deleteCollection('childRelationTest'); } public function testUpdateDocumentWithRelationships(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('userProfiles', [ + $this->getDatabase()->createCollection('userProfiles', [ new Document([ '$id' => ID::custom('username'), 'type' => Database::VAR_STRING, @@ -12036,7 +12036,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('links', [ + $this->getDatabase()->createCollection('links', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -12054,7 +12054,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('videos', [ + $this->getDatabase()->createCollection('videos', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -12072,7 +12072,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('products', [ + $this->getDatabase()->createCollection('products', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -12090,7 +12090,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('settings', [ + $this->getDatabase()->createCollection('settings', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -12108,7 +12108,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('appearance', [ + $this->getDatabase()->createCollection('appearance', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -12126,7 +12126,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('group', [ + $this->getDatabase()->createCollection('group', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -12144,7 +12144,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - static::getDatabase()->createCollection('community', [ + $this->getDatabase()->createCollection('community', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -12163,21 +12163,21 @@ public function testUpdateDocumentWithRelationships(): void Permission::delete(Role::any()) ]); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'links', type: Database::RELATION_ONE_TO_MANY, id: 'links' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'videos', type: Database::RELATION_ONE_TO_MANY, id: 'videos' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'products', type: Database::RELATION_ONE_TO_MANY, @@ -12186,35 +12186,35 @@ public function testUpdateDocumentWithRelationships(): void twoWayKey: 'userProfile', ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'settings', type: Database::RELATION_ONE_TO_ONE, id: 'settings' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'appearance', type: Database::RELATION_ONE_TO_ONE, id: 'appearance' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'group', type: Database::RELATION_MANY_TO_ONE, id: 'group' ); - static::getDatabase()->createRelationship( + $this->getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'community', type: Database::RELATION_MANY_TO_ONE, id: 'community' ); - $profile = static::getDatabase()->createDocument('userProfiles', new Document([ + $profile = $this->getDatabase()->createDocument('userProfiles', new Document([ '$id' => '1', 'username' => 'user1', 'links' => [ @@ -12277,7 +12277,7 @@ public function testUpdateDocumentWithRelationships(): void 'name' => 'New Group Name', ]); - $updatedProfile = static::getDatabase()->updateDocument('userProfiles', '1', $profile); + $updatedProfile = $this->getDatabase()->updateDocument('userProfiles', '1', $profile); $this->assertEquals('New Link Value', $updatedProfile->getAttribute('links')[0]->getAttribute('title')); $this->assertEquals('New Meta Title', $updatedProfile->getAttribute('settings')->getAttribute('metaTitle')); @@ -12290,35 +12290,35 @@ public function testUpdateDocumentWithRelationships(): void $this->assertEquals('Community 1', $updatedProfile->getAttribute('community')->getAttribute('name')); // updating document using two way key in one to many relationship - $product = static::getDatabase()->getDocument('products', 'product1'); + $product = $this->getDatabase()->getDocument('products', 'product1'); $product->setAttribute('userProfile', [ '$id' => '1', 'username' => 'updated user value', ]); - $updatedProduct = static::getDatabase()->updateDocument('products', 'product1', $product); + $updatedProduct = $this->getDatabase()->updateDocument('products', 'product1', $product); $this->assertEquals('updated user value', $updatedProduct->getAttribute('userProfile')->getAttribute('username')); $this->assertEquals('Product 1', $updatedProduct->getAttribute('title')); $this->assertEquals('product1', $updatedProduct->getId()); $this->assertEquals('1', $updatedProduct->getAttribute('userProfile')->getId()); - static::getDatabase()->deleteCollection('userProfiles'); - static::getDatabase()->deleteCollection('links'); - static::getDatabase()->deleteCollection('settings'); - static::getDatabase()->deleteCollection('group'); - static::getDatabase()->deleteCollection('community'); - static::getDatabase()->deleteCollection('videos'); - static::getDatabase()->deleteCollection('products'); - static::getDatabase()->deleteCollection('appearance'); + $this->getDatabase()->deleteCollection('userProfiles'); + $this->getDatabase()->deleteCollection('links'); + $this->getDatabase()->deleteCollection('settings'); + $this->getDatabase()->deleteCollection('group'); + $this->getDatabase()->deleteCollection('community'); + $this->getDatabase()->deleteCollection('videos'); + $this->getDatabase()->deleteCollection('products'); + $this->getDatabase()->deleteCollection('appearance'); } public function testLabels(): void { - $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection( + $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection( 'labels_test', )); - static::getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); + $this->getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); - static::getDatabase()->createDocument('labels_test', new Document([ + $this->getDatabase()->createDocument('labels_test', new Document([ '$id' => 'doc1', 'attr1' => 'value1', '$permissions' => [ @@ -12326,13 +12326,13 @@ public function testLabels(): void ], ])); - $documents = static::getDatabase()->find('labels_test'); + $documents = $this->getDatabase()->find('labels_test'); $this->assertEmpty($documents); $this->authorization->setRole(Role::label('reader')->toString()); - $documents = static::getDatabase()->find('labels_test'); + $documents = $this->getDatabase()->find('labels_test'); $this->assertCount(1, $documents); } @@ -12340,7 +12340,7 @@ public function testLabels(): void public function testEmptyOperatorValues(): void { try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::equal('string', []), ]); $this->fail('Failed to throw exception'); @@ -12350,7 +12350,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::search('string', null), ]); $this->fail('Failed to throw exception'); @@ -12360,7 +12360,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::notEqual('string', []), ]); $this->fail('Failed to throw exception'); @@ -12370,7 +12370,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::lessThan('string', []), ]); $this->fail('Failed to throw exception'); @@ -12380,7 +12380,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::lessThanEqual('string', []), ]); $this->fail('Failed to throw exception'); @@ -12390,7 +12390,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::greaterThan('string', []), ]); $this->fail('Failed to throw exception'); @@ -12400,7 +12400,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::greaterThanEqual('string', []), ]); $this->fail('Failed to throw exception'); @@ -12410,7 +12410,7 @@ public function testEmptyOperatorValues(): void } try { - static::getDatabase()->findOne('documents', [ + $this->getDatabase()->findOne('documents', [ Query::contains('string', []), ]); $this->fail('Failed to throw exception'); @@ -12423,7 +12423,7 @@ public function testEmptyOperatorValues(): void public function testEvents(): void { $this->authorization->skip(function () { - $database = static::getDatabase(); + $database = $this->getDatabase(); $events = [ Database::EVENT_DATABASE_CREATE, From fefad52fff59779c8545aff66409e283c2091316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 19 Oct 2023 15:08:47 +0200 Subject: [PATCH 006/103] Fix tests --- tests/Database/Base.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/Database/Base.php b/tests/Database/Base.php index 9e19cfdd1..557888ade 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -32,7 +32,12 @@ abstract class Base extends TestCase /** * @var Authorization */ - protected Authorization $authorization; + protected static ?Authorization $authorizationSingleton = null; + + /** + * @var Authorization + */ + protected ?Authorization $authorization = null; /** * @return Database @@ -46,7 +51,12 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - $this->authorization = new Authorization(); + if (is_null(self::$authorizationSingleton)) { + self::$authorizationSingleton = new Authorization(); + self::$authorizationSingleton->setRole('any'); + } + + $this->authorization = self::$authorizationSingleton; $this->authorization->setRole('any'); } From c14be0f88cf0008a19e07bdf3fa887557c4889e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 3 Jan 2024 13:22:45 +0000 Subject: [PATCH 007/103] PR review changes --- composer.lock | 111 +++++++++--------- src/Database/Adapter/MariaDB.php | 6 +- src/Database/Adapter/Mongo.php | 6 +- src/Database/Adapter/Postgres.php | 8 +- src/Database/Database.php | 24 ++-- src/Database/Validator/Authorization.php | 25 +++- tests/Database/Adapter/MariaDBTest.php | 3 +- tests/Database/Adapter/MongoDBTest.php | 3 +- tests/Database/Adapter/MySQLTest.php | 3 +- tests/Database/Adapter/PostgresTest.php | 3 +- tests/Database/Adapter/SQLiteTest.php | 3 +- .../Database/Validator/AuthorizationTest.php | 14 +-- 12 files changed, 119 insertions(+), 90 deletions(-) diff --git a/composer.lock b/composer.lock index 569814fb4..17fb74498 100644 --- a/composer.lock +++ b/composer.lock @@ -447,16 +447,16 @@ }, { "name": "fakerphp/faker", - "version": "v1.23.0", + "version": "v1.23.1", "source": { "type": "git", "url": "https://github.com/FakerPHP/Faker.git", - "reference": "e3daa170d00fde61ea7719ef47bb09bb8f1d9b01" + "reference": "bfb4fe148adbf78eff521199619b93a52ae3554b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/FakerPHP/Faker/zipball/e3daa170d00fde61ea7719ef47bb09bb8f1d9b01", - "reference": "e3daa170d00fde61ea7719ef47bb09bb8f1d9b01", + "url": "https://api.github.com/repos/FakerPHP/Faker/zipball/bfb4fe148adbf78eff521199619b93a52ae3554b", + "reference": "bfb4fe148adbf78eff521199619b93a52ae3554b", "shasum": "" }, "require": { @@ -482,11 +482,6 @@ "ext-mbstring": "Required for multibyte Unicode string functionality." }, "type": "library", - "extra": { - "branch-alias": { - "dev-main": "v1.21-dev" - } - }, "autoload": { "psr-4": { "Faker\\": "src/Faker/" @@ -509,9 +504,9 @@ ], "support": { "issues": "https://github.com/FakerPHP/Faker/issues", - "source": "https://github.com/FakerPHP/Faker/tree/v1.23.0" + "source": "https://github.com/FakerPHP/Faker/tree/v1.23.1" }, - "time": "2023-06-12T08:44:38+00:00" + "time": "2024-01-02T13:46:09+00:00" }, { "name": "laravel/pint", @@ -640,16 +635,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.17.1", + "version": "v4.18.0", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d" + "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", - "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1bcbb2179f97633e98bbbc87044ee2611c7d7999", + "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999", "shasum": "" }, "require": { @@ -690,9 +685,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.17.1" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.18.0" }, - "time": "2023-08-13T19:53:39+00:00" + "time": "2023-12-10T21:03:43+00:00" }, { "name": "pcov/clobber", @@ -841,16 +836,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.39", + "version": "1.10.50", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "d9dedb0413f678b4d03cbc2279a48f91592c97c4" + "reference": "06a98513ac72c03e8366b5a0cb00750b487032e4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/d9dedb0413f678b4d03cbc2279a48f91592c97c4", - "reference": "d9dedb0413f678b4d03cbc2279a48f91592c97c4", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/06a98513ac72c03e8366b5a0cb00750b487032e4", + "reference": "06a98513ac72c03e8366b5a0cb00750b487032e4", "shasum": "" }, "require": { @@ -899,27 +894,27 @@ "type": "tidelift" } ], - "time": "2023-10-17T15:46:26+00:00" + "time": "2023-12-13T10:59:42+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "9.2.29", + "version": "9.2.30", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76" + "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6a3a87ac2bbe33b25042753df8195ba4aa534c76", - "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/ca2bd87d2f9215904682a9cb9bb37dda98e76089", + "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089", "shasum": "" }, "require": { "ext-dom": "*", "ext-libxml": "*", "ext-xmlwriter": "*", - "nikic/php-parser": "^4.15", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3", "phpunit/php-file-iterator": "^3.0.3", "phpunit/php-text-template": "^2.0.2", @@ -969,7 +964,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.29" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.30" }, "funding": [ { @@ -977,7 +972,7 @@ "type": "github" } ], - "time": "2023-09-19T04:57:46+00:00" + "time": "2023-12-22T06:47:57+00:00" }, { "name": "phpunit/php-file-iterator", @@ -1222,16 +1217,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.13", + "version": "9.6.15", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be" + "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f3d767f7f9e191eab4189abe41ab37797e30b1be", - "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/05017b80304e0eb3f31d90194a563fd53a6021f1", + "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1", "shasum": "" }, "require": { @@ -1305,7 +1300,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.13" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.15" }, "funding": [ { @@ -1321,7 +1316,7 @@ "type": "tidelift" } ], - "time": "2023-09-19T05:39:22+00:00" + "time": "2023-12-01T16:55:19+00:00" }, { "name": "psr/container", @@ -1665,20 +1660,20 @@ }, { "name": "sebastian/complexity", - "version": "2.0.2", + "version": "2.0.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/complexity.git", - "reference": "739b35e53379900cc9ac327b2147867b8b6efd88" + "reference": "25f207c40d62b8b7aa32f5ab026c53561964053a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/739b35e53379900cc9ac327b2147867b8b6efd88", - "reference": "739b35e53379900cc9ac327b2147867b8b6efd88", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/25f207c40d62b8b7aa32f5ab026c53561964053a", + "reference": "25f207c40d62b8b7aa32f5ab026c53561964053a", "shasum": "" }, "require": { - "nikic/php-parser": "^4.7", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3" }, "require-dev": { @@ -1710,7 +1705,7 @@ "homepage": "https://github.com/sebastianbergmann/complexity", "support": { "issues": "https://github.com/sebastianbergmann/complexity/issues", - "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.2" + "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.3" }, "funding": [ { @@ -1718,7 +1713,7 @@ "type": "github" } ], - "time": "2020-10-26T15:52:27+00:00" + "time": "2023-12-22T06:19:30+00:00" }, { "name": "sebastian/diff", @@ -1992,20 +1987,20 @@ }, { "name": "sebastian/lines-of-code", - "version": "1.0.3", + "version": "1.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/lines-of-code.git", - "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc" + "reference": "e1e4a170560925c26d424b6a03aed157e7dcc5c5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/c1c2e997aa3146983ed888ad08b15470a2e22ecc", - "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/e1e4a170560925c26d424b6a03aed157e7dcc5c5", + "reference": "e1e4a170560925c26d424b6a03aed157e7dcc5c5", "shasum": "" }, "require": { - "nikic/php-parser": "^4.6", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3" }, "require-dev": { @@ -2037,7 +2032,7 @@ "homepage": "https://github.com/sebastianbergmann/lines-of-code", "support": { "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", - "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.3" + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.4" }, "funding": [ { @@ -2045,7 +2040,7 @@ "type": "github" } ], - "time": "2020-11-28T06:42:11+00:00" + "time": "2023-12-22T06:20:34+00:00" }, { "name": "sebastian/object-enumerator", @@ -2430,7 +2425,7 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.3.0", + "version": "v3.4.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", @@ -2477,7 +2472,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.3.0" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" }, "funding": [ { @@ -2497,16 +2492,16 @@ }, { "name": "theseer/tokenizer", - "version": "1.2.1", + "version": "1.2.2", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e" + "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/34a41e998c2183e22995f158c581e7b5e755ab9e", - "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96", + "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96", "shasum": "" }, "require": { @@ -2535,7 +2530,7 @@ "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", "support": { "issues": "https://github.com/theseer/tokenizer/issues", - "source": "https://github.com/theseer/tokenizer/tree/1.2.1" + "source": "https://github.com/theseer/tokenizer/tree/1.2.2" }, "funding": [ { @@ -2543,7 +2538,7 @@ "type": "github" } ], - "time": "2021-07-28T10:34:58+00:00" + "time": "2023-11-20T00:12:19+00:00" }, { "name": "utopia-php/cli", @@ -2619,5 +2614,5 @@ "php": ">=8.0" }, "platform-dev": [], - "plugin-api-version": "2.3.0" + "plugin-api-version": "2.6.0" } diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 07aaa0baa..ef82631b8 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1038,7 +1038,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1151,7 +1151,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, $where[] = $this->getSQLCondition($query); } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1207,7 +1207,7 @@ public function sum(string $collection, string $attribute, array $queries = [], $where[] = $this->getSQLCondition($query); } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index d788efb3e..a9032f688 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -825,7 +825,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->status) { // skip if authorization is disabled + if ($this->authorization->getStatus()) { // skip if authorization is disabled $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1096,7 +1096,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->status) { // skip if authorization is disabled + if ($this->authorization->getStatus()) { // skip if authorization is disabled $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1129,7 +1129,7 @@ public function sum(string $collection, string $attribute, array $queries = [], $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->status) { // skip if authorization is disabled + if ($this->authorization->getStatus()) { // skip if authorization is disabled $roles = \implode('|', $this->authorization->getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 7cab7fc52..e9b422900 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1046,7 +1046,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1159,7 +1159,7 @@ public function count(string $collection, array $queries = [], ?int $max = null, $where[] = $this->getSQLCondition($query); } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1213,13 +1213,13 @@ public function sum(string $collection, string $attribute, array $queries = [], $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; - $permissions = ($this->authorization->status) ? $this->getSQLPermissionsCondition($collection, $roles) : '1=1'; // Disable join when no authorization required + $permissions = ($this->authorization->getStatus()) ? $this->getSQLPermissionsCondition($collection, $roles) : '1=1'; // Disable join when no authorization required foreach ($queries as $query) { $where[] = $this->getSQLCondition($query); } - if ($this->authorization->status) { + if ($this->authorization->getStatus()) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } diff --git a/src/Database/Database.php b/src/Database/Database.php index dc500b9f0..5484d0693 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -316,19 +316,14 @@ class Database * @param Cache $cache * @param array $filters */ - public function __construct(Adapter $adapter, Cache $cache, array $filters = [], Authorization $authorization = null) + public function __construct(Adapter $adapter, Cache $cache, array $filters = []) { - if (\is_null($authorization)) { - $authorization = new Authorization(); - } - - $adapter->setAuthorization($authorization); - - $this->authorization = $authorization; $this->adapter = $adapter; $this->cache = $cache; $this->instanceFilters = $filters; + $this->setAuthorization(new Authorization()); + self::addFilter( 'json', /** @@ -400,6 +395,19 @@ function (?string $value) { ); } + /** + * Sets instance of authorization for permission checks + * + * @param Authorization $authorization + * @return self + */ + public function setAuthorization(Authorization $authorization): self + { + $this->adapter->setAuthorization($authorization); + $this->authorization = $authorization; + return $this; + } + /** * Add listener to events * diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index c38c74539..a8c7119d8 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -135,7 +135,7 @@ public function isRole(string $role): bool /** * @var bool */ - public bool $status = true; + protected bool $status = true; /** * Default value in case we need @@ -143,7 +143,7 @@ public function isRole(string $role): bool * * @var bool */ - public bool $statusDefault = true; + protected bool $statusDefault = true; /** * Change default status. @@ -159,6 +159,27 @@ public function setDefaultStatus(bool $status): void $this->status = $status; } + /** + * Change status + * + * @param bool $status + * @return void + */ + public function setStatus(bool $status): void + { + $this->status = $status; + } + + /** + * Get status + * + * @return bool + */ + public function getStatus(): bool + { + return $this->status; + } + /** * Skip Authorization * diff --git a/tests/Database/Adapter/MariaDBTest.php b/tests/Database/Adapter/MariaDBTest.php index 813144894..8a38342ec 100644 --- a/tests/Database/Adapter/MariaDBTest.php +++ b/tests/Database/Adapter/MariaDBTest.php @@ -46,7 +46,8 @@ public function getDatabase(): Database $redis->flushAll(); $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new MariaDB($pdo), $cache, [], $this->authorization); + $database = new Database(new MariaDB($pdo), $cache, []); + $database->setAuthorization($this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/MongoDBTest.php b/tests/Database/Adapter/MongoDBTest.php index 1042a6470..293bce1c1 100644 --- a/tests/Database/Adapter/MongoDBTest.php +++ b/tests/Database/Adapter/MongoDBTest.php @@ -51,7 +51,8 @@ public function getDatabase(): Database false ); - $database = new Database(new Mongo($client), $cache, [], $this->authorization); + $database = new Database(new Mongo($client), $cache, []); + $database->setAuthorization($this->authorization); $database->setDefaultDatabase($schema); $database->setNamespace('myapp_' . uniqid()); diff --git a/tests/Database/Adapter/MySQLTest.php b/tests/Database/Adapter/MySQLTest.php index 9397147c2..ed34dad66 100644 --- a/tests/Database/Adapter/MySQLTest.php +++ b/tests/Database/Adapter/MySQLTest.php @@ -57,7 +57,8 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new MySQL($pdo), $cache, [], $this->authorization); + $database = new Database(new MySQL($pdo), $cache, []); + $database->setAuthorization($this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/PostgresTest.php b/tests/Database/Adapter/PostgresTest.php index 644725881..11a67e53c 100644 --- a/tests/Database/Adapter/PostgresTest.php +++ b/tests/Database/Adapter/PostgresTest.php @@ -44,7 +44,8 @@ public function getDatabase(): Database $redis->flushAll(); $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new Postgres($pdo), $cache, [], $this->authorization); + $database = new Database(new Postgres($pdo), $cache, []); + $database->setAuthorization($this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Adapter/SQLiteTest.php b/tests/Database/Adapter/SQLiteTest.php index 0fc463ad8..e12de2e9e 100644 --- a/tests/Database/Adapter/SQLiteTest.php +++ b/tests/Database/Adapter/SQLiteTest.php @@ -60,7 +60,8 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); - $database = new Database(new SQLite($pdo), $cache, [], $this->authorization); + $database = new Database(new SQLite($pdo), $cache, []); + $database->setAuthorization($this->authorization); $database->setDefaultDatabase('utopiaTests'); $database->setNamespace('myapp_'.uniqid()); diff --git a/tests/Database/Validator/AuthorizationTest.php b/tests/Database/Validator/AuthorizationTest.php index 89c98a0ad..30249a873 100644 --- a/tests/Database/Validator/AuthorizationTest.php +++ b/tests/Database/Validator/AuthorizationTest.php @@ -103,24 +103,24 @@ public function testValues(): void public function testNestedSkips(): void { - $this->assertEquals(true, $this->authorization->status); + $this->assertEquals(true, $this->authorization->getStatus()); $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->status); + $this->assertEquals(false, $this->authorization->getStatus()); $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->status); + $this->assertEquals(false, $this->authorization->getStatus()); $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->status); + $this->assertEquals(false, $this->authorization->getStatus()); }); - $this->assertEquals(false, $this->authorization->status); + $this->assertEquals(false, $this->authorization->getStatus()); }); - $this->assertEquals(false, $this->authorization->status); + $this->assertEquals(false, $this->authorization->getStatus()); }); - $this->assertEquals(true, $this->authorization->status); + $this->assertEquals(true, $this->authorization->getStatus()); } } From 00c155306c46bdfa2c899747fded8c1c9a72c562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 3 Jan 2024 15:25:37 +0000 Subject: [PATCH 008/103] Refactor auth message and action --- src/Database/Database.php | 103 ++++++++++-------- src/Database/Exception/Validation.php | 7 ++ src/Database/Validator/Authorization.php | 58 ++++------ .../Database/Validator/AuthorizationTest.php | 3 +- 4 files changed, 91 insertions(+), 80 deletions(-) create mode 100644 src/Database/Exception/Validation.php diff --git a/src/Database/Database.php b/src/Database/Database.php index 5484d0693..74a9e4958 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -13,6 +13,7 @@ use Utopia\Database\Exception\Restricted as RestrictedException; use Utopia\Database\Exception\Structure as StructureException; use Utopia\Database\Exception\Query as QueryException; +use Utopia\Database\Exception\Validation; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; @@ -2255,7 +2256,6 @@ public function getDocument(string $collection, string $id, array $queries = []) $queries = \array_values($queries); - $validator = $this->authorization->setAction(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); $cacheKey = 'cache-' . $this->getNamespace() . ':' . $collection->getId() . ':' . $id; @@ -2269,10 +2269,12 @@ public function getDocument(string $collection, string $id, array $queries = []) $document = new Document($cache); if ($collection->getId() !== self::METADATA) { - if (!$validator->isValid([ - ...$collection->getRead(), - ...($documentSecurity ? $document->getRead() : []) - ])) { + try { + $this->authorization->validate(self::PERMISSION_READ, [ + ...$collection->getRead(), + ...($documentSecurity ? $document->getRead() : []) + ]); + } catch(Validation $err) { return new Document(); } } @@ -2291,10 +2293,12 @@ public function getDocument(string $collection, string $id, array $queries = []) $document->setAttribute('$collection', $collection->getId()); if ($collection->getId() !== self::METADATA) { - if (!$validator->isValid([ - ...$collection->getRead(), - ...($documentSecurity ? $document->getRead() : []) - ])) { + try { + $this->authorization->validate(self::PERMISSION_READ, [ + ...$collection->getRead(), + ...($documentSecurity ? $document->getRead() : []) + ]); + } catch(Validation $err) { return new Document(); } } @@ -2613,9 +2617,10 @@ public function createDocument(string $collection, Document $document): Document $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { - $authorization = $this->authorization->setAction(self::PERMISSION_CREATE); - if (!$authorization->isValid($collection->getCreate())) { - throw new AuthorizationException($authorization->getDescription()); + try { + $this->authorization->validate(self::PERMISSION_CREATE, $collection->getCreate()); + } catch(Validation $err) { + throw new AuthorizationException($err->getMessage()); } } @@ -2963,7 +2968,6 @@ public function updateDocument(string $collection, string $id, Document $documen return $attribute['type'] === Database::VAR_RELATIONSHIP; }); - $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); $shouldUpdate = false; if ($collection->getId() !== self::METADATA) { @@ -3050,11 +3054,15 @@ public function updateDocument(string $collection, string $id, Document $documen } } - if ($shouldUpdate && !$validator->isValid([ - ...$collection->getUpdate(), - ...($documentSecurity ? $old->getUpdate() : []) - ])) { - throw new AuthorizationException($validator->getDescription()); + if ($shouldUpdate) { + try { + $this->authorization->validate(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $old->getUpdate() : []) + ]); + } catch(Validation $err) { + throw new AuthorizationException($err->getMessage()); + } } } @@ -3496,19 +3504,19 @@ public function increaseDocumentAttribute(string $collection, string $id, string throw new DatabaseException('Value must be numeric and greater than 0'); } - $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - if (!$validator->isValid([ - ...$collection->getUpdate(), - ...($documentSecurity ? $document->getUpdate() : []) - ])) { - throw new AuthorizationException($validator->getDescription()); + try { + $this->authorization->validate(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $document->getUpdate() : []) + ]); + } catch(Validation $err) { + throw new AuthorizationException($err->getMessage()); } } @@ -3563,19 +3571,19 @@ public function decreaseDocumentAttribute(string $collection, string $id, string throw new DatabaseException('Value must be numeric and greater than 0'); } - $validator = $this->authorization->setAction(self::PERMISSION_UPDATE); - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - if (!$validator->isValid([ - ...$collection->getUpdate(), - ...($documentSecurity ? $document->getUpdate() : []) - ])) { - throw new AuthorizationException($validator->getDescription()); + try { + $this->authorization->validate(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $document->getUpdate() : []) + ]); + } catch(Validation $err) { + throw new AuthorizationException($err->getMessage()); } } @@ -3628,15 +3636,15 @@ public function deleteDocument(string $collection, string $id): bool $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this $collection = $this->silent(fn () => $this->getCollection($collection)); - $validator = $this->authorization->setAction(self::PERMISSION_DELETE); - if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - if (!$validator->isValid([ - ...$collection->getDelete(), - ...($documentSecurity ? $document->getDelete() : []) - ])) { - throw new AuthorizationException($validator->getDescription()); + try { + $this->authorization->validate(self::PERMISSION_DELETE, [ + ...$collection->getDelete(), + ...($documentSecurity ? $document->getDelete() : []) + ]); + } catch(Validation $err) { + throw new AuthorizationException($err->getMessage()); } } @@ -4089,9 +4097,14 @@ public function find(string $collection, array $queries = [], ?int $timeout = nu throw new QueryException($validator->getDescription()); } - $authorization = $this->authorization->setAction(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $authorization->isValid($collection->getRead()); + + try { + $this->authorization->validate(self::PERMISSION_READ, $collection->getRead()); + $skipAuth = true; + } catch(Validation $err) { + $skipAuth = false; + } if (!$skipAuth && !$documentSecurity) { throw new AuthorizationException($validator->getDescription()); @@ -4261,16 +4274,18 @@ public function count(string $collection, array $queries = [], ?int $max = null) throw new QueryException($validator->getDescription()); } - $authorization = $this->authorization->setAction(self::PERMISSION_READ); - if ($authorization->isValid($collection->getRead())) { + try { + $this->authorization->validate(self::PERMISSION_READ, $collection->getRead()); $skipAuth = true; + } catch(Validation $err) { + $skipAuth = false; } $queries = Query::groupByType($queries)['filters']; $queries = self::convertQueries($collection, $queries); $getCount = fn () => $this->adapter->count($collection->getId(), $queries, $max); - $count = $skipAuth ?? false ? $this->authorization->skip($getCount) : $getCount(); + $count = $skipAuth ? $this->authorization->skip($getCount) : $getCount(); $this->trigger(self::EVENT_DOCUMENT_COUNT, $count); diff --git a/src/Database/Exception/Validation.php b/src/Database/Exception/Validation.php new file mode 100644 index 000000000..9e554b443 --- /dev/null +++ b/src/Database/Exception/Validation.php @@ -0,0 +1,7 @@ + true ]; - /** - * @var string - */ - protected string $action = ''; - /** * @var string */ protected string $message = 'Authorization Error'; - /** - * @param string $action - */ - public function __construct(string $action = '') - { - $this->action = $action; - } - - /** - * @param string $action - * @return self - */ - public function setAction(string $action): self - { - $this->action = $action; - - return $this; - } - /** * Get Description. * @@ -54,37 +31,50 @@ public function getDescription(): string return $this->message; } + /* + * Deprecated for this specific validator. Use validate() instead + */ + public function isValid(mixed $permissions): bool + { + try { + $this->validate('unknownAction', $permissions); + return true; + } catch(Validation $error) { + $this->message = $error->getMessage(); + return false; + } + } + /** - * Is valid. + * Validation. Replacement of isValid() which throws exception instead * * Returns true if valid or false if not. * + * @param string $action * @param mixed $permissions * - * @return bool + * @return void + * @throws Validation */ - public function isValid($permissions): bool + public function validate(string $action, mixed $permissions): void { if (!$this->status) { - return true; + return; } if (empty($permissions)) { - $this->message = 'No permissions provided for action \''.$this->action.'\''; - return false; + throw new Validation('No permissions provided for action \''.$action.'\''); } $permission = '-'; foreach ($permissions as $permission) { if (\array_key_exists($permission, $this->roles)) { - return true; + return; } } - $this->message = 'Missing "'.$this->action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; - - return false; + throw new Validation('Missing "'.$action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'); } /** diff --git a/tests/Database/Validator/AuthorizationTest.php b/tests/Database/Validator/AuthorizationTest.php index 30249a873..10f91370d 100644 --- a/tests/Database/Validator/AuthorizationTest.php +++ b/tests/Database/Validator/AuthorizationTest.php @@ -2,7 +2,6 @@ namespace Utopia\Tests\Validator; -use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -39,7 +38,7 @@ public function testValues(): void ], ]); - $object = $this->authorization->setAction(Database::PERMISSION_READ); + $object = $this->authorization; $this->assertEquals($object->isValid($document->getRead()), false); $this->assertEquals($object->isValid(''), false); From c2f3585ef0375ac77f6b8606a9d6ac4dce4730ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 3 Jan 2024 15:36:12 +0000 Subject: [PATCH 009/103] Fix test --- tests/Database/Validator/AuthorizationTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Database/Validator/AuthorizationTest.php b/tests/Database/Validator/AuthorizationTest.php index 10f91370d..edcea2bac 100644 --- a/tests/Database/Validator/AuthorizationTest.php +++ b/tests/Database/Validator/AuthorizationTest.php @@ -43,7 +43,7 @@ public function testValues(): void $this->assertEquals($object->isValid($document->getRead()), false); $this->assertEquals($object->isValid(''), false); $this->assertEquals($object->isValid([]), false); - $this->assertEquals($object->getDescription(), 'No permissions provided for action \'read\''); + $this->assertEquals($object->getDescription(), 'No permissions provided for action \'unknownAction\''); $this->authorization->setRole(Role::user('456')->toString()); $this->authorization->setRole(Role::user('123')->toString()); From 59588d6b28366a64eaafdc483a4b496c21fda8ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 24 Jan 2024 09:22:34 +0000 Subject: [PATCH 010/103] Make auth validator follow adapter --- README.md | 2 +- bin/tasks/load.php | 2 +- bin/tasks/query.php | 2 +- src/Database/Database.php | 96 +++++++++--------- src/Database/Validator/Authorization.php | 74 ++++++-------- .../Validator/Authorization/Input.php | 49 ++++++++++ tests/Database/Base.php | 98 +++++++++---------- .../Database/Validator/AuthorizationTest.php | 41 ++++---- 8 files changed, 199 insertions(+), 165 deletions(-) create mode 100644 src/Database/Validator/Authorization/Input.php diff --git a/README.md b/README.md index f9792d101..6d6239add 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ A list of the utopia/php concepts and their relevant equivalent using the differ - **Document** - A simple JSON object that will be stored in one of the utopia/database collections. For SQL-based adapters, this will be equivalent to a row. For a No-SQL adapter, this will equivalent to a native document. - **Attribute** - A simple document attribute. For SQL-based adapters, this will be equivalent to a column. For a No-SQL adapter, this will equivalent to a native document field. - **Index** - A simple collection index used to improve the performance of your database queries. -- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `Authorization::setRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. +- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `Authorization::addRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. ### Filters diff --git a/bin/tasks/load.php b/bin/tasks/load.php index 336da747d..68f04a58f 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -232,7 +232,7 @@ function createSchema(Database $database): void } $database->create(); - Authorization::setRole(Role::any()->toString()); + Authorization::addRole(Role::any()->toString()); $database->createCollection('articles', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 5f718e1f9..c06690d90 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -177,7 +177,7 @@ function runQueries(Database $database, int $limit) function addRoles($faker, $count) { for ($i = 0; $i < $count; $i++) { - Authorization::setRole($faker->numerify('user####')); + Authorization::addRole($faker->numerify('user####')); } return count(Authorization::getRoles()); } diff --git a/src/Database/Database.php b/src/Database/Database.php index 74a9e4958..4ea0cb286 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -18,6 +18,7 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; +use Utopia\Database\Validator\Authorization\Input; use Utopia\Database\Validator\Queries\Document as DocumentValidator; use Utopia\Database\Validator\Queries\Documents as DocumentsValidator; use Utopia\Database\Validator\Index as IndexValidator; @@ -2269,12 +2270,12 @@ public function getDocument(string $collection, string $id, array $queries = []) $document = new Document($cache); if ($collection->getId() !== self::METADATA) { - try { - $this->authorization->validate(self::PERMISSION_READ, [ - ...$collection->getRead(), - ...($documentSecurity ? $document->getRead() : []) - ]); - } catch(Validation $err) { + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + ...$collection->getRead(), + ...($documentSecurity ? $document->getRead() : []) + ])); + + if (!$isValid) { return new Document(); } } @@ -2293,12 +2294,12 @@ public function getDocument(string $collection, string $id, array $queries = []) $document->setAttribute('$collection', $collection->getId()); if ($collection->getId() !== self::METADATA) { - try { - $this->authorization->validate(self::PERMISSION_READ, [ - ...$collection->getRead(), - ...($documentSecurity ? $document->getRead() : []) - ]); - } catch(Validation $err) { + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + ...$collection->getRead(), + ...($documentSecurity ? $document->getRead() : []) + ])); + + if (!$isValid) { return new Document(); } } @@ -2617,10 +2618,9 @@ public function createDocument(string $collection, Document $document): Document $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { - try { - $this->authorization->validate(self::PERMISSION_CREATE, $collection->getCreate()); - } catch(Validation $err) { - throw new AuthorizationException($err->getMessage()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_CREATE, $collection->getCreate())); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } @@ -3055,13 +3055,12 @@ public function updateDocument(string $collection, string $id, Document $documen } if ($shouldUpdate) { - try { - $this->authorization->validate(self::PERMISSION_UPDATE, [ - ...$collection->getUpdate(), - ...($documentSecurity ? $old->getUpdate() : []) - ]); - } catch(Validation $err) { - throw new AuthorizationException($err->getMessage()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $old->getUpdate() : []) + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } } @@ -3510,13 +3509,12 @@ public function increaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - try { - $this->authorization->validate(self::PERMISSION_UPDATE, [ - ...$collection->getUpdate(), - ...($documentSecurity ? $document->getUpdate() : []) - ]); - } catch(Validation $err) { - throw new AuthorizationException($err->getMessage()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $document->getUpdate() : []) + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } @@ -3577,13 +3575,12 @@ public function decreaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - try { - $this->authorization->validate(self::PERMISSION_UPDATE, [ - ...$collection->getUpdate(), - ...($documentSecurity ? $document->getUpdate() : []) - ]); - } catch(Validation $err) { - throw new AuthorizationException($err->getMessage()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $document->getUpdate() : []) + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } @@ -3638,13 +3635,12 @@ public function deleteDocument(string $collection, string $id): bool if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - try { - $this->authorization->validate(self::PERMISSION_DELETE, [ - ...$collection->getDelete(), - ...($documentSecurity ? $document->getDelete() : []) - ]); - } catch(Validation $err) { - throw new AuthorizationException($err->getMessage()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ + ...$collection->getDelete(), + ...($documentSecurity ? $document->getDelete() : []) + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } @@ -4099,10 +4095,10 @@ public function find(string $collection, array $queries = [], ?int $timeout = nu $documentSecurity = $collection->getAttribute('documentSecurity', false); - try { - $this->authorization->validate(self::PERMISSION_READ, $collection->getRead()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + if ($isValid) { $skipAuth = true; - } catch(Validation $err) { + } else { $skipAuth = false; } @@ -4274,10 +4270,10 @@ public function count(string $collection, array $queries = [], ?int $max = null) throw new QueryException($validator->getDescription()); } - try { - $this->authorization->validate(self::PERMISSION_READ, $collection->getRead()); + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + if ($isValid) { $skipAuth = true; - } catch(Validation $err) { + } else { $skipAuth = false; } diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 1dc40dc6a..cbd10d94a 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -3,10 +3,24 @@ namespace Utopia\Database\Validator; use Utopia\Database\Exception\Validation; +use Utopia\Database\Validator\Authorization\Input; use Utopia\Http\Validator; class Authorization extends Validator { + /** + * @var bool + */ + protected bool $status = true; + + /** + * Default value in case we need + * to reset Authorization status + * + * @var bool + */ + protected bool $statusDefault = true; + /** * @var array */ @@ -32,56 +46,44 @@ public function getDescription(): string } /* - * Deprecated for this specific validator. Use validate() instead - */ - public function isValid(mixed $permissions): bool - { - try { - $this->validate('unknownAction', $permissions); - return true; - } catch(Validation $error) { - $this->message = $error->getMessage(); - return false; - } - } - - /** - * Validation. Replacement of isValid() which throws exception instead + * Validation * * Returns true if valid or false if not. - * - * @param string $action - * @param mixed $permissions - * - * @return void - * @throws Validation - */ - public function validate(string $action, mixed $permissions): void + */ + public function isValid(mixed $input): bool { + /** + * @var Input $input + */ + $permissions = $input->getPermissions(); + $action = $input->getAction(); + if (!$this->status) { - return; + return true; } if (empty($permissions)) { - throw new Validation('No permissions provided for action \''.$action.'\''); + $this->message = 'No permissions provided for action \''.$action.'\''; + return false; } $permission = '-'; foreach ($permissions as $permission) { if (\array_key_exists($permission, $this->roles)) { - return; + return true; } } - throw new Validation('Missing "'.$action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'); + $this->message = 'Missing "'.$action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + return false; } /** * @param string $role * @return void */ - public function setRole(string $role): void + public function addRole(string $role): void { $this->roles[$role] = true; } @@ -91,7 +93,7 @@ public function setRole(string $role): void * * @return void */ - public function unsetRole(string $role): void + public function removeRole(string $role): void { unset($this->roles[$role]); } @@ -122,24 +124,10 @@ public function isRole(string $role): bool return (\array_key_exists($role, $this->roles)); } - /** - * @var bool - */ - protected bool $status = true; - - /** - * Default value in case we need - * to reset Authorization status - * - * @var bool - */ - protected bool $statusDefault = true; - /** * Change default status. * This will be used for the * value set on the $this->reset() method - * * @param bool $status * @return void */ diff --git a/src/Database/Validator/Authorization/Input.php b/src/Database/Validator/Authorization/Input.php new file mode 100644 index 000000000..4c2387097 --- /dev/null +++ b/src/Database/Validator/Authorization/Input.php @@ -0,0 +1,49 @@ +permissions = $permissions; + $this->action = $action; + } + + /** + * @param string[] $permissions + */ + public function setPermissions(array $permissions): self + { + $this->permissions = $permissions; + return $this; + } + + public function setAction(string $action): self + { + $this->action = $action; + return $this; + } + + /** + * @return string[] + */ + public function getPermissions(): array + { + return $this->permissions; + } + + public function getAction(): string + { + return $this->action; + } +} diff --git a/tests/Database/Base.php b/tests/Database/Base.php index 557888ade..aaa060c09 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -53,11 +53,11 @@ public function setUp(): void { if (is_null(self::$authorizationSingleton)) { self::$authorizationSingleton = new Authorization(); - self::$authorizationSingleton->setRole('any'); + self::$authorizationSingleton->addRole('any'); } $this->authorization = self::$authorizationSingleton; - $this->authorization->setRole('any'); + $this->authorization->addRole('any'); } public function tearDown(): void @@ -1498,7 +1498,7 @@ public function testDeleteDocument(Document $document): void */ public function testFind(): array { - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) @@ -1732,7 +1732,7 @@ public function testFindCheckPermissions(): void /** * Check Permissions */ - $this->authorization->setRole('user:x'); + $this->authorization->addRole('user:x'); $documents = $this->getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); @@ -2980,7 +2980,7 @@ public function testCount(): void $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); - $this->authorization->unsetRole('user:x'); + $this->authorization->removeRole('user:x'); $count = $this->getDatabase()->count('movies'); $this->assertEquals(5, $count); @@ -3011,7 +3011,7 @@ public function testCount(): void */ public function testSum(): void { - $this->authorization->setRole('user:x'); + $this->authorization->addRole('user:x'); $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = $this->getDatabase()->sum('movies', 'year'); @@ -3024,8 +3024,8 @@ public function testSum(): void $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); - $this->authorization->unsetRole('user:x'); - $this->authorization->unsetRole('userx'); + $this->authorization->removeRole('user:x'); + $this->authorization->removeRole('userx'); $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = $this->getDatabase()->sum('movies', 'year'); @@ -3286,7 +3286,7 @@ public function testEncodeDecode(): void public function testReadPermissionsSuccess(Document $document): Document { $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3310,7 +3310,7 @@ public function testReadPermissionsSuccess(Document $document): Document $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); return $document; } @@ -3318,7 +3318,7 @@ public function testReadPermissionsSuccess(Document $document): Document public function testReadPermissionsFailure(): Document { $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3341,7 +3341,7 @@ public function testReadPermissionsFailure(): Document $this->assertEquals(true, $document->isEmpty()); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); return $document; } @@ -3378,7 +3378,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document $this->expectException(AuthorizationException::class); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -3812,7 +3812,7 @@ public function testUniqueIndexDuplicate(): void */ public function testUniqueIndexDuplicateUpdate(): void { - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); // create document then update to conflict with index $document = $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ @@ -4469,7 +4469,7 @@ public function testKeywords(): void public function testWritePermissions(): void { - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $database = $this->getDatabase(); $database->createCollection('animals', permissions: [ @@ -9987,7 +9987,7 @@ public function testEnforceRelationshipPermissions(): void return; } $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); @@ -10064,7 +10064,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $this->authorization->setRole(Role::user('user1')->toString()); + $this->authorization->addRole(Role::user('user1')->toString()); $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); @@ -10077,7 +10077,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Bird 1 Updated', $bird1['name']); - $this->authorization->setRole(Role::user('user2')->toString()); + $this->authorization->addRole(Role::user('user2')->toString()); // Try delete multi-level nested document $deleted = $this->getDatabase()->deleteDocument( @@ -11352,7 +11352,7 @@ public function testCollectionPermissionsExceptions(): void public function testCollectionPermissionsCreateWorks(Document $collection): array { $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -11375,7 +11375,7 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra public function testCollectionPermissionsCreateThrowsException(Document $collection): void { $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->createDocument($collection->getId(), new Document([ @@ -11399,7 +11399,7 @@ public function testCollectionPermissionsGetWorks(array $data): array [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -11420,7 +11420,7 @@ public function testCollectionPermissionsGetThrowsException(array $data): void [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -11440,13 +11440,13 @@ public function testCollectionPermissionsFindWorks(array $data): array [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('random')->toString()); + $this->authorization->addRole(Role::user('random')->toString()); try { $this->getDatabase()->find($collection->getId()); @@ -11466,7 +11466,7 @@ public function testCollectionPermissionsFindThrowsException(array $data): void [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->find($collection->getId()); @@ -11482,7 +11482,7 @@ public function testCollectionPermissionsCountWorks(array $data): array [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $count = $this->getDatabase()->count( $collection->getId() @@ -11502,7 +11502,7 @@ public function testCollectionPermissionsCountThrowsException(array $data): void [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $count = $this->getDatabase()->count( $collection->getId() @@ -11520,7 +11520,7 @@ public function testCollectionPermissionsUpdateWorks(array $data): array [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $this->assertInstanceOf(Document::class, $this->getDatabase()->updateDocument( $collection->getId(), @@ -11539,7 +11539,7 @@ public function testCollectionPermissionsUpdateThrowsException(array $data): voi { [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->updateDocument( @@ -11558,7 +11558,7 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->deleteDocument( @@ -11576,7 +11576,7 @@ public function testCollectionPermissionsDeleteWorks(array $data): void [$collection, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), @@ -11668,7 +11668,7 @@ public function testCollectionPermissionsRelationshipsCreateWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -11721,7 +11721,7 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra [$collection, $collectionOneToOne, $collectionOneToMany] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->createDocument($collection->getId(), new Document([ @@ -11744,7 +11744,7 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -11758,7 +11758,7 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->assertFalse($document->isEmpty()); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('random')->toString()); + $this->authorization->addRole(Role::user('random')->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -11783,7 +11783,7 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -11802,7 +11802,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -11818,7 +11818,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertFalse($document->isEmpty()); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('random')->toString()); + $this->authorization->addRole(Role::user('random')->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -11834,7 +11834,7 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertFalse($document->isEmpty()); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('unknown')->toString()); + $this->authorization->addRole(Role::user('unknown')->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -11853,7 +11853,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -11862,7 +11862,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('random')->toString()); + $this->authorization->addRole(Role::user('random')->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -11871,7 +11871,7 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('unknown')->toString()); + $this->authorization->addRole(Role::user('unknown')->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -11890,7 +11890,7 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), @@ -11900,7 +11900,7 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->assertTrue(true); $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('random')->toString()); + $this->authorization->addRole(Role::user('random')->toString()); $this->getDatabase()->updateDocument( $collection->getId(), @@ -11922,7 +11922,7 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->updateDocument( @@ -11941,7 +11941,7 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->deleteDocument( @@ -11959,7 +11959,7 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::users()->toString()); + $this->authorization->addRole(Role::users()->toString()); $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), @@ -11975,7 +11975,7 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void } $this->authorization->cleanRoles(); - $this->authorization->setRole(Role::user('a')->toString()); + $this->authorization->addRole(Role::user('a')->toString()); $this->getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), @@ -12340,7 +12340,7 @@ public function testLabels(): void $this->assertEmpty($documents); - $this->authorization->setRole(Role::label('reader')->toString()); + $this->authorization->addRole(Role::label('reader')->toString()); $documents = $this->getDatabase()->find('labels_test'); diff --git a/tests/Database/Validator/AuthorizationTest.php b/tests/Database/Validator/AuthorizationTest.php index edcea2bac..a6619597d 100644 --- a/tests/Database/Validator/AuthorizationTest.php +++ b/tests/Database/Validator/AuthorizationTest.php @@ -8,6 +8,8 @@ use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; use PHPUnit\Framework\TestCase; +use Utopia\Database\Database; +use Utopia\Database\Validator\Authorization\Input; class AuthorizationTest extends TestCase { @@ -24,7 +26,7 @@ public function tearDown(): void public function testValues(): void { - $this->authorization->setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); $document = new Document([ '$id' => ID::unique(), @@ -40,63 +42,62 @@ public function testValues(): void $object = $this->authorization; - $this->assertEquals($object->isValid($document->getRead()), false); - $this->assertEquals($object->isValid(''), false); - $this->assertEquals($object->isValid([]), false); - $this->assertEquals($object->getDescription(), 'No permissions provided for action \'unknownAction\''); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, [])), false); + $this->assertEquals($object->getDescription(), 'No permissions provided for action \'read\''); - $this->authorization->setRole(Role::user('456')->toString()); - $this->authorization->setRole(Role::user('123')->toString()); + $this->authorization->addRole(Role::user('456')->toString()); + $this->authorization->addRole(Role::user('123')->toString()); $this->assertEquals($this->authorization->isRole(Role::user('456')->toString()), true); $this->assertEquals($this->authorization->isRole(Role::user('457')->toString()), false); $this->assertEquals($this->authorization->isRole(''), false); $this->assertEquals($this->authorization->isRole(Role::any()->toString()), true); - $this->assertEquals($object->isValid($document->getRead()), true); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); $this->authorization->cleanRoles(); - $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->authorization->setRole(Role::team('123')->toString()); + $this->authorization->addRole(Role::team('123')->toString()); - $this->assertEquals($object->isValid($document->getRead()), true); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); $this->authorization->cleanRoles(); $this->authorization->disable(); - $this->assertEquals($object->isValid($document->getRead()), true); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); $this->authorization->reset(); - $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); $this->authorization->setDefaultStatus(false); $this->authorization->disable(); - $this->assertEquals($object->isValid($document->getRead()), true); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); $this->authorization->reset(); - $this->assertEquals($object->isValid($document->getRead()), true); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); $this->authorization->enable(); - $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->authorization->setRole('textX'); + $this->authorization->addRole('textX'); $this->assertContains('textX', $this->authorization->getRoles()); - $this->authorization->unsetRole('textX'); + $this->authorization->removeRole('textX'); $this->assertNotContains('textX', $this->authorization->getRoles()); // Test skip method - $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); $this->assertEquals($this->authorization->skip(function () use ($object, $document) { - return $object->isValid($document->getRead()); + return $object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())); }), true); } From e79ddd1fee25da5194c0e3ceb481d3fa7bdab9b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 24 Jan 2024 11:40:22 +0000 Subject: [PATCH 011/103] Upgrade dependencies --- composer.json | 4 +- composer.lock | 167 +++++++++++++++++++++++--------------------------- 2 files changed, 77 insertions(+), 94 deletions(-) diff --git a/composer.json b/composer.json index 433bcb29c..b95db1f4e 100755 --- a/composer.json +++ b/composer.json @@ -33,7 +33,7 @@ "ext-pdo": "*", "ext-mbstring": "*", "php": ">=8.0", - "utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0", + "utopia-php/framework": "0.34.*", "utopia-php/cache": "0.8.*", "utopia-php/mongo": "0.3.*" }, @@ -42,7 +42,7 @@ "phpunit/phpunit": "^9.4", "pcov/clobber": "^2.0", "swoole/ide-helper": "4.8.0", - "utopia-php/cli": "^0.14.0", + "utopia-php/cli": "0.17.*", "laravel/pint": "1.4.*", "phpstan/phpstan": "1.10.*", "rregeer/phpunit-coverage-check": "^0.3.1" diff --git a/composer.lock b/composer.lock index b9555f4af..41869676b 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "b01ce402808990664d677e2754c65578", + "content-hash": "6b10d5fedb04d606c7bd14223303496f", "packages": [ { "name": "jean85/pretty-package-versions", @@ -268,16 +268,16 @@ }, { "name": "utopia-php/framework", - "version": "dev-fix-v2-swoole-coroutines", + "version": "0.34.0", "source": { "type": "git", - "url": "https://github.com/utopia-php/framework.git", - "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef" + "url": "https://github.com/utopia-php/http.git", + "reference": "f1f0df17b2fbe855b210a707320a3c85288a3c00" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/framework/zipball/e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", - "reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef", + "url": "https://api.github.com/repos/utopia-php/http/zipball/f1f0df17b2fbe855b210a707320a3c85288a3c00", + "reference": "f1f0df17b2fbe855b210a707320a3c85288a3c00", "shasum": "" }, "require": { @@ -301,17 +301,18 @@ "license": [ "MIT" ], - "description": "A simple, light and advanced PHP framework", + "description": "A simple, light and advanced PHP HTTP framework", "keywords": [ "framework", + "http", "php", "upf" ], "support": { - "issues": "https://github.com/utopia-php/framework/issues", - "source": "https://github.com/utopia-php/framework/tree/fix-v2-swoole-coroutines" + "issues": "https://github.com/utopia-php/http/issues", + "source": "https://github.com/utopia-php/http/tree/0.34.0" }, - "time": "2023-10-04T11:53:40+00:00" + "time": "2024-01-24T10:01:25+00:00" }, { "name": "utopia-php/mongo", @@ -447,16 +448,16 @@ }, { "name": "fakerphp/faker", - "version": "v1.23.0", + "version": "v1.23.1", "source": { "type": "git", "url": "https://github.com/FakerPHP/Faker.git", - "reference": "e3daa170d00fde61ea7719ef47bb09bb8f1d9b01" + "reference": "bfb4fe148adbf78eff521199619b93a52ae3554b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/FakerPHP/Faker/zipball/e3daa170d00fde61ea7719ef47bb09bb8f1d9b01", - "reference": "e3daa170d00fde61ea7719ef47bb09bb8f1d9b01", + "url": "https://api.github.com/repos/FakerPHP/Faker/zipball/bfb4fe148adbf78eff521199619b93a52ae3554b", + "reference": "bfb4fe148adbf78eff521199619b93a52ae3554b", "shasum": "" }, "require": { @@ -482,11 +483,6 @@ "ext-mbstring": "Required for multibyte Unicode string functionality." }, "type": "library", - "extra": { - "branch-alias": { - "dev-main": "v1.21-dev" - } - }, "autoload": { "psr-4": { "Faker\\": "src/Faker/" @@ -509,9 +505,9 @@ ], "support": { "issues": "https://github.com/FakerPHP/Faker/issues", - "source": "https://github.com/FakerPHP/Faker/tree/v1.23.0" + "source": "https://github.com/FakerPHP/Faker/tree/v1.23.1" }, - "time": "2023-06-12T08:44:38+00:00" + "time": "2024-01-02T13:46:09+00:00" }, { "name": "laravel/pint", @@ -640,16 +636,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.17.1", + "version": "v4.18.0", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d" + "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", - "reference": "a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1bcbb2179f97633e98bbbc87044ee2611c7d7999", + "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999", "shasum": "" }, "require": { @@ -690,9 +686,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.17.1" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.18.0" }, - "time": "2023-08-13T19:53:39+00:00" + "time": "2023-12-10T21:03:43+00:00" }, { "name": "pcov/clobber", @@ -841,16 +837,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.37", + "version": "1.10.56", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e" + "reference": "27816a01aea996191ee14d010f325434c0ee76fa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/058ba07e92f744d4dcf6061ae75283d0c6456f2e", - "reference": "058ba07e92f744d4dcf6061ae75283d0c6456f2e", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/27816a01aea996191ee14d010f325434c0ee76fa", + "reference": "27816a01aea996191ee14d010f325434c0ee76fa", "shasum": "" }, "require": { @@ -899,27 +895,27 @@ "type": "tidelift" } ], - "time": "2023-10-02T16:18:37+00:00" + "time": "2024-01-15T10:43:00+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "9.2.29", + "version": "9.2.30", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76" + "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6a3a87ac2bbe33b25042753df8195ba4aa534c76", - "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/ca2bd87d2f9215904682a9cb9bb37dda98e76089", + "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089", "shasum": "" }, "require": { "ext-dom": "*", "ext-libxml": "*", "ext-xmlwriter": "*", - "nikic/php-parser": "^4.15", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3", "phpunit/php-file-iterator": "^3.0.3", "phpunit/php-text-template": "^2.0.2", @@ -969,7 +965,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.29" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.30" }, "funding": [ { @@ -977,7 +973,7 @@ "type": "github" } ], - "time": "2023-09-19T04:57:46+00:00" + "time": "2023-12-22T06:47:57+00:00" }, { "name": "phpunit/php-file-iterator", @@ -1222,16 +1218,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.13", + "version": "9.6.16", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be" + "reference": "3767b2c56ce02d01e3491046f33466a1ae60a37f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f3d767f7f9e191eab4189abe41ab37797e30b1be", - "reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/3767b2c56ce02d01e3491046f33466a1ae60a37f", + "reference": "3767b2c56ce02d01e3491046f33466a1ae60a37f", "shasum": "" }, "require": { @@ -1305,7 +1301,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.13" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.16" }, "funding": [ { @@ -1321,7 +1317,7 @@ "type": "tidelift" } ], - "time": "2023-09-19T05:39:22+00:00" + "time": "2024-01-19T07:03:14+00:00" }, { "name": "psr/container", @@ -1665,20 +1661,20 @@ }, { "name": "sebastian/complexity", - "version": "2.0.2", + "version": "2.0.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/complexity.git", - "reference": "739b35e53379900cc9ac327b2147867b8b6efd88" + "reference": "25f207c40d62b8b7aa32f5ab026c53561964053a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/739b35e53379900cc9ac327b2147867b8b6efd88", - "reference": "739b35e53379900cc9ac327b2147867b8b6efd88", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/25f207c40d62b8b7aa32f5ab026c53561964053a", + "reference": "25f207c40d62b8b7aa32f5ab026c53561964053a", "shasum": "" }, "require": { - "nikic/php-parser": "^4.7", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3" }, "require-dev": { @@ -1710,7 +1706,7 @@ "homepage": "https://github.com/sebastianbergmann/complexity", "support": { "issues": "https://github.com/sebastianbergmann/complexity/issues", - "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.2" + "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.3" }, "funding": [ { @@ -1718,7 +1714,7 @@ "type": "github" } ], - "time": "2020-10-26T15:52:27+00:00" + "time": "2023-12-22T06:19:30+00:00" }, { "name": "sebastian/diff", @@ -1992,20 +1988,20 @@ }, { "name": "sebastian/lines-of-code", - "version": "1.0.3", + "version": "1.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/lines-of-code.git", - "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc" + "reference": "e1e4a170560925c26d424b6a03aed157e7dcc5c5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/c1c2e997aa3146983ed888ad08b15470a2e22ecc", - "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/e1e4a170560925c26d424b6a03aed157e7dcc5c5", + "reference": "e1e4a170560925c26d424b6a03aed157e7dcc5c5", "shasum": "" }, "require": { - "nikic/php-parser": "^4.6", + "nikic/php-parser": "^4.18 || ^5.0", "php": ">=7.3" }, "require-dev": { @@ -2037,7 +2033,7 @@ "homepage": "https://github.com/sebastianbergmann/lines-of-code", "support": { "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", - "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.3" + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.4" }, "funding": [ { @@ -2045,7 +2041,7 @@ "type": "github" } ], - "time": "2020-11-28T06:42:11+00:00" + "time": "2023-12-22T06:20:34+00:00" }, { "name": "sebastian/object-enumerator", @@ -2430,7 +2426,7 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.3.0", + "version": "v3.4.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", @@ -2477,7 +2473,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.3.0" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" }, "funding": [ { @@ -2497,16 +2493,16 @@ }, { "name": "theseer/tokenizer", - "version": "1.2.1", + "version": "1.2.2", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e" + "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/34a41e998c2183e22995f158c581e7b5e755ab9e", - "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96", + "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96", "shasum": "" }, "require": { @@ -2535,7 +2531,7 @@ "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", "support": { "issues": "https://github.com/theseer/tokenizer/issues", - "source": "https://github.com/theseer/tokenizer/tree/1.2.1" + "source": "https://github.com/theseer/tokenizer/tree/1.2.2" }, "funding": [ { @@ -2543,29 +2539,31 @@ "type": "github" } ], - "time": "2021-07-28T10:34:58+00:00" + "time": "2023-11-20T00:12:19+00:00" }, { "name": "utopia-php/cli", - "version": "0.14.0", + "version": "0.17.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/0829fd5215afe88f53f3091cedc808da801fd1bb", + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/framework": "0.*.*" + "utopia-php/framework": "0.34.*" }, "require-dev": { + "laravel/pint": "1.2.*", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6" + "squizlabs/php_codesniffer": "^3.6", + "vimeo/psalm": "4.0.1" }, "type": "library", "autoload": { @@ -2577,12 +2575,6 @@ "license": [ "MIT" ], - "authors": [ - { - "name": "Eldad Fux", - "email": "eldad@appwrite.io" - } - ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2594,23 +2586,14 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.14.0" + "source": "https://github.com/utopia-php/cli/tree/0.17.0" }, - "time": "2022-10-09T10:19:07+00:00" - } - ], - "aliases": [ - { - "package": "utopia-php/framework", - "version": "dev-fix-v2-swoole-coroutines", - "alias": "0.31.0", - "alias_normalized": "0.31.0.0" + "time": "2024-01-24T11:37:29+00:00" } ], + "aliases": [], "minimum-stability": "stable", - "stability-flags": { - "utopia-php/framework": 20 - }, + "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, "platform": { From f55b13dedc1320e57103612072caa1f9752e0480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 24 Jan 2024 11:48:23 +0000 Subject: [PATCH 012/103] Fix tests --- composer.lock | 40 ++++++++++++------------- src/Database/Validator/Query/Filter.php | 8 ++--- tests/e2e/Adapter/Base.php | 1 - 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/composer.lock b/composer.lock index dec36fcbd..0d9341c64 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "d6ee891117614d18ee2f10466bfea758", + "content-hash": "fec48bd2695ef6429a8963b4ef480884", "packages": [ { "name": "jean85/pretty-package-versions", @@ -269,16 +269,16 @@ }, { "name": "utopia-php/framework", - "version": "0.33.1", + "version": "0.34.0", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "b745607aa1875554a0ad52e28f6db918da1ce11c" + "reference": "f1f0df17b2fbe855b210a707320a3c85288a3c00" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/b745607aa1875554a0ad52e28f6db918da1ce11c", - "reference": "b745607aa1875554a0ad52e28f6db918da1ce11c", + "url": "https://api.github.com/repos/utopia-php/http/zipball/f1f0df17b2fbe855b210a707320a3c85288a3c00", + "reference": "f1f0df17b2fbe855b210a707320a3c85288a3c00", "shasum": "" }, "require": { @@ -311,9 +311,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.33.1" + "source": "https://github.com/utopia-php/http/tree/0.34.0" }, - "time": "2024-01-17T16:48:32+00:00" + "time": "2024-01-24T10:01:25+00:00" }, { "name": "utopia-php/mongo", @@ -512,16 +512,16 @@ }, { "name": "laravel/pint", - "version": "v1.13.9", + "version": "v1.13.10", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "e3e269cc5d874c8efd2dc7962b1c7ff2585fe525" + "reference": "e2b5060885694ca30ac008c05dc9d47f10ed1abf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/e3e269cc5d874c8efd2dc7962b1c7ff2585fe525", - "reference": "e3e269cc5d874c8efd2dc7962b1c7ff2585fe525", + "url": "https://api.github.com/repos/laravel/pint/zipball/e2b5060885694ca30ac008c05dc9d47f10ed1abf", + "reference": "e2b5060885694ca30ac008c05dc9d47f10ed1abf", "shasum": "" }, "require": { @@ -532,8 +532,8 @@ "php": "^8.1.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.47.0", - "illuminate/view": "^10.40.0", + "friendsofphp/php-cs-fixer": "^3.47.1", + "illuminate/view": "^10.41.0", "larastan/larastan": "^2.8.1", "laravel-zero/framework": "^10.3.0", "mockery/mockery": "^1.6.7", @@ -574,7 +574,7 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2024-01-16T17:39:29+00:00" + "time": "2024-01-22T09:04:15+00:00" }, { "name": "myclabs/deep-copy", @@ -1219,16 +1219,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.15", + "version": "9.6.16", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1" + "reference": "3767b2c56ce02d01e3491046f33466a1ae60a37f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/05017b80304e0eb3f31d90194a563fd53a6021f1", - "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/3767b2c56ce02d01e3491046f33466a1ae60a37f", + "reference": "3767b2c56ce02d01e3491046f33466a1ae60a37f", "shasum": "" }, "require": { @@ -1302,7 +1302,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.15" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.16" }, "funding": [ { @@ -1318,7 +1318,7 @@ "type": "tidelift" } ], - "time": "2023-12-01T16:55:19+00:00" + "time": "2024-01-19T07:03:14+00:00" }, { "name": "psr/container", diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index dcfadedf9..4a380c613 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -6,10 +6,10 @@ use Utopia\Database\Document; use Utopia\Database\Query; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Validator\Boolean; -use Utopia\Validator\FloatValidator; -use Utopia\Validator\Integer; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Boolean; +use Utopia\Http\Validator\FloatValidator; +use Utopia\Http\Validator\Integer; +use Utopia\Http\Validator\Text; class Filter extends Base { diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 7ef7cf2cc..cc633ee38 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -27,7 +27,6 @@ use Utopia\Database\Validator\Index; use Utopia\Database\Validator\Structure; use Utopia\Http\Validator\Range; -use Utopia\Database\Exception\Structure as StructureException; abstract class Base extends TestCase { From 26704cbde7e466962ec9de6c6469aae06cbd5bc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 25 Jan 2024 09:38:34 +0000 Subject: [PATCH 013/103] PR review changes --- src/Database/Database.php | 14 ++------------ src/Database/Validator/Authorization.php | 5 +++++ tests/Database/Base.php | 16 ++++------------ 3 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 4ea0cb286..0549639ad 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4095,12 +4095,7 @@ public function find(string $collection, array $queries = [], ?int $timeout = nu $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); - if ($isValid) { - $skipAuth = true; - } else { - $skipAuth = false; - } + $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); if (!$skipAuth && !$documentSecurity) { throw new AuthorizationException($validator->getDescription()); @@ -4270,12 +4265,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) throw new QueryException($validator->getDescription()); } - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); - if ($isValid) { - $skipAuth = true; - } else { - $skipAuth = false; - } + $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); $queries = Query::groupByType($queries)['filters']; $queries = self::convertQueries($collection, $queries); diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index cbd10d94a..a25daebc4 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -52,9 +52,14 @@ public function getDescription(): string */ public function isValid(mixed $input): bool { + if(!($input instanceof Input)) { + throw new Validation('Authorization validator requires Input class to validate.'); + } + /** * @var Input $input */ + $permissions = $input->getPermissions(); $action = $input->getAction(); diff --git a/tests/Database/Base.php b/tests/Database/Base.php index aaa060c09..e030f45f5 100644 --- a/tests/Database/Base.php +++ b/tests/Database/Base.php @@ -32,12 +32,7 @@ abstract class Base extends TestCase /** * @var Authorization */ - protected static ?Authorization $authorizationSingleton = null; - - /** - * @var Authorization - */ - protected ?Authorization $authorization = null; + protected static ?Authorization $authorization = null; /** * @return Database @@ -51,13 +46,10 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - if (is_null(self::$authorizationSingleton)) { - self::$authorizationSingleton = new Authorization(); - self::$authorizationSingleton->addRole('any'); + if (is_null($this->authorization)) { + $this->authorization = new Authorization(); + $this->authorization->addRole('any'); } - - $this->authorization = self::$authorizationSingleton; - $this->authorization->addRole('any'); } public function tearDown(): void From efd5d1ee31233f986f6c7b1a9945d0f92c18bbd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 25 Jan 2024 10:02:51 +0000 Subject: [PATCH 014/103] Update lockfile --- composer.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.lock b/composer.lock index 0d9341c64..2ab5f8dc0 100644 --- a/composer.lock +++ b/composer.lock @@ -838,16 +838,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.56", + "version": "1.10.57", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "27816a01aea996191ee14d010f325434c0ee76fa" + "reference": "1627b1d03446904aaa77593f370c5201d2ecc34e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/27816a01aea996191ee14d010f325434c0ee76fa", - "reference": "27816a01aea996191ee14d010f325434c0ee76fa", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/1627b1d03446904aaa77593f370c5201d2ecc34e", + "reference": "1627b1d03446904aaa77593f370c5201d2ecc34e", "shasum": "" }, "require": { @@ -896,7 +896,7 @@ "type": "tidelift" } ], - "time": "2024-01-15T10:43:00+00:00" + "time": "2024-01-24T11:51:34+00:00" }, { "name": "phpunit/php-code-coverage", From f0dc793d3c1eb9a00052bcfbdcdd1effaf87c6ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 25 Jan 2024 10:12:18 +0000 Subject: [PATCH 015/103] CI/CD fixes --- README.md | 2 +- bin/tasks/load.php | 17 +++++++++-------- bin/tasks/query.php | 20 +++++++++----------- src/Database/Adapter/Postgres.php | 1 - src/Database/Database.php | 9 ++++----- src/Database/Validator/Authorization.php | 2 +- tests/e2e/Adapter/Base.php | 16 ++++++++-------- tests/e2e/Adapter/MariaDBTest.php | 2 +- tests/e2e/Adapter/MongoDBTest.php | 8 ++++---- 9 files changed, 37 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index c9a603168..cccfa1afa 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ A list of the utopia/php concepts and their relevant equivalent using the differ - **Document** - A simple JSON object that will be stored in one of the utopia/database collections. For SQL-based adapters, this will be equivalent to a row. For a No-SQL adapter, this will equivalent to a native document. - **Attribute** - A simple document attribute. For SQL-based adapters, this will be equivalent to a column. For a No-SQL adapter, this will equivalent to a native document field. - **Index** - A simple collection index used to improve the performance of your database queries. -- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `Authorization::addRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. +- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `$authorization->addRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. ### Filters diff --git a/bin/tasks/load.php b/bin/tasks/load.php index ee47967da..6ed52761a 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -25,6 +25,8 @@ use Utopia\Http\Validator\Numeric; use Utopia\Http\Validator\Text; +$authorization = new Authorization(); + /** * @Example * docker compose exec tests bin/load --adapter=mariadb --limit=1000 --name=testing @@ -61,7 +63,7 @@ $database->setNamespace($namespace); // Outline collection schema - createSchema($database); + $createSchema($database); // reclaim resources $database = null; @@ -121,7 +123,7 @@ $database->setNamespace($namespace); // Outline collection schema - createSchema($database); + $createSchema($database); // reclaim resources $database = null; @@ -183,7 +185,7 @@ $database->setNamespace($namespace); // Outline collection schema - createSchema($database); + $createSchema($database); // Fill DB $faker = Factory::create(); @@ -226,15 +228,14 @@ }); -function createSchema(Database $database): void -{ +$createSchema = function (Database $database) use ($authorization): void { if ($database->exists($database->getDatabase())) { $database->delete($database->getDatabase()); } $database->create(); - Authorization::addRole(Role::any()->toString()); - + $authorization->addRole(Role::any()->toString()); + $database->createCollection('articles', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), @@ -247,7 +248,7 @@ function createSchema(Database $database): void $database->createAttribute('articles', 'views', Database::VAR_INTEGER, 0, true); $database->createAttribute('articles', 'tags', Database::VAR_STRING, 0, true, array: true); $database->createIndex('articles', 'text', Database::INDEX_FULLTEXT, ['text']); -} +}; function createDocument($database, Generator $faker): void { diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 5019260a0..7eb04a996 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -15,7 +15,6 @@ use Utopia\Database\Query; use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MariaDB; -use Utopia\Database\Validator\Authorization; use Utopia\Http\Validator\Numeric; use Utopia\Http\Validator\Text; @@ -84,35 +83,35 @@ $report = []; - $count = setRoles($faker, 1); + $count = $setRoles($faker, 1); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = setRoles($faker, 100); + $count = $setRoles($faker, 100); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = setRoles($faker, 400); + $count = $setRoles($faker, 400); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = setRoles($faker, 500); + $count = $setRoles($faker, 500); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = setRoles($faker, 1000); + $count = $setRoles($faker, 1000); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, @@ -136,13 +135,12 @@ Console::error($error->getMessage()); }); -function setRoles($faker, $count): int -{ +$setRoles = function ($faker, $count) use ($authorization): int { for ($i = 0; $i < $count; $i++) { - Authorization::setRole($faker->numerify('user####')); + $authorization->addRole($faker->numerify('user####')); } - return \count(Authorization::getRoles()); -} + return \count($authorization->getRoles()); +}; function runQueries(Database $database, int $limit): array { diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index f237bfa47..22ff310c5 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -12,7 +12,6 @@ use Utopia\Database\Exception\Duplicate; use Utopia\Database\Exception\Timeout; use Utopia\Database\Query; -use Utopia\Database\Validator\Authorization; class Postgres extends SQL { diff --git a/src/Database/Database.php b/src/Database/Database.php index af407c896..c147f8d25 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3663,19 +3663,18 @@ public function updateDocuments(string $collection, array $documents, int $batch $document->setAttribute('$updatedAt', empty($updatedAt) || !$this->preserveDates ? $time : $updatedAt); $document = $this->encode($collection, $document); - $old = Authorization::skip(fn () => $this->silent( + $old = $this->authorization->skip(fn () => $this->silent( fn () => $this->getDocument( $collection->getId(), $document->getId() ) )); - $validator = new Authorization(self::PERMISSION_UPDATE); if ( $collection->getId() !== self::METADATA - && !$validator->isValid($old->getUpdate()) + && !$this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $old->getUpdate())) ) { - throw new AuthorizationException($validator->getDescription()); + throw new AuthorizationException($this->authorization->getDescription()); } $validator = new Structure($collection); @@ -4716,7 +4715,7 @@ public function find(string $collection, array $queries = []): array $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($authorization->getDescription()); + throw new AuthorizationException($this->authorization->getDescription()); } $relationships = \array_filter( diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index a25daebc4..2d1c676dc 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -59,7 +59,7 @@ public function isValid(mixed $input): bool /** * @var Input $input */ - + $permissions = $input->getPermissions(); $action = $input->getAction(); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index fc30f0842..345c0fbdd 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -251,7 +251,7 @@ public function testDeleteRelatedCollection(): void public function testPreserveDatesUpdate(): void { - Authorization::disable(); + $this->authorization->disable(); $this->getDatabase()->setPreserveDates(true); @@ -297,12 +297,12 @@ public function testPreserveDatesUpdate(): void $this->getDatabase()->setPreserveDates(false); - Authorization::reset(); + $this->authorization->reset(); } public function testPreserveDatesCreate(): void { - Authorization::disable(); + $this->authorization->disable(); $this->getDatabase()->setPreserveDates(true); @@ -345,7 +345,7 @@ public function testPreserveDatesCreate(): void $this->getDatabase()->setPreserveDates(false); - Authorization::reset(); + $this->authorization->reset(); } /** @@ -1870,9 +1870,9 @@ public function testDeleteDocument(Document $document): void */ public function testArrayAttribute(): void { - Authorization::setRole(Role::any()->toString()); + $this->authorization->addRole(Role::any()->toString()); - $database = static::getDatabase(); + $database = $this->getDatabase(); $collection = 'json'; $permissions = [Permission::read(Role::any())]; @@ -13130,7 +13130,7 @@ public function testLabels(): void public function testEnableDisableValidation(): void { - $database = static::getDatabase(); + $database = $this->getDatabase(); $database->createCollection('validation', permissions: [ Permission::create(Role::any()), @@ -13229,7 +13229,7 @@ public function testIsolationModes(): void /** * Default mode already tested, we'll test 'schema' and 'table' isolation here */ - $database = static::getDatabase(); + $database = $this->getDatabase(); if ($database->exists('schema1')) { $database->setDatabase('schema1')->delete(); diff --git a/tests/e2e/Adapter/MariaDBTest.php b/tests/e2e/Adapter/MariaDBTest.php index 535f44390..bf7a77847 100644 --- a/tests/e2e/Adapter/MariaDBTest.php +++ b/tests/e2e/Adapter/MariaDBTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(bool $fresh = false): Database + public function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; diff --git a/tests/e2e/Adapter/MongoDBTest.php b/tests/e2e/Adapter/MongoDBTest.php index 99a807e08..207976be9 100644 --- a/tests/e2e/Adapter/MongoDBTest.php +++ b/tests/e2e/Adapter/MongoDBTest.php @@ -70,10 +70,10 @@ public function getDatabase(): Database public function testCreateExistsDelete(): void { // Mongo creates databases on the fly, so exists would always pass. So we override this test to remove the exists check. - $this->assertNotNull(static::getDatabase()->create()); - $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); - $this->assertEquals(true, static::getDatabase()->create()); - $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); + $this->assertNotNull($this->getDatabase()->create()); + $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); + $this->assertEquals(true, $this->getDatabase()->create()); + $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); } public function testRenameAttribute(): void From 597a9aba5362dccb06f616c9840345678b98b313 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 25 Jan 2024 11:06:27 +0000 Subject: [PATCH 016/103] =?UTF-8?q?Fix=20all=20tests=20=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database/Validator/Authorization.php | 4 +- tests/e2e/Adapter/Base.php | 205 ++++++++++++----------- tests/e2e/Adapter/MariaDBTest.php | 2 +- tests/e2e/Adapter/MongoDBTest.php | 2 +- tests/e2e/Adapter/MySQLTest.php | 2 +- tests/e2e/Adapter/PostgresTest.php | 2 +- tests/e2e/Adapter/SQLiteTest.php | 2 +- 7 files changed, 110 insertions(+), 109 deletions(-) diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 2d1c676dc..962f51988 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -50,7 +50,7 @@ public function getDescription(): string * * Returns true if valid or false if not. */ - public function isValid(mixed $input): bool + public function isValid(mixed $input): bool // any, CREATE { if(!($input instanceof Input)) { throw new Validation('Authorization validator requires Input class to validate.'); @@ -88,7 +88,7 @@ public function isValid(mixed $input): bool * @param string $role * @return void */ - public function addRole(string $role): void + public function addRole(string $role): void // user:meldiron, users, any { $this->roles[$role] = true; } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 345c0fbdd..fd02867ad 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -49,15 +49,16 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - if (is_null($this->authorization)) { - $this->authorization = new Authorization(); - $this->authorization->addRole('any'); + if (is_null(self::$authorization)) { + self::$authorization = new Authorization(); } + + self::$authorization->addRole('any'); } public function tearDown(): void { - $this->authorization->setDefaultStatus(true); + self::$authorization->setDefaultStatus(true); } protected string $testDatabase = 'utopiaTests'; @@ -251,7 +252,7 @@ public function testDeleteRelatedCollection(): void public function testPreserveDatesUpdate(): void { - $this->authorization->disable(); + self::$authorization->disable(); $this->getDatabase()->setPreserveDates(true); @@ -297,12 +298,12 @@ public function testPreserveDatesUpdate(): void $this->getDatabase()->setPreserveDates(false); - $this->authorization->reset(); + self::$authorization->reset(); } public function testPreserveDatesCreate(): void { - $this->authorization->disable(); + self::$authorization->disable(); $this->getDatabase()->setPreserveDates(true); @@ -345,7 +346,7 @@ public function testPreserveDatesCreate(): void $this->getDatabase()->setPreserveDates(false); - $this->authorization->reset(); + self::$authorization->reset(); } /** @@ -1870,7 +1871,7 @@ public function testDeleteDocument(Document $document): void */ public function testArrayAttribute(): void { - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); $database = $this->getDatabase(); $collection = 'json'; @@ -2101,7 +2102,7 @@ public function testArrayAttribute(): void */ public function testFind(): array { - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); $this->getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), @@ -2336,7 +2337,7 @@ public function testFindCheckPermissions(): void /** * Check Permissions */ - $this->authorization->addRole('user:x'); + self::$authorization->addRole('user:x'); $documents = $this->getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); @@ -3703,30 +3704,30 @@ public function testCount(): void $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); - $this->authorization->removeRole('user:x'); + self::$authorization->removeRole('user:x'); $count = $this->getDatabase()->count('movies'); $this->assertEquals(5, $count); - $this->authorization->disable(); + self::$authorization->disable(); $count = $this->getDatabase()->count('movies'); $this->assertEquals(6, $count); - $this->authorization->reset(); + self::$authorization->reset(); - $this->authorization->disable(); + self::$authorization->disable(); $count = $this->getDatabase()->count('movies', [], 3); $this->assertEquals(3, $count); - $this->authorization->reset(); + self::$authorization->reset(); /** * Test that OR queries are handled correctly */ - $this->authorization->disable(); + self::$authorization->disable(); $count = $this->getDatabase()->count('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); $this->assertEquals(1, $count); - $this->authorization->reset(); + self::$authorization->reset(); } /** @@ -3734,7 +3735,7 @@ public function testCount(): void */ public function testSum(): void { - $this->authorization->addRole('user:x'); + self::$authorization->addRole('user:x'); $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = $this->getDatabase()->sum('movies', 'year'); @@ -3747,8 +3748,8 @@ public function testSum(): void $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); - $this->authorization->removeRole('user:x'); - $this->authorization->removeRole('userx'); + self::$authorization->removeRole('user:x'); + self::$authorization->removeRole('userx'); $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); $sum = $this->getDatabase()->sum('movies', 'year'); @@ -4008,8 +4009,8 @@ public function testEncodeDecode(): void */ public function testReadPermissionsSuccess(Document $document): Document { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -4028,20 +4029,20 @@ public function testReadPermissionsSuccess(Document $document): Document $this->assertEquals(false, $document->isEmpty()); - $this->authorization->cleanRoles(); + self::$authorization->cleanRoles(); $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); return $document; } public function testReadPermissionsFailure(): Document { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -4058,13 +4059,13 @@ public function testReadPermissionsFailure(): Document 'colors' => ['pink', 'green', 'blue'], ])); - $this->authorization->cleanRoles(); + self::$authorization->cleanRoles(); $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); return $document; } @@ -4074,7 +4075,7 @@ public function testReadPermissionsFailure(): Document */ public function testWritePermissionsSuccess(Document $document): void { - $this->authorization->cleanRoles(); + self::$authorization->cleanRoles(); $this->expectException(AuthorizationException::class); $this->getDatabase()->createDocument('documents', new Document([ @@ -4100,8 +4101,8 @@ public function testWritePermissionsUpdateFailure(Document $document): Document { $this->expectException(AuthorizationException::class); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->createDocument('documents', new Document([ '$permissions' => [ @@ -4118,7 +4119,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document 'colors' => ['pink', 'green', 'blue'], ])); - $this->authorization->cleanRoles(); + self::$authorization->cleanRoles(); $document = $this->getDatabase()->updateDocument('documents', $document->getId(), new Document([ '$id' => ID::custom($document->getId()), @@ -4565,7 +4566,7 @@ public function testUniqueIndexDuplicate(): void */ public function testUniqueIndexDuplicateUpdate(): void { - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->addRole(Role::users()->toString()); // create document then update to conflict with index $document = $this->getDatabase()->createDocument('movies', new Document([ '$permissions' => [ @@ -5241,7 +5242,7 @@ public function testKeywords(): void public function testWritePermissions(): void { - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); $database = $this->getDatabase(); $database->createCollection('animals', permissions: [ @@ -5307,7 +5308,7 @@ public function testWritePermissions(): void $newCat = $cat->setAttribute('type', 'newCat'); $database->updateDocument('animals', 'cat', $newCat); - $docs = $this->authorization->skip(fn () => $database->find('animals')); + $docs = self::$authorization->skip(fn () => $database->find('animals')); $this->assertCount(1, $docs); $this->assertEquals('cat', $docs[0]['$id']); $this->assertEquals('newCat', $docs[0]['type']); @@ -10767,8 +10768,8 @@ public function testEnforceRelationshipPermissions(): void $this->expectNotToPerformAssertions(); return; } - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); @@ -10845,7 +10846,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $this->authorization->addRole(Role::user('user1')->toString()); + self::$authorization->addRole(Role::user('user1')->toString()); $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); @@ -10858,7 +10859,7 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Bird 1 Updated', $bird1['name']); - $this->authorization->addRole(Role::user('user2')->toString()); + self::$authorization->addRole(Role::user('user2')->toString()); // Try delete multi-level nested document $deleted = $this->getDatabase()->deleteDocument( @@ -12132,8 +12133,8 @@ public function testCollectionPermissionsExceptions(): void */ public function testCollectionPermissionsCreateWorks(Document $collection): array { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -12155,8 +12156,8 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra */ public function testCollectionPermissionsCreateThrowsException(Document $collection): void { - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->createDocument($collection->getId(), new Document([ @@ -12179,8 +12180,8 @@ public function testCollectionPermissionsGetWorks(array $data): array { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -12200,8 +12201,8 @@ public function testCollectionPermissionsGetThrowsException(array $data): void { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -12220,14 +12221,14 @@ public function testCollectionPermissionsFindWorks(array $data): array { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('random')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('random')->toString()); try { $this->getDatabase()->find($collection->getId()); @@ -12246,8 +12247,8 @@ public function testCollectionPermissionsFindThrowsException(array $data): void { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->find($collection->getId()); @@ -12262,8 +12263,8 @@ public function testCollectionPermissionsCountWorks(array $data): array { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $count = $this->getDatabase()->count( $collection->getId() @@ -12282,8 +12283,8 @@ public function testCollectionPermissionsCountThrowsException(array $data): void { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $count = $this->getDatabase()->count( $collection->getId() @@ -12300,8 +12301,8 @@ public function testCollectionPermissionsUpdateWorks(array $data): array { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $this->assertInstanceOf(Document::class, $this->getDatabase()->updateDocument( $collection->getId(), @@ -12319,8 +12320,8 @@ public function testCollectionPermissionsUpdateWorks(array $data): array public function testCollectionPermissionsUpdateThrowsException(array $data): void { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->updateDocument( @@ -12338,8 +12339,8 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->deleteDocument( @@ -12356,8 +12357,8 @@ public function testCollectionPermissionsDeleteWorks(array $data): void { [$collection, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), @@ -12448,8 +12449,8 @@ public function testCollectionPermissionsRelationships(): array public function testCollectionPermissionsRelationshipsCreateWorks(array $data): array { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), @@ -12501,8 +12502,8 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $this->getDatabase()->createDocument($collection->getId(), new Document([ @@ -12524,8 +12525,8 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -12538,8 +12539,8 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('random')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('random')->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -12563,8 +12564,8 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $document = $this->getDatabase()->getDocument( $collection->getId(), @@ -12582,8 +12583,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -12598,8 +12599,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('random')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('random')->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -12614,8 +12615,8 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(1, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('unknown')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('unknown')->toString()); $documents = $this->getDatabase()->find( $collection->getId() @@ -12633,8 +12634,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -12642,8 +12643,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('random')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('random')->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -12651,8 +12652,8 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v $this->assertEquals(1, $documents); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('unknown')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('unknown')->toString()); $documents = $this->getDatabase()->count( $collection->getId() @@ -12670,8 +12671,8 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $this->getDatabase()->updateDocument( $collection->getId(), $document->getId(), @@ -12680,8 +12681,8 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->assertTrue(true); - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('random')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('random')->toString()); $this->getDatabase()->updateDocument( $collection->getId(), @@ -12702,8 +12703,8 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->updateDocument( @@ -12721,8 +12722,8 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::any()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); $document = $this->getDatabase()->deleteDocument( @@ -12739,8 +12740,8 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::users()->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::users()->toString()); $this->assertTrue($this->getDatabase()->deleteDocument( $collection->getId(), @@ -12755,8 +12756,8 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void return; } - $this->authorization->cleanRoles(); - $this->authorization->addRole(Role::user('a')->toString()); + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::user('a')->toString()); $this->getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), @@ -13121,7 +13122,7 @@ public function testLabels(): void $this->assertEmpty($documents); - $this->authorization->addRole(Role::label('reader')->toString()); + self::$authorization->addRole(Role::label('reader')->toString()); $documents = $this->getDatabase()->find('labels_test'); @@ -13396,7 +13397,7 @@ public function testTransformations(): void public function testEvents(): void { - $this->authorization->skip(function () { + self::$authorization->skip(function () { $database = $this->getDatabase(); $events = [ diff --git a/tests/e2e/Adapter/MariaDBTest.php b/tests/e2e/Adapter/MariaDBTest.php index bf7a77847..5d7267ed5 100644 --- a/tests/e2e/Adapter/MariaDBTest.php +++ b/tests/e2e/Adapter/MariaDBTest.php @@ -46,7 +46,7 @@ public function getDatabase(bool $fresh = false): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MariaDB($pdo), $cache, []); - $database->setAuthorization($this->authorization); + $database->setAuthorization(self::$authorization); $database->setDatabase('utopiaTests'); $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); diff --git a/tests/e2e/Adapter/MongoDBTest.php b/tests/e2e/Adapter/MongoDBTest.php index 207976be9..11db0c4bd 100644 --- a/tests/e2e/Adapter/MongoDBTest.php +++ b/tests/e2e/Adapter/MongoDBTest.php @@ -51,7 +51,7 @@ public function getDatabase(): Database ); $database = new Database(new Mongo($client), $cache, []); - $database->setAuthorization($this->authorization); + $database->setAuthorization(self::$authorization); $database->setDatabase($schema); $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); diff --git a/tests/e2e/Adapter/MySQLTest.php b/tests/e2e/Adapter/MySQLTest.php index 3d94490b6..7c63a43ab 100644 --- a/tests/e2e/Adapter/MySQLTest.php +++ b/tests/e2e/Adapter/MySQLTest.php @@ -48,7 +48,7 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MySQL($pdo), $cache, []); - $database->setAuthorization($this->authorization); + $database->setAuthorization(self::$authorization); $database->setDatabase('utopiaTests'); $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); diff --git a/tests/e2e/Adapter/PostgresTest.php b/tests/e2e/Adapter/PostgresTest.php index 47d370e2e..2f87a5863 100644 --- a/tests/e2e/Adapter/PostgresTest.php +++ b/tests/e2e/Adapter/PostgresTest.php @@ -45,7 +45,7 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new Postgres($pdo), $cache, []); - $database->setAuthorization($this->authorization); + $database->setAuthorization(self::$authorization); $database->setDatabase('utopiaTests'); $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); diff --git a/tests/e2e/Adapter/SQLiteTest.php b/tests/e2e/Adapter/SQLiteTest.php index 557664fc3..00d24689d 100644 --- a/tests/e2e/Adapter/SQLiteTest.php +++ b/tests/e2e/Adapter/SQLiteTest.php @@ -51,7 +51,7 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new SQLite($pdo), $cache, []); - $database->setAuthorization($this->authorization); + $database->setAuthorization(self::$authorization); $database->setDatabase('utopiaTests'); $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); From 6f8b4a7f10c5c03bf736e8ce6db1558af1e3cf8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 25 Jan 2024 11:25:01 +0000 Subject: [PATCH 017/103] Remove validation exception --- src/Database/Database.php | 1 - src/Database/Exception/Validation.php | 7 ------- src/Database/Validator/Authorization.php | 4 ++-- 3 files changed, 2 insertions(+), 10 deletions(-) delete mode 100644 src/Database/Exception/Validation.php diff --git a/src/Database/Database.php b/src/Database/Database.php index c147f8d25..65e64bf56 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -12,7 +12,6 @@ use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Exception\Restricted as RestrictedException; use Utopia\Database\Exception\Structure as StructureException; -use Utopia\Database\Exception\Validation; use Utopia\Database\Exception\Timeout as TimeoutException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; diff --git a/src/Database/Exception/Validation.php b/src/Database/Exception/Validation.php deleted file mode 100644 index 9e554b443..000000000 --- a/src/Database/Exception/Validation.php +++ /dev/null @@ -1,7 +0,0 @@ -message = 'Invalid input provided'; + return false; } /** From 6dd6562e876c8af6fac3fc7e7fb188e443162c61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 22 Feb 2024 10:24:52 +0000 Subject: [PATCH 018/103] Post-merge fixes --- composer.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.lock b/composer.lock index de59f3b68..9a43dbb49 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1fec834c5b222e402702b7bc89a5a8a8", + "content-hash": "fec48bd2695ef6429a8963b4ef480884", "packages": [ { "name": "jean85/pretty-package-versions", @@ -266,16 +266,16 @@ }, { "name": "utopia-php/framework", - "version": "0.33.2", + "version": "0.34.2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "b1423ca3e3b61c6c4c2e619d2cb80672809a19f3" + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/b1423ca3e3b61c6c4c2e619d2cb80672809a19f3", - "reference": "b1423ca3e3b61c6c4c2e619d2cb80672809a19f3", + "url": "https://api.github.com/repos/utopia-php/http/zipball/fd126c02b78cc80678c9638f7b335dfb4a841b78", + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78", "shasum": "" }, "require": { @@ -308,9 +308,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.33.2" + "source": "https://github.com/utopia-php/http/tree/0.34.2" }, - "time": "2024-01-31T10:35:59+00:00" + "time": "2024-02-20T11:36:56+00:00" }, { "name": "utopia-php/mongo", From 3465bc51bf2387b73c7d10d0d2b8b816ed0e3273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 27 Feb 2024 10:49:12 +0100 Subject: [PATCH 019/103] Add method for coroutine-style to wipe previous transformations state --- src/Database/Adapter.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 536718d5b..54282b1f5 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -50,6 +50,16 @@ public function setAuthorization(Authorization $authorization): self return $this; } + /** + * @return $this + */ + public function clearTransformations(): self + { + $this->transformations = []; + + return $this; + } + /** * @param string $key * @param mixed $value From 79fd5790227e039832372f2c6c9c284f6f1284bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 27 Feb 2024 11:05:08 +0100 Subject: [PATCH 020/103] Improve clear transformation --- src/Database/Adapter.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 54282b1f5..1c6151dac 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -55,7 +55,9 @@ public function setAuthorization(Authorization $authorization): self */ public function clearTransformations(): self { - $this->transformations = []; + $this->transformations = [ + '*' => [], + ]; return $this; } From 73fb44339b2de17648003a516489c7ff22e39c72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 7 Mar 2024 14:58:58 +0000 Subject: [PATCH 021/103] Resolve framework V2 issues --- composer.lock | 103 ++++++++++++----------- src/Database/Adapter/Proxy.php | 7 +- src/Database/Validator/Authorization.php | 10 +++ tests/e2e/Adapter/MariaDBProxyTest.php | 2 +- 4 files changed, 69 insertions(+), 53 deletions(-) diff --git a/composer.lock b/composer.lock index f20f938e8..f06a6b78f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4adf56005e024ee6b5bb991e96e2ee72", + "content-hash": "2fdc7433d4d3ef058cab039b00b77427", "packages": [ { "name": "jean85/pretty-package-versions", @@ -763,20 +763,21 @@ }, { "name": "phar-io/manifest", - "version": "2.0.3", + "version": "2.0.4", "source": { "type": "git", "url": "https://github.com/phar-io/manifest.git", - "reference": "97803eca37d319dfa7826cc2437fc020857acb53" + "reference": "54750ef60c58e43759730615a392c31c80e23176" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/manifest/zipball/97803eca37d319dfa7826cc2437fc020857acb53", - "reference": "97803eca37d319dfa7826cc2437fc020857acb53", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176", + "reference": "54750ef60c58e43759730615a392c31c80e23176", "shasum": "" }, "require": { "ext-dom": "*", + "ext-libxml": "*", "ext-phar": "*", "ext-xmlwriter": "*", "phar-io/version": "^3.0.1", @@ -817,9 +818,15 @@ "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", "support": { "issues": "https://github.com/phar-io/manifest/issues", - "source": "https://github.com/phar-io/manifest/tree/2.0.3" + "source": "https://github.com/phar-io/manifest/tree/2.0.4" }, - "time": "2021-07-20T11:28:43+00:00" + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:33:53+00:00" }, { "name": "phar-io/version", @@ -874,16 +881,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.59", + "version": "1.10.60", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "e607609388d3a6d418a50a49f7940e8086798281" + "reference": "95dcea7d6c628a3f2f56d091d8a0219485a86bbe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/e607609388d3a6d418a50a49f7940e8086798281", - "reference": "e607609388d3a6d418a50a49f7940e8086798281", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/95dcea7d6c628a3f2f56d091d8a0219485a86bbe", + "reference": "95dcea7d6c628a3f2f56d091d8a0219485a86bbe", "shasum": "" }, "require": { @@ -932,20 +939,20 @@ "type": "tidelift" } ], - "time": "2024-02-20T13:59:13+00:00" + "time": "2024-03-07T13:30:19+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "9.2.30", + "version": "9.2.31", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089" + "reference": "48c34b5d8d983006bd2adc2d0de92963b9155965" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/ca2bd87d2f9215904682a9cb9bb37dda98e76089", - "reference": "ca2bd87d2f9215904682a9cb9bb37dda98e76089", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/48c34b5d8d983006bd2adc2d0de92963b9155965", + "reference": "48c34b5d8d983006bd2adc2d0de92963b9155965", "shasum": "" }, "require": { @@ -1002,7 +1009,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.30" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.31" }, "funding": [ { @@ -1010,7 +1017,7 @@ "type": "github" } ], - "time": "2023-12-22T06:47:57+00:00" + "time": "2024-03-02T06:37:42+00:00" }, { "name": "phpunit/php-file-iterator", @@ -1457,16 +1464,16 @@ }, { "name": "sebastian/cli-parser", - "version": "1.0.1", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/cli-parser.git", - "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2" + "reference": "2b56bea83a09de3ac06bb18b92f068e60cc6f50b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/442e7c7e687e42adc03470c7b668bc4b2402c0b2", - "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/2b56bea83a09de3ac06bb18b92f068e60cc6f50b", + "reference": "2b56bea83a09de3ac06bb18b92f068e60cc6f50b", "shasum": "" }, "require": { @@ -1501,7 +1508,7 @@ "homepage": "https://github.com/sebastianbergmann/cli-parser", "support": { "issues": "https://github.com/sebastianbergmann/cli-parser/issues", - "source": "https://github.com/sebastianbergmann/cli-parser/tree/1.0.1" + "source": "https://github.com/sebastianbergmann/cli-parser/tree/1.0.2" }, "funding": [ { @@ -1509,7 +1516,7 @@ "type": "github" } ], - "time": "2020-09-28T06:08:49+00:00" + "time": "2024-03-02T06:27:43+00:00" }, { "name": "sebastian/code-unit", @@ -1755,16 +1762,16 @@ }, { "name": "sebastian/diff", - "version": "4.0.5", + "version": "4.0.6", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131" + "reference": "ba01945089c3a293b01ba9badc29ad55b106b0bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/74be17022044ebaaecfdf0c5cd504fc9cd5a7131", - "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/ba01945089c3a293b01ba9badc29ad55b106b0bc", + "reference": "ba01945089c3a293b01ba9badc29ad55b106b0bc", "shasum": "" }, "require": { @@ -1809,7 +1816,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/diff/issues", - "source": "https://github.com/sebastianbergmann/diff/tree/4.0.5" + "source": "https://github.com/sebastianbergmann/diff/tree/4.0.6" }, "funding": [ { @@ -1817,7 +1824,7 @@ "type": "github" } ], - "time": "2023-05-07T05:35:17+00:00" + "time": "2024-03-02T06:30:58+00:00" }, { "name": "sebastian/environment", @@ -1884,16 +1891,16 @@ }, { "name": "sebastian/exporter", - "version": "4.0.5", + "version": "4.0.6", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/exporter.git", - "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d" + "reference": "78c00df8f170e02473b682df15bfcdacc3d32d72" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d", - "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/78c00df8f170e02473b682df15bfcdacc3d32d72", + "reference": "78c00df8f170e02473b682df15bfcdacc3d32d72", "shasum": "" }, "require": { @@ -1949,7 +1956,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/exporter/issues", - "source": "https://github.com/sebastianbergmann/exporter/tree/4.0.5" + "source": "https://github.com/sebastianbergmann/exporter/tree/4.0.6" }, "funding": [ { @@ -1957,20 +1964,20 @@ "type": "github" } ], - "time": "2022-09-14T06:03:37+00:00" + "time": "2024-03-02T06:33:00+00:00" }, { "name": "sebastian/global-state", - "version": "5.0.6", + "version": "5.0.7", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "bde739e7565280bda77be70044ac1047bc007e34" + "reference": "bca7df1f32ee6fe93b4d4a9abbf69e13a4ada2c9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bde739e7565280bda77be70044ac1047bc007e34", - "reference": "bde739e7565280bda77be70044ac1047bc007e34", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bca7df1f32ee6fe93b4d4a9abbf69e13a4ada2c9", + "reference": "bca7df1f32ee6fe93b4d4a9abbf69e13a4ada2c9", "shasum": "" }, "require": { @@ -2013,7 +2020,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/global-state/issues", - "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.6" + "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.7" }, "funding": [ { @@ -2021,7 +2028,7 @@ "type": "github" } ], - "time": "2023-08-02T09:26:13+00:00" + "time": "2024-03-02T06:35:11+00:00" }, { "name": "sebastian/lines-of-code", @@ -2530,16 +2537,16 @@ }, { "name": "theseer/tokenizer", - "version": "1.2.2", + "version": "1.2.3", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96" + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96", - "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", "shasum": "" }, "require": { @@ -2568,7 +2575,7 @@ "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", "support": { "issues": "https://github.com/theseer/tokenizer/issues", - "source": "https://github.com/theseer/tokenizer/tree/1.2.2" + "source": "https://github.com/theseer/tokenizer/tree/1.2.3" }, "funding": [ { @@ -2576,7 +2583,7 @@ "type": "github" } ], - "time": "2023-11-20T00:12:19+00:00" + "time": "2024-03-03T12:36:25+00:00" }, { "name": "utopia-php/cli", diff --git a/src/Database/Adapter/Proxy.php b/src/Database/Adapter/Proxy.php index 46553b5ce..6bb02b8b2 100644 --- a/src/Database/Adapter/Proxy.php +++ b/src/Database/Adapter/Proxy.php @@ -10,7 +10,6 @@ use Utopia\Fetch\Client; use Utopia\Database\Query; use Utopia\Database\Exception as DatabaseException; -use Utopia\Database\Validator\Authorization; use Utopia\Fetch\FetchException; abstract class Proxy extends Adapter @@ -48,7 +47,7 @@ public function __construct(string $endpoint, string $secret, string $database) */ private function query(string $query, array $params = []): mixed { - $roles = Authorization::getRoles(); + $roles = $this->authorization->getRoles(); $response = Client::fetch( url: $this->endpoint . '/queries', @@ -57,8 +56,8 @@ private function query(string $query, array $params = []): mixed 'x-utopia-database' => $this->database, 'x-utopia-namespace' => $this->getNamespace(), 'x-utopia-auth-roles' => \json_encode($roles) ?: '', - 'x-utopia-auth-status' => Authorization::$status ? 'true' : 'false', - 'x-utopia-auth-status-default' => Authorization::$statusDefault ? 'true' : 'false', + 'x-utopia-auth-status' => $this->authorization->getStatus() ? 'true' : 'false', + 'x-utopia-auth-status-default' => $this->authorization->getStatusDefault() ? 'true' : 'false', 'x-utopia-timeouts' => \json_encode($this->timeouts) ?: '', 'x-utopia-share-tables' => $this->shareTables ? 'true' : 'false', 'x-utopia-tenant' => \strval($this->tenant ?? ''), diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 41d904889..b6acbd291 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -163,6 +163,16 @@ public function getStatus(): bool return $this->status; } + /** + * Get default status + * + * @return bool + */ + public function getStatusDefault(): bool + { + return $this->statusDefault; + } + /** * Skip Authorization * diff --git a/tests/e2e/Adapter/MariaDBProxyTest.php b/tests/e2e/Adapter/MariaDBProxyTest.php index 046abb954..bd92393f3 100644 --- a/tests/e2e/Adapter/MariaDBProxyTest.php +++ b/tests/e2e/Adapter/MariaDBProxyTest.php @@ -24,7 +24,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; From bdd9140e40c77faadb0cf2f5050b466c34eef673 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Thu, 7 Mar 2024 16:55:44 +0000 Subject: [PATCH 022/103] Add new method --- src/Database/Database.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Database/Database.php b/src/Database/Database.php index e746c30ff..e6ac5ae4f 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -444,6 +444,16 @@ public function setAuthorization(Authorization $authorization): self return $this; } + /** + * Get instance of authorization + * + * @return Authorization + */ + public function getAuthorization(): Authorization + { + return $this->authorization; + } + /** * Add listener to events * From b0010c457ca0721ec121f1bef2a47caf0504f3ad Mon Sep 17 00:00:00 2001 From: fogelito Date: Wed, 17 Apr 2024 17:13:08 +0300 Subject: [PATCH 023/103] composer.lock --- composer.lock | 83 ++++++++++++++++++++++++--------------------------- 1 file changed, 39 insertions(+), 44 deletions(-) diff --git a/composer.lock b/composer.lock index f06a6b78f..346c57f42 100644 --- a/composer.lock +++ b/composer.lock @@ -8,16 +8,16 @@ "packages": [ { "name": "jean85/pretty-package-versions", - "version": "2.0.5", + "version": "2.0.6", "source": { "type": "git", "url": "https://github.com/Jean85/pretty-package-versions.git", - "reference": "ae547e455a3d8babd07b96966b17d7fd21d9c6af" + "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/ae547e455a3d8babd07b96966b17d7fd21d9c6af", - "reference": "ae547e455a3d8babd07b96966b17d7fd21d9c6af", + "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/f9fdd29ad8e6d024f52678b570e5593759b550b4", + "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4", "shasum": "" }, "require": { @@ -25,9 +25,9 @@ "php": "^7.1|^8.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.17", + "friendsofphp/php-cs-fixer": "^3.2", "jean85/composer-provided-replaced-stub-package": "^1.0", - "phpstan/phpstan": "^0.12.66", + "phpstan/phpstan": "^1.4", "phpunit/phpunit": "^7.5|^8.5|^9.4", "vimeo/psalm": "^4.3" }, @@ -61,9 +61,9 @@ ], "support": { "issues": "https://github.com/Jean85/pretty-package-versions/issues", - "source": "https://github.com/Jean85/pretty-package-versions/tree/2.0.5" + "source": "https://github.com/Jean85/pretty-package-versions/tree/2.0.6" }, - "time": "2021-10-08T21:21:46+00:00" + "time": "2024-03-08T09:58:59+00:00" }, { "name": "mongodb/mongodb", @@ -216,16 +216,16 @@ }, { "name": "utopia-php/cache", - "version": "0.9.0", + "version": "0.9.1", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "4fc7b4789b5f0ce74835c1ecfec4f3afe6f0e34e" + "reference": "552b4c554bb14d0c529631ce304cdf4a2b9d06a6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/4fc7b4789b5f0ce74835c1ecfec4f3afe6f0e34e", - "reference": "4fc7b4789b5f0ce74835c1ecfec4f3afe6f0e34e", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/552b4c554bb14d0c529631ce304cdf4a2b9d06a6", + "reference": "552b4c554bb14d0c529631ce304cdf4a2b9d06a6", "shasum": "" }, "require": { @@ -260,9 +260,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/0.9.0" + "source": "https://github.com/utopia-php/cache/tree/0.9.1" }, - "time": "2024-01-07T18:11:23+00:00" + "time": "2024-03-19T17:07:20+00:00" }, { "name": "utopia-php/fetch", @@ -673,21 +673,21 @@ }, { "name": "nikic/php-parser", - "version": "v4.18.0", + "version": "v4.19.1", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999" + "reference": "4e1b88d21c69391150ace211e9eaf05810858d0b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1bcbb2179f97633e98bbbc87044ee2611c7d7999", - "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/4e1b88d21c69391150ace211e9eaf05810858d0b", + "reference": "4e1b88d21c69391150ace211e9eaf05810858d0b", "shasum": "" }, "require": { "ext-tokenizer": "*", - "php": ">=7.0" + "php": ">=7.1" }, "require-dev": { "ircmaxell/php-yacc": "^0.0.7", @@ -723,9 +723,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.18.0" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.1" }, - "time": "2023-12-10T21:03:43+00:00" + "time": "2024-03-17T08:10:35+00:00" }, { "name": "pcov/clobber", @@ -881,16 +881,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.60", + "version": "1.10.67", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "95dcea7d6c628a3f2f56d091d8a0219485a86bbe" + "reference": "16ddbe776f10da6a95ebd25de7c1dbed397dc493" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/95dcea7d6c628a3f2f56d091d8a0219485a86bbe", - "reference": "95dcea7d6c628a3f2f56d091d8a0219485a86bbe", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/16ddbe776f10da6a95ebd25de7c1dbed397dc493", + "reference": "16ddbe776f10da6a95ebd25de7c1dbed397dc493", "shasum": "" }, "require": { @@ -933,13 +933,9 @@ { "url": "https://github.com/phpstan", "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", - "type": "tidelift" } ], - "time": "2024-03-07T13:30:19+00:00" + "time": "2024-04-16T07:22:02+00:00" }, { "name": "phpunit/php-code-coverage", @@ -1262,16 +1258,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.17", + "version": "9.6.19", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "1a156980d78a6666721b7e8e8502fe210b587fcd" + "reference": "a1a54a473501ef4cdeaae4e06891674114d79db8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/1a156980d78a6666721b7e8e8502fe210b587fcd", - "reference": "1a156980d78a6666721b7e8e8502fe210b587fcd", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a1a54a473501ef4cdeaae4e06891674114d79db8", + "reference": "a1a54a473501ef4cdeaae4e06891674114d79db8", "shasum": "" }, "require": { @@ -1345,7 +1341,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.17" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.19" }, "funding": [ { @@ -1361,7 +1357,7 @@ "type": "tidelift" } ], - "time": "2024-02-23T13:14:51+00:00" + "time": "2024-04-05T04:35:58+00:00" }, { "name": "psr/container", @@ -2264,16 +2260,16 @@ }, { "name": "sebastian/resource-operations", - "version": "3.0.3", + "version": "3.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/resource-operations.git", - "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8" + "reference": "05d5692a7993ecccd56a03e40cd7e5b09b1d404e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8", - "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/05d5692a7993ecccd56a03e40cd7e5b09b1d404e", + "reference": "05d5692a7993ecccd56a03e40cd7e5b09b1d404e", "shasum": "" }, "require": { @@ -2285,7 +2281,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-main": "3.0-dev" } }, "autoload": { @@ -2306,8 +2302,7 @@ "description": "Provides a list of PHP built-in functions that operate on resources", "homepage": "https://www.github.com/sebastianbergmann/resource-operations", "support": { - "issues": "https://github.com/sebastianbergmann/resource-operations/issues", - "source": "https://github.com/sebastianbergmann/resource-operations/tree/3.0.3" + "source": "https://github.com/sebastianbergmann/resource-operations/tree/3.0.4" }, "funding": [ { @@ -2315,7 +2310,7 @@ "type": "github" } ], - "time": "2020-09-28T06:45:17+00:00" + "time": "2024-03-14T16:00:52+00:00" }, { "name": "sebastian/type", From 0645d8550cbcdb921d072b05f05b0f979442d94f Mon Sep 17 00:00:00 2001 From: fogelito Date: Wed, 17 Apr 2024 17:28:28 +0300 Subject: [PATCH 024/103] composer.lock --- composer.lock | 61 +++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/composer.lock b/composer.lock index 192acf6d6..346c57f42 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4adf56005e024ee6b5bb991e96e2ee72", + "content-hash": "2fdc7433d4d3ef058cab039b00b77427", "packages": [ { "name": "jean85/pretty-package-versions", @@ -305,48 +305,51 @@ }, { "name": "utopia-php/framework", - "version": "0.33.6", + "version": "0.34.2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "8fe57da0cecd57e3b17cd395b4a666a24f4c07a6" + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/8fe57da0cecd57e3b17cd395b4a666a24f4c07a6", - "reference": "8fe57da0cecd57e3b17cd395b4a666a24f4c07a6", + "url": "https://api.github.com/repos/utopia-php/http/zipball/fd126c02b78cc80678c9638f7b335dfb4a841b78", + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78", "shasum": "" }, "require": { + "ext-swoole": "*", "php": ">=8.0" }, "require-dev": { "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25" + "phpunit/phpunit": "^9.5.25", + "swoole/ide-helper": "4.8.3" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/" + "Utopia\\Http\\": "src/Http" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "description": "A simple, light and advanced PHP framework", + "description": "A simple, light and advanced PHP HTTP framework", "keywords": [ "framework", + "http", "php", "upf" ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.33.6" + "source": "https://github.com/utopia-php/http/tree/0.34.2" }, - "time": "2024-03-21T18:10:57+00:00" + "time": "2024-02-20T11:36:56+00:00" }, { "name": "utopia-php/mongo", @@ -878,16 +881,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.66", + "version": "1.10.67", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "94779c987e4ebd620025d9e5fdd23323903950bd" + "reference": "16ddbe776f10da6a95ebd25de7c1dbed397dc493" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/94779c987e4ebd620025d9e5fdd23323903950bd", - "reference": "94779c987e4ebd620025d9e5fdd23323903950bd", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/16ddbe776f10da6a95ebd25de7c1dbed397dc493", + "reference": "16ddbe776f10da6a95ebd25de7c1dbed397dc493", "shasum": "" }, "require": { @@ -930,13 +933,9 @@ { "url": "https://github.com/phpstan", "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", - "type": "tidelift" } ], - "time": "2024-03-28T16:17:31+00:00" + "time": "2024-04-16T07:22:02+00:00" }, { "name": "phpunit/php-code-coverage", @@ -2583,25 +2582,27 @@ }, { "name": "utopia-php/cli", - "version": "0.14.0", + "version": "0.17.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/0829fd5215afe88f53f3091cedc808da801fd1bb", + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/framework": "0.*.*" + "utopia-php/framework": "0.34.*" }, "require-dev": { + "laravel/pint": "1.2.*", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6" + "squizlabs/php_codesniffer": "^3.6", + "vimeo/psalm": "4.0.1" }, "type": "library", "autoload": { @@ -2613,12 +2614,6 @@ "license": [ "MIT" ], - "authors": [ - { - "name": "Eldad Fux", - "email": "eldad@appwrite.io" - } - ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2630,9 +2625,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.14.0" + "source": "https://github.com/utopia-php/cli/tree/0.17.0" }, - "time": "2022-10-09T10:19:07+00:00" + "time": "2024-01-24T11:37:29+00:00" } ], "aliases": [], From 6b8264a4e269d679182fc376179281b7108a4242 Mon Sep 17 00:00:00 2001 From: fogelito Date: Thu, 18 Apr 2024 15:50:22 +0300 Subject: [PATCH 025/103] updateRelationship --- src/Database/Adapter/Proxy.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Database/Adapter/Proxy.php b/src/Database/Adapter/Proxy.php index 6bb02b8b2..95f40a614 100644 --- a/src/Database/Adapter/Proxy.php +++ b/src/Database/Adapter/Proxy.php @@ -288,9 +288,9 @@ public function createRelationship(string $collection, string $relatedCollection * @param string|null $newTwoWayKey * @return bool */ - public function updateRelationship(string $collection, string $relatedCollection, string $type, bool $twoWay, string $key, string $twoWayKey, ?string $newKey = null, ?string $newTwoWayKey = null): bool + public function updateRelationship(string $collection, string $relatedCollection, string $type, bool $twoWay, string $key, string $twoWayKey, string $side, ?string $newKey = null, ?string $newTwoWayKey = null): bool { - return $this->query('updateRelationship', [$collection, $relatedCollection, $type, $twoWay, $key, $twoWayKey, $newKey, $newTwoWayKey]); + return $this->query('updateRelationship', [$collection, $relatedCollection, $type, $twoWay, $key, $twoWayKey, $side, $newKey, $newTwoWayKey]); } /** From 0d7b914c7770a5c488f104a36147d91db3b71368 Mon Sep 17 00:00:00 2001 From: fogelito Date: Fri, 19 Apr 2024 17:37:34 +0300 Subject: [PATCH 026/103] Remove Proxy files --- src/Database/Adapter/Proxy.php | 746 ------------------------- tests/e2e/Adapter/MariaDBProxyTest.php | 45 -- 2 files changed, 791 deletions(-) delete mode 100644 src/Database/Adapter/Proxy.php delete mode 100644 tests/e2e/Adapter/MariaDBProxyTest.php diff --git a/src/Database/Adapter/Proxy.php b/src/Database/Adapter/Proxy.php deleted file mode 100644 index 95f40a614..000000000 --- a/src/Database/Adapter/Proxy.php +++ /dev/null @@ -1,746 +0,0 @@ - $timeouts Map of timeouts where key is event name and value is timeout in milliseconds - */ - protected array $timeouts = []; - - /** - * Constructor. - * - * Set connection and settings - * - * @param string $endpoint - * @param string $secret - */ - public function __construct(string $endpoint, string $secret, string $database) - { - $this->endpoint = $endpoint; - $this->secret = $secret; - $this->database = $database; - } - - /** - * @param mixed[] $params - * - * @throws FetchException - * @throws DatabaseException - * @throws Exception - */ - private function query(string $query, array $params = []): mixed - { - $roles = $this->authorization->getRoles(); - - $response = Client::fetch( - url: $this->endpoint . '/queries', - headers: [ - 'x-utopia-secret' => $this->secret, - 'x-utopia-database' => $this->database, - 'x-utopia-namespace' => $this->getNamespace(), - 'x-utopia-auth-roles' => \json_encode($roles) ?: '', - 'x-utopia-auth-status' => $this->authorization->getStatus() ? 'true' : 'false', - 'x-utopia-auth-status-default' => $this->authorization->getStatusDefault() ? 'true' : 'false', - 'x-utopia-timeouts' => \json_encode($this->timeouts) ?: '', - 'x-utopia-share-tables' => $this->shareTables ? 'true' : 'false', - 'x-utopia-tenant' => \strval($this->tenant ?? ''), - 'content-type' => 'application/json' - ], - method: 'POST', - body: [ - 'query' => $query, - 'params' => \base64_encode(\serialize($params)) - ] - ); - - if ($response->getStatusCode() >= 400) { - if (empty($response->getBody())) { - throw new Exception('Internal ' . $response->getStatusCode() . ' HTTP error in data api'); - } - - $error = \json_decode($response->getBody(), true); - - try { - $exception = new $error['type']($error['message'], $error['code'], $error['file'], $error['line']); - /** - * @var DatabaseException $exception - */ - } catch(Throwable $err) { - // Cannot find exception type - throw new Exception($error['message'], $error['code']); - } - - throw $exception; - } - - $body = \json_decode($response->getBody(), false); - - $output = $body->output ?? ''; - - $processArray = function (mixed $self, mixed $json) { - $keys = []; - - foreach ($json as $param) { - if(\is_object($param)) { - $keys[] = new Document((array) $param); - } elseif(\is_array($param)) { - $keys[] = $self($self, $param); - } else { - $keys[] = $param; - } - } - - return $keys; - }; - - if(\is_array($output)) { - $output = $processArray($processArray, $output); - } else { - $output = $processArray($processArray, [$output])[0]; - } - - return $output; - } - - /** - * Ping Database - * - * @return bool - */ - public function ping(): bool - { - return $this->query('ping'); - } - - /** - * Create Database - * - * @param string $name - * - * @return bool - */ - public function create(string $name): bool - { - return $this->query('create', [$name]); - } - - /** - * Check if database exists - * Optionally check if collection exists in database - * - * @param string $database database name - * @param string|null $collection (optional) collection name - * - * @return bool - */ - public function exists(string $database, ?string $collection = null): bool - { - return $this->query('exists', [$database, $collection]); - } - - /** - * List Databases - * - * @return array - */ - public function list(): array - { - return $this->query('list'); - } - - /** - * Delete Database - * - * @param string $name - * - * @return bool - */ - public function delete(string $name): bool - { - return $this->query('delete', [$name]); - } - - /** - * Create Collection - * - * @param string $name - * @param array $attributes (optional) - * @param array $indexes (optional) - * @return bool - */ - public function createCollection(string $name, array $attributes = [], array $indexes = []): bool - { - return $this->query('createCollection', [$name, $attributes, $indexes]); - } - - /** - * Delete Collection - * - * @param string $id - * - * @return bool - */ - public function deleteCollection(string $id): bool - { - return $this->query('deleteCollection', [$id]); - } - - /** - * Create Attribute - * - * @param string $collection - * @param string $id - * @param string $type - * @param int $size - * @param bool $signed - * @param bool $array - * @return bool - */ - public function createAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false): bool - { - return $this->query('createAttribute', [$collection, $id, $type, $size, $signed, $array]); - } - - /** - * Update Attribute - * - * @param string $collection - * @param string $id - * @param string $type - * @param int $size - * @param bool $signed - * @param bool $array - * - * @return bool - */ - public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false): bool - { - return $this->query('updateAttribute', [$collection, $id, $type, $size, $signed, $array]); - } - - /** - * Delete Attribute - * - * @param string $collection - * @param string $id - * - * @return bool - */ - public function deleteAttribute(string $collection, string $id): bool - { - return $this->query('deleteAttribute', [$collection, $id]); - } - - /** - * Rename Attribute - * - * @param string $collection - * @param string $old - * @param string $new - * @return bool - */ - public function renameAttribute(string $collection, string $old, string $new): bool - { - return $this->query('renameAttribute', [$collection, $old, $new]); - } - - /** - * @param string $collection - * @param string $relatedCollection - * @param string $type - * @param bool $twoWay - * @param string $id - * @param string $twoWayKey - * @return bool - */ - public function createRelationship(string $collection, string $relatedCollection, string $type, bool $twoWay = false, string $id = '', string $twoWayKey = ''): bool - { - return $this->query('createRelationship', [$collection, $relatedCollection, $type, $twoWay, $id, $twoWayKey]); - } - - /** - * Update Relationship - * - * @param string $collection - * @param string $relatedCollection - * @param string $type - * @param bool $twoWay - * @param string $key - * @param string $twoWayKey - * @param string|null $newKey - * @param string|null $newTwoWayKey - * @return bool - */ - public function updateRelationship(string $collection, string $relatedCollection, string $type, bool $twoWay, string $key, string $twoWayKey, string $side, ?string $newKey = null, ?string $newTwoWayKey = null): bool - { - return $this->query('updateRelationship', [$collection, $relatedCollection, $type, $twoWay, $key, $twoWayKey, $side, $newKey, $newTwoWayKey]); - } - - /** - * Delete Relationship - * - * @param string $collection - * @param string $relatedCollection - * @param string $type - * @param bool $twoWay - * @param string $key - * @param string $twoWayKey - * @param string $side - * @return bool - */ - public function deleteRelationship(string $collection, string $relatedCollection, string $type, bool $twoWay, string $key, string $twoWayKey, string $side): bool - { - return $this->query('deleteRelationship', [$collection, $relatedCollection, $type, $twoWay, $key, $twoWayKey, $side]); - } - - /** - * Rename Index - * - * @param string $collection - * @param string $old - * @param string $new - * @return bool - */ - public function renameIndex(string $collection, string $old, string $new): bool - { - return $this->query('renameIndex', [$collection, $old, $new]); - } - - /** - * Create Index - * - * @param string $collection - * @param string $id - * @param string $type - * @param array $attributes - * @param array $lengths - * @param array $orders - * - * @return bool - */ - public function createIndex(string $collection, string $id, string $type, array $attributes, array $lengths, array $orders): bool - { - return $this->query('createIndex', [$collection, $id, $type, $attributes, $lengths, $orders]); - } - - /** - * Delete Index - * - * @param string $collection - * @param string $id - * - * @return bool - */ - public function deleteIndex(string $collection, string $id): bool - { - return $this->query('deleteIndex', [$collection, $id]); - } - - /** - * Get Document - * - * @param string $collection - * @param string $id - * @param array $queries - * @return Document - */ - public function getDocument(string $collection, string $id, array $queries = []): Document - { - return $this->query('getDocument', [$collection, $id, $queries]); - } - - /** - * Create Document - * - * @param string $collection - * @param Document $document - * - * @return Document - */ - public function createDocument(string $collection, Document $document): Document - { - return $this->query('createDocument', [$collection, $document]); - } - - /** - * Create Documents in batches - * - * @param string $collection - * @param array $documents - * @param int $batchSize - * - * @return array - * - * @throws DatabaseException - */ - public function createDocuments(string $collection, array $documents, int $batchSize): array - { - return $this->query('createDocuments', [$collection, $documents, $batchSize]); - } - - /** - * Update Document - * - * @param string $collection - * @param Document $document - * - * @return Document - */ - public function updateDocument(string $collection, Document $document): Document - { - return $this->query('updateDocument', [$collection, $document]); - } - - /** - * Update Documents in batches - * - * @param string $collection - * @param array $documents - * @param int $batchSize - * - * @return array - * - * @throws DatabaseException - */ - public function updateDocuments(string $collection, array $documents, int $batchSize): array - { - return $this->query('updateDocuments', [$collection, $documents, $batchSize]); - } - - /** - * Delete Document - * - * @param string $collection - * @param string $id - * - * @return bool - */ - public function deleteDocument(string $collection, string $id): bool - { - return $this->query('deleteDocument', [$collection, $id]); - } - - /** - * Find Documents - * - * Find data sets using chosen queries - * - * @param string $collection - * @param array $queries - * @param int|null $limit - * @param int|null $offset - * @param array $orderAttributes - * @param array $orderTypes - * @param array $cursor - * @param string $cursorDirection - * - * @return array - */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array - { - return $this->query('find', [$collection, $queries, $limit, $offset, $orderAttributes, $orderTypes, $cursor, $cursorDirection]); - } - - /** - * Sum an attribute - * - * @param string $collection - * @param string $attribute - * @param array $queries - * @param int|null $max - * - * @return int|float - */ - public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): float|int - { - return $this->query('sum', [$collection, $attribute, $queries, $max]); - } - - /** - * Count Documents - * - * @param string $collection - * @param array $queries - * @param int|null $max - * - * @return int - */ - public function count(string $collection, array $queries = [], ?int $max = null): int - { - return $this->query('count', [$collection, $queries, $max]); - } - - /** - * Get Collection Size - * - * @param string $collection - * @return int - * @throws DatabaseException - */ - public function getSizeOfCollection(string $collection): int - { - return $this->query('getSizeOfCollection', [$collection]); - } - - /** - * Get max STRING limit - * - * @return int - */ - public function getLimitForString(): int - { - return $this->query('getLimitForString'); - } - - /** - * Get max INT limit - * - * @return int - */ - public function getLimitForInt(): int - { - return $this->query('getLimitForInt'); - } - - /** - * Get maximum attributes limit. - * - * @return int - */ - public function getLimitForAttributes(): int - { - return $this->query('getLimitForAttributes'); - } - - /** - * Get maximum index limit. - * - * @return int - */ - public function getLimitForIndexes(): int - { - return $this->query('getLimitForIndexes'); - } - - /** - * Is schemas supported? - * - * @return bool - */ - public function getSupportForSchemas(): bool - { - return $this->query('getSupportForSchemas'); - } - - /** - * Is index supported? - * - * @return bool - */ - public function getSupportForIndex(): bool - { - return $this->query('getSupportForIndex'); - } - - /** - * Is unique index supported? - * - * @return bool - */ - public function getSupportForUniqueIndex(): bool - { - return $this->query('getSupportForUniqueIndex'); - } - - /** - * Is fulltext index supported? - * - * @return bool - */ - public function getSupportForFulltextIndex(): bool - { - return $this->query('getSupportForFulltextIndex'); - } - - /** - * Is fulltext wildcard supported? - * - * @return bool - */ - public function getSupportForFulltextWildcardIndex(): bool - { - return $this->query('getSupportForFulltextWildcardIndex'); - } - - - /** - * Does the adapter handle casting? - * - * @return bool - */ - public function getSupportForCasting(): bool - { - return $this->query('getSupportForCasting'); - } - - /** - * Does the adapter handle array Contains? - * - * @return bool - */ - public function getSupportForQueryContains(): bool - { - return $this->query('getSupportForQueryContains'); - } - - /** - * Are timeouts supported? - * - * @return bool - */ - public function getSupportForTimeouts(): bool - { - return $this->query('getSupportForTimeouts'); - } - - /** - * Are relationships supported? - * - * @return bool - */ - public function getSupportForRelationships(): bool - { - return $this->query('getSupportForRelationships'); - } - - /** - * Get current attribute count from collection document - * - * @param Document $collection - * @return int - */ - public function getCountOfAttributes(Document $collection): int - { - return $this->query('getCountOfAttributes', [$collection]); - } - - /** - * Get current index count from collection document - * - * @param Document $collection - * @return int - */ - public function getCountOfIndexes(Document $collection): int - { - return $this->query('getCountOfIndexes', [$collection]); - } - - /** - * Estimate maximum number of bytes required to store a document in $collection. - * Byte requirement varies based on column type and size. - * Needed to satisfy MariaDB/MySQL row width limit. - * Return 0 when no restrictions apply to row width - * - * @param Document $collection - * @return int - */ - public function getAttributeWidth(Document $collection): int - { - return $this->query('getAttributeWidth', [$collection]); - } - - /** - * Get list of keywords that cannot be used - * - * @return array - */ - public function getKeywords(): array - { - return $this->query('getKeywords'); - } - - /** - * Get an attribute projection given a list of selected attributes - * - * @param array $selections - * @param string $prefix - * @return mixed - */ - protected function getAttributeProjection(array $selections, string $prefix = ''): mixed - { - return $this->query('getAttributeProjection', [$selections, $prefix]); - } - - /** - * Increase and Decrease Attribute Value - * - * @param string $collection - * @param string $id - * @param string $attribute - * @param int|float $value - * @param int|float|null $min - * @param int|float|null $max - * @return bool - * @throws Exception - */ - public function increaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value, int|float|null $min = null, int|float|null $max = null): bool - { - return $this->query('increaseDocumentAttribute', [$collection, $id, $attribute, $value, $min, $max]); - } - - /** - * @return int - */ - public function getMaxIndexLength(): int - { - return $this->query('getMaxIndexLength'); - } - - /** - * Set a global timeout for database queries in milliseconds. - * - * This function allows you to set a maximum execution time for all database - * queries executed using the library, or a specific event specified by the - * event parameter. Once this timeout is set, any database query that takes - * longer than the specified time will be automatically terminated by the library, - * and an appropriate error or exception will be raised to handle the timeout condition. - * - * @param int $milliseconds The timeout value in milliseconds for database queries. - * @param string $event The event the timeout should fire fore - * @return void - * - * @throws Exception The provided timeout value must be greater than or equal to 0. - */ - public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void - { - $this->timeouts[$event] = $milliseconds; - } - - /** - * Clears a global timeout for database queries. - * - * @param string $event - * @return void - */ - public function clearTimeout(string $event): void - { - unset($this->timeouts[$event]); - } -} diff --git a/tests/e2e/Adapter/MariaDBProxyTest.php b/tests/e2e/Adapter/MariaDBProxyTest.php deleted file mode 100644 index bd92393f3..000000000 --- a/tests/e2e/Adapter/MariaDBProxyTest.php +++ /dev/null @@ -1,45 +0,0 @@ -setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); - - if ($database->exists('utopiaTests')) { - $database->delete('utopiaTests'); - } - - $database->create(); - - return self::$database = $database; - } -} From 04abd9110c8f79974fbddd9d639bf90bfaa49923 Mon Sep 17 00:00:00 2001 From: fogelito Date: Thu, 9 May 2024 21:20:34 +0300 Subject: [PATCH 027/103] pull main --- composer.lock | 61 +++++++++++++++--------------- src/Database/Validator/Index.php | 2 +- src/Database/Validator/Queries.php | 2 +- 3 files changed, 32 insertions(+), 33 deletions(-) diff --git a/composer.lock b/composer.lock index ce3743198..c11faf49d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1fec834c5b222e402702b7bc89a5a8a8", + "content-hash": "fec48bd2695ef6429a8963b4ef480884", "packages": [ { "name": "jean85/pretty-package-versions", @@ -266,48 +266,51 @@ }, { "name": "utopia-php/framework", - "version": "0.33.6", + "version": "0.34.2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "8fe57da0cecd57e3b17cd395b4a666a24f4c07a6" + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/8fe57da0cecd57e3b17cd395b4a666a24f4c07a6", - "reference": "8fe57da0cecd57e3b17cd395b4a666a24f4c07a6", + "url": "https://api.github.com/repos/utopia-php/http/zipball/fd126c02b78cc80678c9638f7b335dfb4a841b78", + "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78", "shasum": "" }, "require": { + "ext-swoole": "*", "php": ">=8.0" }, "require-dev": { "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25" + "phpunit/phpunit": "^9.5.25", + "swoole/ide-helper": "4.8.3" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/" + "Utopia\\Http\\": "src/Http" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "description": "A simple, light and advanced PHP framework", + "description": "A simple, light and advanced PHP HTTP framework", "keywords": [ "framework", + "http", "php", "upf" ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.33.6" + "source": "https://github.com/utopia-php/http/tree/0.34.2" }, - "time": "2024-03-21T18:10:57+00:00" + "time": "2024-02-20T11:36:56+00:00" }, { "name": "utopia-php/mongo", @@ -2423,16 +2426,16 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.4.0", + "version": "v3.5.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", - "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", + "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", "shasum": "" }, "require": { @@ -2441,7 +2444,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "3.4-dev" + "dev-main": "3.5-dev" }, "thanks": { "name": "symfony/contracts", @@ -2470,7 +2473,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.0" }, "funding": [ { @@ -2486,7 +2489,7 @@ "type": "tidelift" } ], - "time": "2023-05-23T14:45:45+00:00" + "time": "2024-04-18T09:32:20+00:00" }, { "name": "theseer/tokenizer", @@ -2540,25 +2543,27 @@ }, { "name": "utopia-php/cli", - "version": "0.14.0", + "version": "0.17.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/0829fd5215afe88f53f3091cedc808da801fd1bb", + "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/framework": "0.*.*" + "utopia-php/framework": "0.34.*" }, "require-dev": { + "laravel/pint": "1.2.*", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6" + "squizlabs/php_codesniffer": "^3.6", + "vimeo/psalm": "4.0.1" }, "type": "library", "autoload": { @@ -2570,12 +2575,6 @@ "license": [ "MIT" ], - "authors": [ - { - "name": "Eldad Fux", - "email": "eldad@appwrite.io" - } - ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2587,9 +2586,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.14.0" + "source": "https://github.com/utopia-php/cli/tree/0.17.0" }, - "time": "2022-10-09T10:19:07+00:00" + "time": "2024-01-24T11:37:29+00:00" } ], "aliases": [], diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index b24e39f73..08e269ae5 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -5,7 +5,7 @@ use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; -use Utopia\Validator; +use Utopia\Http\Validator; class Index extends Validator { diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index 2e4aac71a..608ac73fc 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -4,7 +4,7 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Query\Base; -use Utopia\Validator; +use Utopia\Http\Validator; class Queries extends Validator { From f53d63bc5903ea6d6ff8f61293a20235e912b242 Mon Sep 17 00:00:00 2001 From: fogelito Date: Thu, 9 May 2024 21:33:47 +0300 Subject: [PATCH 028/103] lint --- bin/tasks/query.php | 1 - src/Database/Validator/Structure.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 232161ffa..21b2faf1d 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -14,7 +14,6 @@ use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; use Utopia\Database\Query; -use Utopia\Database\Validator\Authorization; use Utopia\Mongo\Client; use Utopia\Validator\Numeric; use Utopia\Validator\Text; diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 2b0409a5d..b6e00b528 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -12,8 +12,8 @@ use Utopia\Http\Validator\Boolean; use Utopia\Http\Validator\FloatValidator; use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Text; use Utopia\Http\Validator\Range; +use Utopia\Http\Validator\Text; class Structure extends Validator { From 5b0d6ba40141dd9d4983d3aac018782f8ecdfc8a Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Wed, 5 Jun 2024 20:07:47 -0400 Subject: [PATCH 029/103] chore: Updating composer.lock --- composer.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.lock b/composer.lock index c11faf49d..28d3cfcf6 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "fec48bd2695ef6429a8963b4ef480884", + "content-hash": "5c60ed13bb6b0fa26209a9f44e4f868f", "packages": [ { "name": "jean85/pretty-package-versions", @@ -216,16 +216,16 @@ }, { "name": "utopia-php/cache", - "version": "0.9.1", + "version": "0.10.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "552b4c554bb14d0c529631ce304cdf4a2b9d06a6" + "reference": "313bcdfbb166f75c2c205a59d1467cead63a9626" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/552b4c554bb14d0c529631ce304cdf4a2b9d06a6", - "reference": "552b4c554bb14d0c529631ce304cdf4a2b9d06a6", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/313bcdfbb166f75c2c205a59d1467cead63a9626", + "reference": "313bcdfbb166f75c2c205a59d1467cead63a9626", "shasum": "" }, "require": { @@ -260,9 +260,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/0.9.1" + "source": "https://github.com/utopia-php/cache/tree/0.10.0" }, - "time": "2024-03-19T17:07:20+00:00" + "time": "2024-06-05T16:40:43+00:00" }, { "name": "utopia-php/framework", From 964bfa23a6efb6a437cf90b5dc5ad6540ec28e28 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Fri, 19 Jul 2024 12:46:00 -0400 Subject: [PATCH 030/103] chore: merge --- composer.lock | 85 ++++++++++++++++++++------------------- src/Database/Database.php | 7 ++-- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/composer.lock b/composer.lock index cf5f75087..49080f907 100644 --- a/composer.lock +++ b/composer.lock @@ -136,16 +136,16 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.29.0", + "version": "v1.30.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b" + "reference": "77fa7995ac1b21ab60769b7323d600a991a90433" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", - "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/77fa7995ac1b21ab60769b7323d600a991a90433", + "reference": "77fa7995ac1b21ab60769b7323d600a991a90433", "shasum": "" }, "require": { @@ -196,7 +196,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.29.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.30.0" }, "funding": [ { @@ -212,20 +212,20 @@ "type": "tidelift" } ], - "time": "2024-01-29T20:11:03+00:00" + "time": "2024-05-31T15:07:36+00:00" }, { "name": "utopia-php/cache", - "version": "0.10.1", + "version": "0.10.2", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "87ee4fc91e50d4ddfef650aa999ea12be3a99583" + "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/87ee4fc91e50d4ddfef650aa999ea12be3a99583", - "reference": "87ee4fc91e50d4ddfef650aa999ea12be3a99583", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/b22c6eb6d308de246b023efd0fc9758aee8b8247", + "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247", "shasum": "" }, "require": { @@ -260,22 +260,22 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/0.10.1" + "source": "https://github.com/utopia-php/cache/tree/0.10.2" }, - "time": "2024-06-18T13:20:25+00:00" + "time": "2024-06-25T20:36:35+00:00" }, { "name": "utopia-php/framework", - "version": "0.34.2", + "version": "0.34.3", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78" + "reference": "e3bbca07c1df4e908ea9d3ce4f59367a7696b66b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/fd126c02b78cc80678c9638f7b335dfb4a841b78", - "reference": "fd126c02b78cc80678c9638f7b335dfb4a841b78", + "url": "https://api.github.com/repos/utopia-php/http/zipball/e3bbca07c1df4e908ea9d3ce4f59367a7696b66b", + "reference": "e3bbca07c1df4e908ea9d3ce4f59367a7696b66b", "shasum": "" }, "require": { @@ -292,7 +292,8 @@ "type": "library", "autoload": { "psr-4": { - "Utopia\\Http\\": "src/Http" + "Utopia\\": "src/", + "Tests\\E2E\\": "tests/e2e" } }, "notification-url": "https://packagist.org/downloads/", @@ -308,9 +309,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.34.2" + "source": "https://github.com/utopia-php/http/tree/0.34.3" }, - "time": "2024-02-20T11:36:56+00:00" + "time": "2024-07-02T15:08:46+00:00" }, { "name": "utopia-php/mongo", @@ -1220,45 +1221,45 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.19", + "version": "9.6.20", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "a1a54a473501ef4cdeaae4e06891674114d79db8" + "reference": "49d7820565836236411f5dc002d16dd689cde42f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a1a54a473501ef4cdeaae4e06891674114d79db8", - "reference": "a1a54a473501ef4cdeaae4e06891674114d79db8", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/49d7820565836236411f5dc002d16dd689cde42f", + "reference": "49d7820565836236411f5dc002d16dd689cde42f", "shasum": "" }, "require": { - "doctrine/instantiator": "^1.3.1 || ^2", + "doctrine/instantiator": "^1.5.0 || ^2", "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-xml": "*", "ext-xmlwriter": "*", - "myclabs/deep-copy": "^1.10.1", - "phar-io/manifest": "^2.0.3", - "phar-io/version": "^3.0.2", + "myclabs/deep-copy": "^1.12.0", + "phar-io/manifest": "^2.0.4", + "phar-io/version": "^3.2.1", "php": ">=7.3", - "phpunit/php-code-coverage": "^9.2.28", - "phpunit/php-file-iterator": "^3.0.5", + "phpunit/php-code-coverage": "^9.2.31", + "phpunit/php-file-iterator": "^3.0.6", "phpunit/php-invoker": "^3.1.1", - "phpunit/php-text-template": "^2.0.3", - "phpunit/php-timer": "^5.0.2", - "sebastian/cli-parser": "^1.0.1", - "sebastian/code-unit": "^1.0.6", + "phpunit/php-text-template": "^2.0.4", + "phpunit/php-timer": "^5.0.3", + "sebastian/cli-parser": "^1.0.2", + "sebastian/code-unit": "^1.0.8", "sebastian/comparator": "^4.0.8", - "sebastian/diff": "^4.0.3", - "sebastian/environment": "^5.1.3", - "sebastian/exporter": "^4.0.5", - "sebastian/global-state": "^5.0.1", - "sebastian/object-enumerator": "^4.0.3", - "sebastian/resource-operations": "^3.0.3", - "sebastian/type": "^3.2", + "sebastian/diff": "^4.0.6", + "sebastian/environment": "^5.1.5", + "sebastian/exporter": "^4.0.6", + "sebastian/global-state": "^5.0.7", + "sebastian/object-enumerator": "^4.0.4", + "sebastian/resource-operations": "^3.0.4", + "sebastian/type": "^3.2.1", "sebastian/version": "^3.0.2" }, "suggest": { @@ -1303,7 +1304,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.19" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.20" }, "funding": [ { @@ -1319,7 +1320,7 @@ "type": "tidelift" } ], - "time": "2024-04-05T04:35:58+00:00" + "time": "2024-07-10T11:45:39+00:00" }, { "name": "psr/container", diff --git a/src/Database/Database.php b/src/Database/Database.php index 1d8fd3cb0..6f270ff73 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3689,12 +3689,11 @@ public function updateDocument(string $collection, string $id, Document $documen $readValidator = new Input(self::PERMISSION_READ, [ ...$collection->getRead(), ...($documentSecurity ? $old->getRead() : []) - ])); + ]); if (($shouldUpdate && !$this->authorization->isValid($updateValidator)) - || (!$shouldUpdate && !$this->authorization->isValid($readValidator)){ - throw new AuthorizationException($this->authorization->getDescription()); - + || (!$shouldUpdate && !$this->authorization->isValid($readValidator))) { + throw new AuthorizationException($this->authorization->getDescription()); } } From ab01fa3bdb9e6450d8922e140b295bb7452eaad0 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Fri, 19 Jul 2024 12:51:25 -0400 Subject: [PATCH 031/103] chore: codeql --- tests/e2e/Adapter/SharedTables/MariaDBTest.php | 2 +- tests/e2e/Adapter/SharedTables/MongoDBTest.php | 2 +- tests/e2e/Adapter/SharedTables/MySQLTest.php | 2 +- tests/e2e/Adapter/SharedTables/PostgresTest.php | 2 +- tests/e2e/Adapter/SharedTables/SQLiteTest.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/e2e/Adapter/SharedTables/MariaDBTest.php b/tests/e2e/Adapter/SharedTables/MariaDBTest.php index 249e13319..21debcdc5 100644 --- a/tests/e2e/Adapter/SharedTables/MariaDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MariaDBTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(bool $fresh = false): Database + public function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; diff --git a/tests/e2e/Adapter/SharedTables/MongoDBTest.php b/tests/e2e/Adapter/SharedTables/MongoDBTest.php index 47f480073..47d40767e 100644 --- a/tests/e2e/Adapter/SharedTables/MongoDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MongoDBTest.php @@ -30,7 +30,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; diff --git a/tests/e2e/Adapter/SharedTables/MySQLTest.php b/tests/e2e/Adapter/SharedTables/MySQLTest.php index 689ea49c7..d5b891e57 100644 --- a/tests/e2e/Adapter/SharedTables/MySQLTest.php +++ b/tests/e2e/Adapter/SharedTables/MySQLTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; diff --git a/tests/e2e/Adapter/SharedTables/PostgresTest.php b/tests/e2e/Adapter/SharedTables/PostgresTest.php index df85dfeb0..483f5249a 100644 --- a/tests/e2e/Adapter/SharedTables/PostgresTest.php +++ b/tests/e2e/Adapter/SharedTables/PostgresTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; diff --git a/tests/e2e/Adapter/SharedTables/SQLiteTest.php b/tests/e2e/Adapter/SharedTables/SQLiteTest.php index a69984216..87cf381b6 100644 --- a/tests/e2e/Adapter/SharedTables/SQLiteTest.php +++ b/tests/e2e/Adapter/SharedTables/SQLiteTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public static function getDatabase(): Database + public function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; From 9ddf91aa4812a0eeb7feb9667b4827b407032df1 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Fri, 19 Jul 2024 13:41:23 -0400 Subject: [PATCH 032/103] tests: Adjusting to new authorization --- tests/e2e/Adapter/SharedTables/MariaDBTest.php | 1 + tests/e2e/Adapter/SharedTables/MongoDBTest.php | 1 + tests/e2e/Adapter/SharedTables/MySQLTest.php | 1 + tests/e2e/Adapter/SharedTables/PostgresTest.php | 1 + tests/e2e/Adapter/SharedTables/SQLiteTest.php | 1 + 5 files changed, 5 insertions(+) diff --git a/tests/e2e/Adapter/SharedTables/MariaDBTest.php b/tests/e2e/Adapter/SharedTables/MariaDBTest.php index 21debcdc5..7ee04ac5b 100644 --- a/tests/e2e/Adapter/SharedTables/MariaDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MariaDBTest.php @@ -48,6 +48,7 @@ public function getDatabase(bool $fresh = false): Database $database = new Database(new MariaDB($pdo), $cache); $database + ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/MongoDBTest.php b/tests/e2e/Adapter/SharedTables/MongoDBTest.php index 47d40767e..c5968727c 100644 --- a/tests/e2e/Adapter/SharedTables/MongoDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MongoDBTest.php @@ -53,6 +53,7 @@ public function getDatabase(): Database $database = new Database(new Mongo($client), $cache); $database + ->setAuthorization(self::$authorization) ->setDatabase($schema) ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/MySQLTest.php b/tests/e2e/Adapter/SharedTables/MySQLTest.php index d5b891e57..af244d985 100644 --- a/tests/e2e/Adapter/SharedTables/MySQLTest.php +++ b/tests/e2e/Adapter/SharedTables/MySQLTest.php @@ -50,6 +50,7 @@ public function getDatabase(): Database $database = new Database(new MySQL($pdo), $cache); $database + ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/PostgresTest.php b/tests/e2e/Adapter/SharedTables/PostgresTest.php index 483f5249a..4de48ee1d 100644 --- a/tests/e2e/Adapter/SharedTables/PostgresTest.php +++ b/tests/e2e/Adapter/SharedTables/PostgresTest.php @@ -47,6 +47,7 @@ public function getDatabase(): Database $database = new Database(new Postgres($pdo), $cache); $database + ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/SQLiteTest.php b/tests/e2e/Adapter/SharedTables/SQLiteTest.php index 87cf381b6..a1254505d 100644 --- a/tests/e2e/Adapter/SharedTables/SQLiteTest.php +++ b/tests/e2e/Adapter/SharedTables/SQLiteTest.php @@ -53,6 +53,7 @@ public function getDatabase(): Database $database = new Database(new SQLite($pdo), $cache); $database + ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) From 36720e88125e3c16fb770bf2422a757fcec68050 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:41:07 -0400 Subject: [PATCH 033/103] chore: versions upgrade --- bin/tasks/index.php | 2 +- bin/tasks/load.php | 4 +- bin/tasks/query.php | 4 +- composer.json | 6 +- composer.lock | 142 ++++++++++++++++++++++++++++++++++++++------ 5 files changed, 131 insertions(+), 27 deletions(-) diff --git a/bin/tasks/index.php b/bin/tasks/index.php index 5b43b5920..e44c0dd56 100644 --- a/bin/tasks/index.php +++ b/bin/tasks/index.php @@ -14,7 +14,7 @@ use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; use Utopia\Mongo\Client; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Text; /** * @Example diff --git a/bin/tasks/load.php b/bin/tasks/load.php index 85b00b1f0..d21734717 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -22,8 +22,8 @@ use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; use Utopia\Mongo\Client; -use Utopia\Validator\Numeric; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Text; $authorization = new Authorization(); diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 21b2faf1d..2aafacdca 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -15,8 +15,8 @@ use Utopia\Database\Database; use Utopia\Database\Query; use Utopia\Mongo\Client; -use Utopia\Validator\Numeric; -use Utopia\Validator\Text; +use Utopia\Http\Validator\Numeric; +use Utopia\Http\Validator\Text; /** * @Example diff --git a/composer.json b/composer.json index f0a165dbd..632d56734 100755 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "type": "library", "keywords": ["php","framework", "upf", "utopia", "database"], "license": "MIT", - "minimum-stability": "stable", + "minimum-stability": "RC", "autoload": { "psr-4": {"Utopia\\Database\\": "src/Database"} }, @@ -36,7 +36,7 @@ "ext-pdo": "*", "ext-mbstring": "*", "php": ">=8.0", - "utopia-php/framework": "0.34.*", + "utopia-php/framework": "1.0.*", "utopia-php/cache": "0.10.*", "utopia-php/mongo": "0.3.*" }, @@ -45,7 +45,7 @@ "phpunit/phpunit": "^9.4", "pcov/clobber": "^2.0", "swoole/ide-helper": "4.8.0", - "utopia-php/cli": "0.17.*", + "utopia-php/cli": "1.0.*", "laravel/pint": "1.13.*", "phpstan/phpstan": "1.10.*", "rregeer/phpunit-coverage-check": "^0.3.1" diff --git a/composer.lock b/composer.lock index 49080f907..ced8ceeb0 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5c60ed13bb6b0fa26209a9f44e4f868f", + "content-hash": "09bc4991024f1e5885c8bf530f009c26", "packages": [ { "name": "jean85/pretty-package-versions", @@ -264,25 +264,75 @@ }, "time": "2024-06-25T20:36:35+00:00" }, + { + "name": "utopia-php/di", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/di.git", + "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/di/zipball/22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "laravel/pint": "^1.2", + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^9.5.25", + "swoole/ide-helper": "4.8.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\": "src/", + "Tests\\E2E\\": "tests/e2e" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A simple and lite library for managing dependency injections", + "keywords": [ + "framework", + "http", + "php", + "upf" + ], + "support": { + "issues": "https://github.com/utopia-php/di/issues", + "source": "https://github.com/utopia-php/di/tree/0.1.0" + }, + "time": "2024-08-08T14:35:19+00:00" + }, { "name": "utopia-php/framework", - "version": "0.34.3", + "version": "1.0.0-RC2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "e3bbca07c1df4e908ea9d3ce4f59367a7696b66b" + "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/e3bbca07c1df4e908ea9d3ce4f59367a7696b66b", - "reference": "e3bbca07c1df4e908ea9d3ce4f59367a7696b66b", + "url": "https://api.github.com/repos/utopia-php/http/zipball/d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", + "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", "shasum": "" }, "require": { "ext-swoole": "*", - "php": ">=8.0" + "php": ">=8.0", + "utopia-php/servers": "0.1.* " }, "require-dev": { + "ext-xdebug": "*", "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", @@ -292,8 +342,7 @@ "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/", - "Tests\\E2E\\": "tests/e2e" + "Utopia\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -309,9 +358,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.34.3" + "source": "https://github.com/utopia-php/http/tree/1.0.0-RC2" }, - "time": "2024-07-02T15:08:46+00:00" + "time": "2024-08-08T14:46:41+00:00" }, { "name": "utopia-php/mongo", @@ -372,6 +421,59 @@ "source": "https://github.com/utopia-php/mongo/tree/0.3.1" }, "time": "2023-09-01T17:25:28+00:00" + }, + { + "name": "utopia-php/servers", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/servers.git", + "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/servers/zipball/7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", + "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", + "shasum": "" + }, + "require": { + "php": ">=8.0", + "utopia-php/di": "0.1.*" + }, + "require-dev": { + "laravel/pint": "^0.2.3", + "phpstan/phpstan": "^1.8", + "phpunit/phpunit": "^9.5.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\Servers\\": "src/Servers" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Team Appwrite", + "email": "team@appwrite.io" + } + ], + "description": "A base library for building Utopia style servers.", + "keywords": [ + "framework", + "php", + "servers", + "upf", + "utopia" + ], + "support": { + "issues": "https://github.com/utopia-php/servers/issues", + "source": "https://github.com/utopia-php/servers/tree/0.1.0" + }, + "time": "2024-08-08T14:31:39+00:00" } ], "packages-dev": [ @@ -2545,27 +2647,29 @@ }, { "name": "utopia-php/cli", - "version": "0.17.0", + "version": "1.0.0-RC1", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb" + "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/0829fd5215afe88f53f3091cedc808da801fd1bb", - "reference": "0829fd5215afe88f53f3091cedc808da801fd1bb", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", + "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/framework": "0.34.*" + "utopia-php/di": "0.1.*", + "utopia-php/framework": "1.0.*" }, "require-dev": { "laravel/pint": "1.2.*", + "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^9.3", "squizlabs/php_codesniffer": "^3.6", - "vimeo/psalm": "4.0.1" + "swoole/ide-helper": "4.8.8" }, "type": "library", "autoload": { @@ -2588,13 +2692,13 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.17.0" + "source": "https://github.com/utopia-php/cli/tree/1.0.0-RC1" }, - "time": "2024-01-24T11:37:29+00:00" + "time": "2024-08-09T17:35:04+00:00" } ], "aliases": [], - "minimum-stability": "stable", + "minimum-stability": "RC", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, From a25e63ea09184956b3070a30605f71310adfcc57 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:38:56 -0400 Subject: [PATCH 034/103] chore: merge --- src/Database/Database.php | 3 +-- tests/e2e/Adapter/Base.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 31c079b0f..bb481d173 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3688,11 +3688,10 @@ public function updateDocument(string $collection, string $id, Document $documen $time = DateTime::now(); $old = $this->authorization->skip(fn () => $this->silent( fn () => - $this->getDocument($collection->getId(), $id, forUpdate: true + $this->getDocument($collection->getId(), $id, forUpdate: true) )); $document = \array_merge($old->getArrayCopy(), $document->getArrayCopy()); - $document = \array_merge($old->getArrayCopy(), $document->getArrayCopy()); $document['$collection'] = $old->getAttribute('$collection'); // Make sure user doesn't switch collection ID if ($this->adapter->getSharedTables()) { $document['$tenant'] = $old->getAttribute('$tenant'); // Make sure user doesn't switch tenant diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 629ae5272..f3e1519e8 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -4163,7 +4163,7 @@ public function testAndNested(): void public function testNestedIDQueries(): void { - Authorization::setRole(Role::any()->toString()); + self::$authorization->addRole(Role::any()->toString()); static::getDatabase()->createCollection('movies_nested_id', permissions: [ Permission::create(Role::any()), From 8dfdf8dbb2b280fbfdc9a9ee476faa509a2c0283 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:46:57 -0400 Subject: [PATCH 035/103] chore: format --- bin/tasks/index.php | 2 +- bin/tasks/load.php | 2 +- bin/tasks/query.php | 2 +- src/Database/Adapter.php | 2 +- src/Database/Database.php | 28 ++++++++++++++-------------- tests/e2e/Adapter/Base.php | 6 +++--- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/bin/tasks/index.php b/bin/tasks/index.php index e44c0dd56..c1505cc26 100644 --- a/bin/tasks/index.php +++ b/bin/tasks/index.php @@ -13,8 +13,8 @@ use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; -use Utopia\Mongo\Client; use Utopia\Http\Validator\Text; +use Utopia\Mongo\Client; /** * @Example diff --git a/bin/tasks/load.php b/bin/tasks/load.php index d21734717..e48a4cc55 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -21,9 +21,9 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Mongo\Client; use Utopia\Http\Validator\Numeric; use Utopia\Http\Validator\Text; +use Utopia\Mongo\Client; $authorization = new Authorization(); diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 2aafacdca..28dc0c431 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -14,9 +14,9 @@ use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; use Utopia\Database\Query; -use Utopia\Mongo\Client; use Utopia\Http\Validator\Numeric; use Utopia\Http\Validator\Text; +use Utopia\Mongo\Client; /** * @Example diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index bfa219219..44f7f3ddc 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -4,9 +4,9 @@ use Exception; use Utopia\Database\Exception as DatabaseException; -use Utopia\Database\Validator\Authorization; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Timeout as TimeoutException; +use Utopia\Database\Validator\Authorization; abstract class Adapter { diff --git a/src/Database/Database.php b/src/Database/Database.php index bb481d173..452f0dede 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3691,7 +3691,7 @@ public function updateDocument(string $collection, string $id, Document $documen $this->getDocument($collection->getId(), $id, forUpdate: true) )); - $document = \array_merge($old->getArrayCopy(), $document->getArrayCopy()); + $document = \array_merge($old->getArrayCopy(), $document->getArrayCopy()); $document['$collection'] = $old->getAttribute('$collection'); // Make sure user doesn't switch collection ID if ($this->adapter->getSharedTables()) { $document['$tenant'] = $old->getAttribute('$tenant'); // Make sure user doesn't switch tenant @@ -3796,19 +3796,19 @@ public function updateDocument(string $collection, string $id, Document $documen } } - $updateValidator = new Input(self::PERMISSION_UPDATE, [ + $updateValidator = new Input(self::PERMISSION_UPDATE, [ ...$collection->getUpdate(), ...($documentSecurity ? $old->getUpdate() : []) - ]); + ]); - $readValidator = new Input(self::PERMISSION_READ, [ + $readValidator = new Input(self::PERMISSION_READ, [ ...$collection->getRead(), ...($documentSecurity ? $old->getRead() : []) - ]); + ]); - if (($shouldUpdate && !$this->authorization->isValid($updateValidator)) - || (!$shouldUpdate && !$this->authorization->isValid($readValidator))) { - throw new AuthorizationException($this->authorization->getDescription()); + if (($shouldUpdate && !$this->authorization->isValid($updateValidator)) + || (!$shouldUpdate && !$this->authorization->isValid($readValidator))) { + throw new AuthorizationException($this->authorization->getDescription()); } } @@ -3894,7 +3894,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $document->setAttribute('$updatedAt', empty($updatedAt) || !$this->preserveDates ? $time : $updatedAt); $document = $this->encode($collection, $document); - $old = $this->authorization->skip(fn () => $this->silent( + $old = $this->authorization->skip(fn () => $this->silent( fn () => $this->getDocument( $collection->getId(), $document->getId(), @@ -3906,7 +3906,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $collection->getId() !== self::METADATA && !$this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $old->getUpdate())) ) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($this->authorization->getDescription()); } $validator = new Structure($collection); @@ -4554,12 +4554,12 @@ public function deleteDocument(string $collection, string $id): bool if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ ...$collection->getDelete(), ...($documentSecurity ? $document->getDelete() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index f3e1519e8..62d87d322 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -985,7 +985,7 @@ public function testQueryTimeout(): void $this->assertEquals(true, static::getDatabase()->createAttribute('global-timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); for ($i = 0 ; $i <= 20 ; $i++) { - $this->getDatabase()->createDocument('global-timeouts', new Document([ + $this->getDatabase()->createDocument('global-timeouts', new Document([ 'longtext' => file_get_contents(__DIR__ . '/../../resources/longtext.txt'), '$permissions' => [ Permission::read(Role::any()), @@ -995,10 +995,10 @@ public function testQueryTimeout(): void ])); } - static::getDatabase()->setTimeout(1); + static::getDatabase()->setTimeout(1); try { - $this->getDatabase()->find('global-timeouts', [ + $this->getDatabase()->find('global-timeouts', [ Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); From bfd1168e5bf5aae6d7aca07e65dc524049cac9b9 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:52:15 -0400 Subject: [PATCH 036/103] chore: Updating composer.lock --- composer.lock | 170 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 137 insertions(+), 33 deletions(-) diff --git a/composer.lock b/composer.lock index b98610e74..483bb0099 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "8a6537ec5c4f47cd0b6c34e9ceda042b", + "content-hash": "a5ffc9e423ebf50ba55260295fb404fa", "packages": [ { "name": "jean85/pretty-package-versions", @@ -264,28 +264,80 @@ }, "time": "2024-06-25T20:36:35+00:00" }, + { + "name": "utopia-php/di", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/di.git", + "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/di/zipball/22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "laravel/pint": "^1.2", + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^9.5.25", + "swoole/ide-helper": "4.8.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\": "src/", + "Tests\\E2E\\": "tests/e2e" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A simple and lite library for managing dependency injections", + "keywords": [ + "framework", + "http", + "php", + "upf" + ], + "support": { + "issues": "https://github.com/utopia-php/di/issues", + "source": "https://github.com/utopia-php/di/tree/0.1.0" + }, + "time": "2024-08-08T14:35:19+00:00" + }, { "name": "utopia-php/framework", - "version": "0.33.8", + "version": "1.0.0-RC2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "a7f577540a25cb90896fef2b64767bf8d700f3c5" + "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/a7f577540a25cb90896fef2b64767bf8d700f3c5", - "reference": "a7f577540a25cb90896fef2b64767bf8d700f3c5", + "url": "https://api.github.com/repos/utopia-php/http/zipball/d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", + "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", "shasum": "" }, "require": { - "php": ">=8.0" + "ext-swoole": "*", + "php": ">=8.0", + "utopia-php/servers": "0.1.* " }, "require-dev": { + "ext-xdebug": "*", "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25" + "phpunit/phpunit": "^9.5.25", + "swoole/ide-helper": "4.8.3" }, "type": "library", "autoload": { @@ -297,17 +349,18 @@ "license": [ "MIT" ], - "description": "A simple, light and advanced PHP framework", + "description": "A simple, light and advanced PHP HTTP framework", "keywords": [ "framework", + "http", "php", "upf" ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/0.33.8" + "source": "https://github.com/utopia-php/http/tree/1.0.0-RC2" }, - "time": "2024-08-15T14:10:09+00:00" + "time": "2024-08-08T14:46:41+00:00" }, { "name": "utopia-php/mongo", @@ -368,6 +421,59 @@ "source": "https://github.com/utopia-php/mongo/tree/0.3.1" }, "time": "2023-09-01T17:25:28+00:00" + }, + { + "name": "utopia-php/servers", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/servers.git", + "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/servers/zipball/7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", + "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", + "shasum": "" + }, + "require": { + "php": ">=8.0", + "utopia-php/di": "0.1.*" + }, + "require-dev": { + "laravel/pint": "^0.2.3", + "phpstan/phpstan": "^1.8", + "phpunit/phpunit": "^9.5.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\Servers\\": "src/Servers" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Team Appwrite", + "email": "team@appwrite.io" + } + ], + "description": "A base library for building Utopia style servers.", + "keywords": [ + "framework", + "php", + "servers", + "upf", + "utopia" + ], + "support": { + "issues": "https://github.com/utopia-php/servers/issues", + "source": "https://github.com/utopia-php/servers/tree/0.1.0" + }, + "time": "2024-08-08T14:31:39+00:00" } ], "packages-dev": [ @@ -506,16 +612,16 @@ }, { "name": "laravel/pint", - "version": "v1.17.2", + "version": "v1.17.3", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "e8a88130a25e3f9d4d5785e6a1afca98268ab110" + "reference": "9d77be916e145864f10788bb94531d03e1f7b482" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/e8a88130a25e3f9d4d5785e6a1afca98268ab110", - "reference": "e8a88130a25e3f9d4d5785e6a1afca98268ab110", + "url": "https://api.github.com/repos/laravel/pint/zipball/9d77be916e145864f10788bb94531d03e1f7b482", + "reference": "9d77be916e145864f10788bb94531d03e1f7b482", "shasum": "" }, "require": { @@ -526,13 +632,13 @@ "php": "^8.1.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.61.1", - "illuminate/view": "^10.48.18", + "friendsofphp/php-cs-fixer": "^3.64.0", + "illuminate/view": "^10.48.20", "larastan/larastan": "^2.9.8", "laravel-zero/framework": "^10.4.0", "mockery/mockery": "^1.6.12", "nunomaduro/termwind": "^1.15.1", - "pestphp/pest": "^2.35.0" + "pestphp/pest": "^2.35.1" }, "bin": [ "builds/pint" @@ -568,7 +674,7 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2024-08-06T15:11:54+00:00" + "time": "2024-09-03T15:00:28+00:00" }, { "name": "myclabs/deep-copy", @@ -2531,25 +2637,29 @@ }, { "name": "utopia-php/cli", - "version": "0.14.0", + "version": "1.0.0-RC1", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" + "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", - "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", + "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/framework": "0.*.*" + "utopia-php/di": "0.1.*", + "utopia-php/framework": "1.0.*" }, "require-dev": { + "laravel/pint": "1.2.*", + "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6" + "squizlabs/php_codesniffer": "^3.6", + "swoole/ide-helper": "4.8.8" }, "type": "library", "autoload": { @@ -2561,12 +2671,6 @@ "license": [ "MIT" ], - "authors": [ - { - "name": "Eldad Fux", - "email": "eldad@appwrite.io" - } - ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2578,13 +2682,13 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.14.0" + "source": "https://github.com/utopia-php/cli/tree/1.0.0-RC1" }, - "time": "2022-10-09T10:19:07+00:00" + "time": "2024-08-09T17:35:04+00:00" } ], "aliases": [], - "minimum-stability": "stable", + "minimum-stability": "RC", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, From d70eb76c7cf5ee596752209a4d57e4d08fe8a986 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:58:16 -0400 Subject: [PATCH 037/103] chore: format --- src/Database/Adapter/MariaDB.php | 20 +++++------ src/Database/Adapter/Mongo.php | 7 ++-- src/Database/Adapter/Postgres.php | 14 ++++---- src/Database/Adapter/SQL.php | 6 ++-- src/Database/Adapter/SQLite.php | 12 +++---- src/Database/Database.php | 8 ++--- src/Database/Exception.php | 2 +- src/Database/Query.php | 4 +-- src/Database/Validator/Authorization.php | 2 +- src/Database/Validator/Datetime.php | 18 +++++----- src/Database/Validator/Index.php | 14 ++++---- src/Database/Validator/Queries.php | 4 +-- src/Database/Validator/Query/Filter.php | 18 +++++----- src/Database/Validator/Structure.php | 2 +- tests/e2e/Adapter/Base.php | 42 ++++++++++++------------ tests/unit/Validator/DateTimeTest.php | 2 +- 16 files changed, 87 insertions(+), 88 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index b1f11c919..fca156055 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -686,7 +686,7 @@ public function createIndex(string $collection, string $id, string $type, array $attributes[$i] = "`{$attr}`{$length} {$order}"; - if(!empty($collectionAttribute['array']) && $this->castIndexArray()) { + if (!empty($collectionAttribute['array']) && $this->castIndexArray()) { $attributes[$i] = '(CAST(' . $attr . ' AS char(' . Database::ARRAY_INDEX_LENGTH . ') ARRAY))'; } } @@ -870,7 +870,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions->execute(); } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -918,7 +918,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_createdAt'] = $document->getCreatedAt(); $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if(!empty($document->getInternalId())) { + if (!empty($document->getInternalId())) { $attributes['_id'] = $document->getInternalId(); } @@ -998,7 +998,7 @@ public function createDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1244,7 +1244,7 @@ public function updateDocument(string $collection, Document $document): Document } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1501,7 +1501,7 @@ public function updateDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1732,7 +1732,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1860,7 +1860,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2077,7 +2077,7 @@ protected function getSQLCondition(Query $query): string return "`table_main`.{$attribute} {$this->getSQLOperator($query->getMethod())}"; case Query::TYPE_CONTAINS: - if($this->getSupportForJSONOverlaps() && $query->onArray()) { + if ($this->getSupportForJSONOverlaps() && $query->onArray()) { return "JSON_OVERLAPS(`table_main`.{$attribute}, :{$placeholder}_0)"; } @@ -2103,7 +2103,7 @@ protected function getSQLCondition(Query $query): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSON'; } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index f49e3a4a6..693c18965 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -3,7 +3,6 @@ namespace Utopia\Database\Adapter; use Exception; - use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -291,7 +290,7 @@ public function getSizeOfCollection(string $collection): int } else { throw new DatabaseException('No size found'); } - } catch(Exception $e) { + } catch (Exception $e) { throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); } } @@ -1368,7 +1367,7 @@ protected function buildFilters(array $queries, string $separator = '$and'): arr $queries = Query::groupByType($queries)['filters']; foreach ($queries as $query) { /* @var $query Query */ - if($query->isNested()) { + if ($query->isNested()) { $operator = $this->getQueryOperator($query->getMethod()); $filters[$separator][] = $this->buildFilters($query->getValues(), $operator); } else { @@ -1422,7 +1421,7 @@ protected function buildFilter(Query $query): array } elseif ($operator == '$ne' && \is_array($value)) { $filter[$attribute]['$nin'] = $value; } elseif ($operator == '$in') { - if($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { + if ($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { $filter[$attribute]['$regex'] = new Regex(".*{$this->escapeWildcards($value)}.*", 'i'); } else { $filter[$attribute]['$in'] = $query->getValues(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 92d764e9a..8d2bc1560 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -840,7 +840,7 @@ public function createDocument(string $collection, Document $document): Document $queryPermissions = $this->trigger(Database::EVENT_PERMISSIONS_CREATE, $queryPermissions); $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($sqlTenant) { + if ($sqlTenant) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -899,7 +899,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1229,7 +1229,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1421,7 +1421,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); } - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(':_tenant', $this->tenant); } @@ -1653,7 +1653,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1781,7 +1781,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2021,7 +2021,7 @@ protected function getFulltextValue(string $value): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSONB'; } diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index dd6d822c6..e73515a57 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -818,14 +818,14 @@ protected function bindConditionValue(mixed $stmt, Query $query): void return; } - if($query->isNested()) { + if ($query->isNested()) { foreach ($query->getValues() as $value) { $this->bindConditionValue($stmt, $value); } return; } - if($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { + if ($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { $placeholder = $this->getSQLPlaceholder($query) . '_0'; $stmt->bindValue($placeholder, json_encode($query->getValues()), PDO::PARAM_STR); return; @@ -1071,7 +1071,7 @@ public function getSQLConditions(array $queries = [], string $separator = 'AND') continue; } - if($query->isNested()) { + if ($query->isNested()) { $conditions[] = $this->getSQLConditions($query->getValues(), $query->getMethod()); } else { $conditions[] = $this->getSQLCondition($query); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 9f7441f6b..193f9b19c 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -448,7 +448,7 @@ public function createDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -522,7 +522,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -567,7 +567,7 @@ public function updateDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -701,7 +701,7 @@ public function updateDocument(string $collection, Document $document): Document $stmtAddPermissions = $this->getPDO()->prepare($sql); $stmtAddPermissions->bindValue(":_uid", $document->getId()); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(":_tenant", $this->tenant); } @@ -814,7 +814,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1012,7 +1012,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); } - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(':_tenant', $this->tenant); } diff --git a/src/Database/Database.php b/src/Database/Database.php index 452f0dede..d98347969 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4359,7 +4359,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4452,7 +4452,7 @@ public function decreaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4548,7 +4548,7 @@ public function deleteDocument(string $collection, string $id): bool $this->getDocument($collection->getId(), $id, forUpdate: true) )); - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -5136,7 +5136,7 @@ public function find(string $collection, array $queries = []): array $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); - foreach ($results as &$node) { + foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { $node = $this->silent(fn () => $this->populateDocumentRelationships($collection, $node, $nestedSelections)); } diff --git a/src/Database/Exception.php b/src/Database/Exception.php index 64ad3c997..94099c6ae 100644 --- a/src/Database/Exception.php +++ b/src/Database/Exception.php @@ -8,7 +8,7 @@ class Exception extends \Exception { public function __construct(string $message, int|string $code = 0, Throwable $previous = null) { - if(\is_string($code)) { + if (\is_string($code)) { if (\is_numeric($code)) { $code = (int) $code; } else { diff --git a/src/Database/Query.php b/src/Database/Query.php index 6af553415..aab17c195 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -297,7 +297,7 @@ public function toArray(): array { $array = ['method' => $this->method]; - if(!empty($this->attribute)) { + if (!empty($this->attribute)) { $array['attribute'] = $this->attribute; } @@ -690,7 +690,7 @@ public static function groupByType(array $queries): array */ public function isNested(): bool { - if(in_array($this->getMethod(), self::LOGICAL_TYPES)) { + if (in_array($this->getMethod(), self::LOGICAL_TYPES)) { return true; } diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index b6acbd291..22d0ebc5c 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -51,7 +51,7 @@ public function getDescription(): string */ public function isValid(mixed $input): bool // any, CREATE { - if(!($input instanceof Input)) { + if (!($input instanceof Input)) { $this->message = 'Invalid input provided'; return false; } diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index fe04851f5..1d8c9dfd2 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -33,7 +33,7 @@ class Datetime extends Validator */ public function __construct(bool $requireDateInFuture = false, string $precision = self::PRECISION_ANY, int $offset = 0) { - if($offset < 0) { + if ($offset < 0) { throw new \Exception('Offset must be a positive number.'); } @@ -50,13 +50,13 @@ public function getDescription(): string { $message = 'Value must be valid date'; - if($this->offset > 0) { + if ($this->offset > 0) { $message .= " at least " . $this->offset . " seconds in future"; - } elseif($this->requireDateInFuture) { + } elseif ($this->requireDateInFuture) { $message .= " in future"; } - if($this->precision !== self::PRECISION_ANY) { + if ($this->precision !== self::PRECISION_ANY) { $message .= " with " . $this->precision . " precision"; } @@ -84,9 +84,9 @@ public function isValid($value): bool return false; } - if($this->offset !== 0) { + if ($this->offset !== 0) { $diff = $date->getTimestamp() - $now->getTimestamp(); - if($diff <= $this->offset) { + if ($diff <= $this->offset) { return false; } } @@ -109,12 +109,12 @@ public function isValid($value): bool break; } - foreach($denyConstants as $constant) { - if(\intval($date->format($constant)) !== 0) { + foreach ($denyConstants as $constant) { + if (\intval($date->format($constant)) !== 0) { return false; } } - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index 08e269ae5..d7f1beba4 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -126,30 +126,30 @@ public function checkArrayIndex(Document $index): bool foreach ($attributes as $attributePosition => $attributeName) { $attribute = $this->attributes[\strtolower($attributeName)] ?? new Document(); - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { // Database::INDEX_UNIQUE Is not allowed! since mariaDB VS MySQL makes the unique Different on values - if($index->getAttribute('type') != Database::INDEX_KEY) { + if ($index->getAttribute('type') != Database::INDEX_KEY) { $this->message = '"' . ucfirst($index->getAttribute('type')) . '" index is forbidden on array attributes'; return false; } - if(empty($lengths[$attributePosition])) { + if (empty($lengths[$attributePosition])) { $this->message = 'Index length for array not specified'; return false; } $arrayAttributes[] = $attribute->getAttribute('key', ''); - if(count($arrayAttributes) > 1) { + if (count($arrayAttributes) > 1) { $this->message = 'An index may only contain one array attribute'; return false; } $direction = $orders[$attributePosition] ?? ''; - if(!empty($direction)) { + if (!empty($direction)) { $this->message = 'Invalid index order "' . $direction . '" on array attribute "'. $attribute->getAttribute('key', '') .'"'; return false; } - } elseif($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { + } elseif ($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { $this->message = 'Cannot set a length on "'. $attribute->getAttribute('type') . '" attributes'; return false; } @@ -188,7 +188,7 @@ public function checkIndexLength(Document $index): bool break; } - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { $attributeSize = Database::ARRAY_INDEX_LENGTH; $indexLength = Database::ARRAY_INDEX_LENGTH; } diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index 608ac73fc..cc5ae3f5a 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -71,8 +71,8 @@ public function isValid($value): bool } } - if($query->isNested()) { - if(!self::isValid($query->getValues())) { + if ($query->isNested()) { + if (!self::isValid($query->getValues())) { return false; } } diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index f63e0cab3..697c87ee9 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -131,29 +131,29 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s } } - if($attributeSchema['type'] === 'relationship') { + if ($attributeSchema['type'] === 'relationship') { /** * We can not disable relationship query since we have logic that use it, * so instead we validate against the relation type */ $options = $attributeSchema['options']; - if($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { + if ($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_MANY) { + if ($options['relationType'] === Database::RELATION_MANY_TO_MANY) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } @@ -161,7 +161,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s $array = $attributeSchema['array'] ?? false; - if( + if ( !$array && $method === Query::TYPE_CONTAINS && $attributeSchema['type'] !== Database::VAR_STRING @@ -170,7 +170,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s return false; } - if( + if ( $array && !in_array($method, [Query::TYPE_CONTAINS, Query::TYPE_IS_NULL, Query::TYPE_IS_NOT_NULL]) ) { @@ -253,12 +253,12 @@ public function isValid($value): bool case Query::TYPE_AND: $filters = Query::groupByType($value->getValues())['filters']; - if(count($value->getValues()) !== count($filters)) { + if (count($value->getValues()) !== count($filters)) { $this->message = \ucfirst($method) . ' queries can only contain filter queries'; return false; } - if(count($filters) < 2) { + if (count($filters) < 2) { $this->message = \ucfirst($method) . ' queries require at least two queries'; return false; } diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index b6e00b528..4820009f7 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -257,7 +257,7 @@ public function isValid($document): bool continue; } - if($type === Database::VAR_RELATIONSHIP) { + if ($type === Database::VAR_RELATIONSHIP) { continue; } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 62d87d322..31068c30c 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1002,7 +1002,7 @@ public function testQueryTimeout(): void Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); - } catch(TimeoutException $ex) { + } catch (TimeoutException $ex) { static::getDatabase()->clearTimeout(); static::getDatabase()->deleteCollection('global-timeouts'); } @@ -1851,7 +1851,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertStringContainsString('Invalid document structure: Attribute "float_unsigned" has invalid type. Value must be a valid range between 0 and', $e->getMessage()); } @@ -1870,7 +1870,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertEquals('Invalid document structure: Attribute "bigint_unsigned" has invalid type. Value must be a valid range between 0 and 9,223,372,036,854,775,807', $e->getMessage()); } @@ -2261,7 +2261,7 @@ public function testListDocumentSearch(): void public function testEmptyTenant(): void { - if(static::getDatabase()->getAdapter()->getSharedTables()) { + if (static::getDatabase()->getAdapter()->getSharedTables()) { $this->expectNotToPerformAssertions(); return; } @@ -2440,7 +2440,7 @@ public function testUpdateDocumentConflict(Document $document): void return $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof ConflictException); $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); } @@ -2581,7 +2581,7 @@ public function testArrayAttribute(): void try { $database->createDocument($collection, new Document([])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Missing required attribute "booleans"', $e->getMessage()); } @@ -2601,7 +2601,7 @@ public function testArrayAttribute(): void 'short' => ['More than 5 size'], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "short[\'0\']" has invalid type. Value must be a valid string and no longer than 5 chars', $e->getMessage()); } @@ -2610,7 +2610,7 @@ public function testArrayAttribute(): void 'names' => ['Joe', 100], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "names[\'1\']" has invalid type. Value must be a valid string and no longer than 255 chars', $e->getMessage()); } @@ -2619,7 +2619,7 @@ public function testArrayAttribute(): void 'age' => 1.5, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid integer', $e->getMessage()); } @@ -2628,7 +2628,7 @@ public function testArrayAttribute(): void 'age' => -100, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid range between 0 and 2,147,483,647', $e->getMessage()); } @@ -2657,7 +2657,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->assertEquals('"Fulltext" index is forbidden on array attributes', $e->getMessage()); } else { @@ -2668,7 +2668,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_KEY, ['numbers', 'names'], [100,100]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('An index may only contain one array attribute', $e->getMessage()); } @@ -2689,7 +2689,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx_numbers', Database::INDEX_KEY, ['tv_show', 'numbers'], [], []); // [700, 255] $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Index length is longer than the maximum: 768', $e->getMessage()); } } @@ -2700,7 +2700,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx4', Database::INDEX_KEY, ['age', 'names'], [10, 255], []); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Cannot set a length on "integer" attributes', $e->getMessage()); } @@ -2713,7 +2713,7 @@ public function testArrayAttribute(): void Query::equal('names', ['Joe']), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query equal on attribute "names" because it is an array.', $e->getMessage()); } @@ -2722,7 +2722,7 @@ public function testArrayAttribute(): void Query::contains('age', [10]) ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "age" because it is not an array or string.', $e->getMessage()); } @@ -3158,7 +3158,7 @@ public function testFindContains(): void Query::contains('price', [10.5]), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "price" because it is not an array or string.', $e->getMessage()); $this->assertTrue($e instanceof DatabaseException); } @@ -4065,7 +4065,7 @@ public function testOrSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: Or queries require at least two queries', $e->getMessage()); } } @@ -4125,7 +4125,7 @@ public function testAndSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: And queries require at least two queries', $e->getMessage()); } } @@ -4971,7 +4971,7 @@ public function testStructureValidationAfterRelationsAttribute(): void 'name' => 'Frozen', // Unknown attribute 'name' after relation attribute ])); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(StructureException::class, $e); } } @@ -5046,7 +5046,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void try { $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); diff --git a/tests/unit/Validator/DateTimeTest.php b/tests/unit/Validator/DateTimeTest.php index b9157e8b8..d8ababb6f 100644 --- a/tests/unit/Validator/DateTimeTest.php +++ b/tests/unit/Validator/DateTimeTest.php @@ -128,7 +128,7 @@ public function testOffset(): void $threwException = false; try { $dateValidator = new DatetimeValidator(offset: -60); - } catch(\Exception $e) { + } catch (\Exception $e) { $threwException = true; } $this->assertTrue($threwException); From e2bf86abdccf9fbfcebdf8f750dbe5663100fe98 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Thu, 5 Sep 2024 11:51:58 -0400 Subject: [PATCH 038/103] chore: Updating composer.lock --- composer.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.lock b/composer.lock index 483bb0099..763c8d428 100644 --- a/composer.lock +++ b/composer.lock @@ -314,22 +314,22 @@ }, { "name": "utopia-php/framework", - "version": "1.0.0-RC2", + "version": "1.0.0", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7" + "reference": "cc880ec41f7f163d4f9956fec26cc6be51b412cf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", - "reference": "d1e9674dbf33bed03fa53854ec1f2c6e074cf4d7", + "url": "https://api.github.com/repos/utopia-php/http/zipball/cc880ec41f7f163d4f9956fec26cc6be51b412cf", + "reference": "cc880ec41f7f163d4f9956fec26cc6be51b412cf", "shasum": "" }, "require": { "ext-swoole": "*", "php": ">=8.0", - "utopia-php/servers": "0.1.* " + "utopia-php/servers": "0.1.*" }, "require-dev": { "ext-xdebug": "*", @@ -358,9 +358,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/1.0.0-RC2" + "source": "https://github.com/utopia-php/http/tree/1.0.0" }, - "time": "2024-08-08T14:46:41+00:00" + "time": "2024-09-05T15:38:08+00:00" }, { "name": "utopia-php/mongo", From bb2a6870105b39ab246bd30a42e2141d1917ee49 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Thu, 5 Sep 2024 11:55:23 -0400 Subject: [PATCH 039/103] chore: updating packages --- composer.json | 4 ++-- composer.lock | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/composer.json b/composer.json index 05a0b2f8e..f8f5bf8e9 100755 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "type": "library", "keywords": ["php","framework", "upf", "utopia", "database"], "license": "MIT", - "minimum-stability": "RC", + "minimum-stability": "stable", "autoload": { "psr-4": {"Utopia\\Database\\": "src/Database"} }, @@ -45,7 +45,7 @@ "phpunit/phpunit": "9.6.*", "pcov/clobber": "2.0.*", "swoole/ide-helper": "5.1.3", - "utopia-php/cli": "1.0.*", + "utopia-php/cli": "0.19.*", "laravel/pint": "1.17.*", "phpstan/phpstan": "1.11.*", "rregeer/phpunit-coverage-check": "0.3.*" diff --git a/composer.lock b/composer.lock index 763c8d428..b21e9af33 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "a5ffc9e423ebf50ba55260295fb404fa", + "content-hash": "62684826df21956b2d48dc2c42cc3e07", "packages": [ { "name": "jean85/pretty-package-versions", @@ -2637,16 +2637,16 @@ }, { "name": "utopia-php/cli", - "version": "1.0.0-RC1", + "version": "0.19.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80" + "reference": "f8af1d6087f498bc1f0191750a118d357ded9948" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", - "reference": "7664161dcdb9b76a3ece0ae2f36a9aca1e548e80", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/f8af1d6087f498bc1f0191750a118d357ded9948", + "reference": "f8af1d6087f498bc1f0191750a118d357ded9948", "shasum": "" }, "require": { @@ -2682,13 +2682,13 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/1.0.0-RC1" + "source": "https://github.com/utopia-php/cli/tree/0.19.0" }, - "time": "2024-08-09T17:35:04+00:00" + "time": "2024-09-05T15:46:56+00:00" } ], "aliases": [], - "minimum-stability": "RC", + "minimum-stability": "stable", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, From 170f8d50d0d5896623c3a6a09016a88a4a457aaf Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 10 Sep 2024 10:27:13 +0200 Subject: [PATCH 040/103] Initial Push for Batch Deletes --- src/Database/Adapter.php | 10 +++ src/Database/Adapter/MariaDB.php | 55 ++++++++++++ src/Database/Adapter/Mongo.php | 13 +++ src/Database/Adapter/Postgres.php | 55 ++++++++++++ src/Database/Database.php | 78 ++++++++++++++++ tests/e2e/Adapter/Base.php | 145 ++++++++++++++++++++++++++++++ 6 files changed, 356 insertions(+) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 4c2aa326a..bf010faaa 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -587,6 +587,16 @@ abstract public function updateDocuments(string $collection, array $documents, i */ abstract public function deleteDocument(string $collection, string $id): bool; + /** + * Delete Documents + * + * @param string $collection + * @param array<\Utopia\Database\Query> $queries + * + * @return bool + */ + abstract public function deleteDocuments(string $collection, array $queries): bool; + /** * Find Documents * diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index aaaa260fe..6256fec37 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1635,6 +1635,61 @@ public function deleteDocument(string $collection, string $id): bool return $deleted; } + /** + * Delete Documents + * + * @param string $collection + * @param array<\Utopia\Database\Query> $queries + * + * @return bool + */ + public function deleteDocuments(string $collection, array $queries): bool + { + $name = $this->filter($collection); + $where = []; + + $queries = array_map(fn ($query) => clone $query, $queries); + + $conditions = $this->getSQLConditions($queries); + if(!empty($conditions)) { + $where[] = $conditions; + } + + if ($this->sharedTables) { + $where[] = "table_main._tenant = :_tenant"; + } + + $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + + $selections = $this->getAttributeSelections($queries); + + $sql = " + USE {$this->database}; + DELETE {$this->getAttributeProjection($selections, 'table_main')} + FROM {$this->getSQLTable($name)} as table_main + {$sqlWhere}; + "; + + $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + + $stmt = $this->getPDO()->prepare($sql); + + foreach ($queries as $query) { + $this->bindConditionValue($stmt, $query); + } + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } + + try { + $stmt->execute(); + } catch (PDOException $e) { + $this->processException($e); + } + + return true; + } + /** * Find Documents * diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index feb1d9a15..62b411ca3 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -909,6 +909,19 @@ public function deleteDocument(string $collection, string $id): bool return (!!$result); } + /** + * Delete Documents + * + * @param string $collection + * @param array<\Utopia\Database\Query> $queries + * + * @return bool + */ + public function deleteDocuments(string $collection, array $queries): bool + { + throw new \Exception('Not Implemented'); + } + /** * Update Attribute. * @param string $collection diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8c25731d6..7ea145f85 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1558,6 +1558,61 @@ public function deleteDocument(string $collection, string $id): bool return $deleted; } + + /** + * Delete Documents + * + * @param string $collection + * @param array<\Utopia\Database\Query> $queries + * + * @return bool + */ + public function deleteDocuments(string $collection, array $queries): bool + { + $name = $this->filter($collection); + $where = []; + + $queries = array_map(fn ($query) => clone $query, $queries); + + $conditions = $this->getSQLConditions($queries); + if(!empty($conditions)) { + $where[] = $conditions; + } + + if ($this->sharedTables) { + $where[] = "table_main._tenant = :_tenant"; + } + + $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + + $selections = $this->getAttributeSelections($queries); + + $sql = " + SELECT {$this->getAttributeProjection($selections, 'table_main')} + FROM {$this->getSQLTable($name)} as table_main + {$sqlWhere} + "; + + $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + + $stmt = $this->getPDO()->prepare($sql); + + foreach ($queries as $query) { + $this->bindConditionValue($stmt, $query); + } + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } + + try { + $stmt->execute(); + } catch (PDOException $e) { + $this->processException($e); + } + + return true; + } + /** * Find Documents * diff --git a/src/Database/Database.php b/src/Database/Database.php index 437f18881..58b9d0000 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4944,6 +4944,84 @@ private function deleteCascade(Document $collection, Document $relatedCollection } } + /** + * Delete Documents + * + * Deletes all documents which match the given query, will respect the relationship's onDelete optin. + * + * @param string $collection + * @param array $queries + * + * @return bool + * + * @throws AuthorizationException + * @throws DatabaseException + * @throws RestrictedException + */ + public function deleteDocuments(string $collection, array $queries = []): bool + { + if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { + throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); + } + + $collection = $this->silent(fn () => $this->getCollection($collection)); + + $deleted = $this->withTransaction(function () use ($collection, $queries) { + $lastDocument = null; + while (true) { + $affectedDocuments = $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit(100), + ] : [ + Query::limit(100), + Query::cursorAfter($lastDocument), + ], + $queries, + )); + + if (empty($affectedDocuments)) { + break; + } + + foreach ($affectedDocuments as $document) { + $validator = new Authorization(self::PERMISSION_DELETE); + + if ($collection->getId() !== self::METADATA) { + $documentSecurity = $collection->getAttribute('documentSecurity', false); + if (!$validator->isValid([ + ...$collection->getDelete(), + ...($documentSecurity ? $document->getDelete() : []) + ])) { + throw new AuthorizationException($validator->getDescription()); + } + } + + // Delete Relationships + if ($this->resolveRelationships) { + $document = $this->silent(fn () => $this->deleteDocumentRelationships($collection, $document)); + } + + // Fire events + $this->trigger(self::EVENT_DOCUMENT_DELETE, $document); + + $this->purgeRelatedDocuments($collection, $document->getId()); + $this->purgeCachedDocument($collection->getId(), $document->getId()); + } + + if (count($affectedDocuments) < 100) { + break; + } else { + $lastDocument = end($affectedDocuments); + } + } + + // Mass delete using adapter with query + return $this->adapter->deleteDocuments($collection->getId(), $queries); + }); + + return $deleted; + } + /** * Cleans the all the collection's documents from the cache * And the all related cached documents. diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 72587d44a..ff2998633 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15608,4 +15608,149 @@ public function testEvents(): void $database->delete('hellodb'); }); } + + public function propegateBulkDocuments(bool $documentSecurity = false): void + { + for ($i = 0; $i < 10; $i++) { + var_dump(new Document( + array_merge([ + '$id' => 'doc' . $i, + 'text' => 'value' . $i, + 'integer' => $i + ], $documentSecurity ? [ + '$permissions' => [ + Permission::delete(Role::any()), + Permission::create(Role::any()), + Permission::read(Role::any()), + ], + ] : []) + )); + + static::getDatabase()->createDocument('bulk_delete', new Document( + array_merge([ + '$id' => 'doc' . $i, + 'text' => 'value' . $i, + 'integer' => $i + ], $documentSecurity ? [ + '$permissions' => [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ], + ] : []) + )); + } + } + + public function testDeleteBulkDocuments(): void + { + static::getDatabase()->createCollection( + 'bulk_delete', + attributes: [ + new Document([ + '$id' => 'text', + 'type' => Database::VAR_STRING, + 'size' => 100, + 'required' => true, + ]), + new Document([ + '$id' => 'integer', + 'type' => Database::VAR_INTEGER, + 'size' => 10, + 'required' => true, + ]) + ], + documentSecurity: false, + permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::delete(Role::any()) + ] + ); + + $this->propegateBulkDocuments(); + + $docs = static::getDatabase()->find('bulk_delete'); + $this->assertCount(10, $docs); + + // TEST: Bulk Delete All Documents + static::getDatabase()->deleteDocuments('bulk_delete'); + + $docs = static::getDatabase()->find('bulk_delete'); + $this->assertCount(0, $docs); + + // TEST: Bulk delete documents with queries. + $this->propegateBulkDocuments(); + + static::getDatabase()->deleteDocuments('bulk_delete', [ + Query::greaterThanEqual('integer', 5) + ]); + + $docs = static::getDatabase()->find('bulk_delete'); + $this->assertCount(5, $docs); + + // TEST (FAIL): Bulk delete all documents with invalid collection permission + static::getDatabase()->updateCollection('bulk_delete', [], false); + try { + static::getDatabase()->deleteDocuments('bulk_delete'); + $this->fail('Bulk deleted documents with invalid collection permission'); + } catch (\Utopia\Database\Exception\Authorization) { + } + + static::getDatabase()->updateCollection('bulk_delete', [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::delete(Role::any()) + ], false); + static::getDatabase()->deleteDocuments('bulk_delete'); + $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); + + // TEST (FAIL): Bulk delete all documents with invalid document permissions + // Authorization::setRole(Role::any()->toString()); + static::getDatabase()->updateCollection('bulk_delete', [ + Permission::create(Role::any()), + ], true); + $this->propegateBulkDocuments(true); + + try { + static::getDatabase()->deleteDocuments('bulk_delete'); + $this->fail('Bulk deleted documents with invalid document permission'); + } catch (\Utopia\Database\Exception\Authorization) { + } + + static::getDatabase()->updateCollection('bulk_delete', [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::delete(Role::any()) + ], false); + static::getDatabase()->deleteDocuments('bulk_delete'); + $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); + + // Teardown + static::getDatabase()->deleteCollection('bulk_delete'); + } + + + public function testDeleteBulkDocumentsRelationships(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + $this->expectNotToPerformAssertions(); + return; + } + + static::getDatabase()->createCollection('bulk_delete_r_1'); + static::getDatabase()->createCollection('bulk_delete_r_2'); + + // ONE_TO_ONE + static::getDatabase()->createRelationship( + collection: 'bulk_delete_r_1', + relatedCollection: 'bulk_delete_r_2', + type: Database::RELATION_ONE_TO_ONE, + ); + + // Restrict + + // NULL + + // Cascade + } } From 20a046759337b9d7af1537a020dc5a6a9fb14a44 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 10 Sep 2024 11:55:33 +0200 Subject: [PATCH 041/103] Fix non-quoted newKey in MariaDB and add newKey filtering for postgres --- composer.lock | 38 +++++++++++++++---------------- src/Database/Adapter/MariaDB.php | 2 +- src/Database/Adapter/Postgres.php | 1 + tests/e2e/Adapter/Base.php | 12 ++++++++++ 4 files changed, 33 insertions(+), 20 deletions(-) diff --git a/composer.lock b/composer.lock index b21e9af33..6ec1690e1 100644 --- a/composer.lock +++ b/composer.lock @@ -136,20 +136,20 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.30.0", + "version": "v1.31.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "77fa7995ac1b21ab60769b7323d600a991a90433" + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/77fa7995ac1b21ab60769b7323d600a991a90433", - "reference": "77fa7995ac1b21ab60769b7323d600a991a90433", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", "shasum": "" }, "require": { - "php": ">=7.1" + "php": ">=7.2" }, "type": "library", "extra": { @@ -196,7 +196,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.30.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" }, "funding": [ { @@ -212,7 +212,7 @@ "type": "tidelift" } ], - "time": "2024-05-31T15:07:36+00:00" + "time": "2024-09-09T11:45:10+00:00" }, { "name": "utopia-php/cache", @@ -314,16 +314,16 @@ }, { "name": "utopia-php/framework", - "version": "1.0.0", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "cc880ec41f7f163d4f9956fec26cc6be51b412cf" + "reference": "fc63ec61c720190a5ea5bb484c615145850951e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/cc880ec41f7f163d4f9956fec26cc6be51b412cf", - "reference": "cc880ec41f7f163d4f9956fec26cc6be51b412cf", + "url": "https://api.github.com/repos/utopia-php/http/zipball/fc63ec61c720190a5ea5bb484c615145850951e6", + "reference": "fc63ec61c720190a5ea5bb484c615145850951e6", "shasum": "" }, "require": { @@ -358,9 +358,9 @@ ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/1.0.0" + "source": "https://github.com/utopia-php/http/tree/1.0.2" }, - "time": "2024-09-05T15:38:08+00:00" + "time": "2024-09-10T09:04:19+00:00" }, { "name": "utopia-php/mongo", @@ -424,16 +424,16 @@ }, { "name": "utopia-php/servers", - "version": "0.1.0", + "version": "0.1.1", "source": { "type": "git", "url": "https://github.com/utopia-php/servers.git", - "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c" + "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/servers/zipball/7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", - "reference": "7d9e4f364fb1ab1889fb89ca96eb9946467cb09c", + "url": "https://api.github.com/repos/utopia-php/servers/zipball/fd5c8d32778f265256c1936372a071b944f5ba8a", + "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a", "shasum": "" }, "require": { @@ -471,9 +471,9 @@ ], "support": { "issues": "https://github.com/utopia-php/servers/issues", - "source": "https://github.com/utopia-php/servers/tree/0.1.0" + "source": "https://github.com/utopia-php/servers/tree/0.1.1" }, - "time": "2024-08-08T14:31:39+00:00" + "time": "2024-09-06T02:25:56+00:00" } ], "packages-dev": [ diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index fca156055..03c0a33e6 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -321,7 +321,7 @@ public function updateAttribute(string $collection, string $id, string $type, in $type = $this->getSQLType($type, $size, $signed, $array); if (!empty($newKey)) { - $sql = "ALTER TABLE {$this->getSQLTable($name)} CHANGE COLUMN `{$id}` {$newKey} {$type};"; + $sql = "ALTER TABLE {$this->getSQLTable($name)} CHANGE COLUMN `{$id}` `{$newKey}` {$type};"; } else { $sql = "ALTER TABLE {$this->getSQLTable($name)} MODIFY `{$id}` {$type};"; } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8d2bc1560..92445569f 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -350,6 +350,7 @@ public function updateAttribute(string $collection, string $id, string $type, in { $name = $this->filter($collection); $id = $this->filter($id); + $newKey = empty($newKey) ? null : $this->filter($newKey); $type = $this->getSQLType($type, $size, $signed, $array); if ($type == 'TIMESTAMP(3)') { diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 31068c30c..088535c60 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -5906,6 +5906,18 @@ public function testUpdateAttributeRename(): void } catch (\Exception $e) { $this->assertInstanceOf(StructureException::class, $e); } + + // Check new key filtering + static::getDatabase()->updateAttribute( + collection: 'rename_test', + id: 'renamed', + newKey: 'renamed-test', + ); + + $doc = static::getDatabase()->getDocument('rename_test', $doc->getId()); + + $this->assertEquals('string', $doc->getAttribute('renamed-test')); + $this->assertArrayNotHasKey('renamed', $doc->getAttributes()); } public function createRandomString(int $length = 10): string From 79e65da983634578b676c7458d5cad879a3dfbbe Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 10 Sep 2024 19:46:46 +0900 Subject: [PATCH 042/103] Update src/Database/Adapter/MariaDB.php Co-authored-by: Jake Barnby --- src/Database/Adapter/MariaDB.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 6256fec37..825ecefdb 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1664,9 +1664,7 @@ public function deleteDocuments(string $collection, array $queries): bool $selections = $this->getAttributeSelections($queries); $sql = " - USE {$this->database}; - DELETE {$this->getAttributeProjection($selections, 'table_main')} - FROM {$this->getSQLTable($name)} as table_main + DELETE FROM {$this->getSQLTable($name)} {$sqlWhere}; "; From b0798700db1d37a4f531b0f005e897f3dfca66a5 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 17 Sep 2024 14:16:55 +0900 Subject: [PATCH 043/103] Address comments, add MongoDB and Postgres Support --- composer.lock | 30 +++++++++++++++--------------- src/Database/Adapter/MariaDB.php | 2 -- src/Database/Adapter/Mongo.php | 27 ++++++++++++++++++++++++++- src/Database/Adapter/Postgres.php | 5 +---- src/Database/Database.php | 10 ++++++---- tests/e2e/Adapter/Base.php | 14 -------------- 6 files changed, 48 insertions(+), 40 deletions(-) diff --git a/composer.lock b/composer.lock index b98610e74..32455f27d 100644 --- a/composer.lock +++ b/composer.lock @@ -136,20 +136,20 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.30.0", + "version": "v1.31.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "77fa7995ac1b21ab60769b7323d600a991a90433" + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/77fa7995ac1b21ab60769b7323d600a991a90433", - "reference": "77fa7995ac1b21ab60769b7323d600a991a90433", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", "shasum": "" }, "require": { - "php": ">=7.1" + "php": ">=7.2" }, "type": "library", "extra": { @@ -196,7 +196,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.30.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" }, "funding": [ { @@ -212,7 +212,7 @@ "type": "tidelift" } ], - "time": "2024-05-31T15:07:36+00:00" + "time": "2024-09-09T11:45:10+00:00" }, { "name": "utopia-php/cache", @@ -506,16 +506,16 @@ }, { "name": "laravel/pint", - "version": "v1.17.2", + "version": "v1.17.3", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "e8a88130a25e3f9d4d5785e6a1afca98268ab110" + "reference": "9d77be916e145864f10788bb94531d03e1f7b482" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/e8a88130a25e3f9d4d5785e6a1afca98268ab110", - "reference": "e8a88130a25e3f9d4d5785e6a1afca98268ab110", + "url": "https://api.github.com/repos/laravel/pint/zipball/9d77be916e145864f10788bb94531d03e1f7b482", + "reference": "9d77be916e145864f10788bb94531d03e1f7b482", "shasum": "" }, "require": { @@ -526,13 +526,13 @@ "php": "^8.1.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.61.1", - "illuminate/view": "^10.48.18", + "friendsofphp/php-cs-fixer": "^3.64.0", + "illuminate/view": "^10.48.20", "larastan/larastan": "^2.9.8", "laravel-zero/framework": "^10.4.0", "mockery/mockery": "^1.6.12", "nunomaduro/termwind": "^1.15.1", - "pestphp/pest": "^2.35.0" + "pestphp/pest": "^2.35.1" }, "bin": [ "builds/pint" @@ -568,7 +568,7 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2024-08-06T15:11:54+00:00" + "time": "2024-09-03T15:00:28+00:00" }, { "name": "myclabs/deep-copy", diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 825ecefdb..7b1537d11 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1661,8 +1661,6 @@ public function deleteDocuments(string $collection, array $queries): bool $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; - $selections = $this->getAttributeSelections($queries); - $sql = " DELETE FROM {$this->getSQLTable($name)} {$sqlWhere}; diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 62b411ca3..41c3c147e 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -919,7 +919,32 @@ public function deleteDocument(string $collection, string $id): bool */ public function deleteDocuments(string $collection, array $queries): bool { - throw new \Exception('Not Implemented'); + $name = $this->getNamespace() . '_' . $this->filter($collection); + $queries = array_map(fn ($query) => clone $query, $queries); + + $filters = $this->buildFilters($queries); + + if ($this->sharedTables) { + $filters['_tenant'] = (string)$this->getTenant(); + } + + $filters = $this->replaceInternalIdsKeys($filters, '$', '_', $this->operators); + $filters = $this->timeFilter($filters); + + $options = []; + + try { + $res = $this->client->delete( + collection: $name, + filters: $filters, + options: $options, + limit: 0 + ); + } catch (MongoException $e) { + $this->processException($e); + } + + return true; } /** diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 7ea145f85..9162ea12e 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1585,11 +1585,8 @@ public function deleteDocuments(string $collection, array $queries): bool $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; - $selections = $this->getAttributeSelections($queries); - $sql = " - SELECT {$this->getAttributeProjection($selections, 'table_main')} - FROM {$this->getSQLTable($name)} as table_main + DELETE FROM {$this->getSQLTable($name)} {$sqlWhere} "; diff --git a/src/Database/Database.php b/src/Database/Database.php index 58b9d0000..944c3bea0 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4951,6 +4951,7 @@ private function deleteCascade(Document $collection, Document $relatedCollection * * @param string $collection * @param array $queries + * @param int $batchSize * * @return bool * @@ -4958,22 +4959,23 @@ private function deleteCascade(Document $collection, Document $relatedCollection * @throws DatabaseException * @throws RestrictedException */ - public function deleteDocuments(string $collection, array $queries = []): bool + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = 100): bool { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } + $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); - $deleted = $this->withTransaction(function () use ($collection, $queries) { + $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize) { $lastDocument = null; while (true) { $affectedDocuments = $this->find($collection->getId(), array_merge( empty($lastDocument) ? [ - Query::limit(100), + Query::limit($batchSize), ] : [ - Query::limit(100), + Query::limit($batchSize), Query::cursorAfter($lastDocument), ], $queries, diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index ff2998633..345605abb 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15612,20 +15612,6 @@ public function testEvents(): void public function propegateBulkDocuments(bool $documentSecurity = false): void { for ($i = 0; $i < 10; $i++) { - var_dump(new Document( - array_merge([ - '$id' => 'doc' . $i, - 'text' => 'value' . $i, - 'integer' => $i - ], $documentSecurity ? [ - '$permissions' => [ - Permission::delete(Role::any()), - Permission::create(Role::any()), - Permission::read(Role::any()), - ], - ] : []) - )); - static::getDatabase()->createDocument('bulk_delete', new Document( array_merge([ '$id' => 'doc' . $i, From a931aab7f429f30a35894065bdcf5badf44e8bb7 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 17 Sep 2024 14:39:37 +0900 Subject: [PATCH 044/103] Make event test the last test --- tests/e2e/Adapter/Base.php | 226 ++++++++++++++++++------------------- 1 file changed, 113 insertions(+), 113 deletions(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 345605abb..903c7284e 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -993,7 +993,7 @@ public function testQueryTimeout(): void Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); - } catch(TimeoutException $ex) { + } catch (TimeoutException $ex) { static::getDatabase()->clearTimeout(); static::getDatabase()->deleteCollection('global-timeouts'); } @@ -1843,7 +1843,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertStringContainsString('Invalid document structure: Attribute "float_unsigned" has invalid type. Value must be a valid range between 0 and', $e->getMessage()); } @@ -1862,7 +1862,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertEquals('Invalid document structure: Attribute "bigint_unsigned" has invalid type. Value must be a valid range between 0 and 9,223,372,036,854,775,807', $e->getMessage()); } @@ -2253,7 +2253,7 @@ public function testListDocumentSearch(): void public function testEmptyTenant(): void { - if(static::getDatabase()->getAdapter()->getSharedTables()) { + if (static::getDatabase()->getAdapter()->getSharedTables()) { $this->expectNotToPerformAssertions(); return; } @@ -2432,7 +2432,7 @@ public function testUpdateDocumentConflict(Document $document): void return $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof ConflictException); $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); } @@ -2573,7 +2573,7 @@ public function testArrayAttribute(): void try { $database->createDocument($collection, new Document([])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Missing required attribute "booleans"', $e->getMessage()); } @@ -2593,7 +2593,7 @@ public function testArrayAttribute(): void 'short' => ['More than 5 size'], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "short[\'0\']" has invalid type. Value must be a valid string and no longer than 5 chars', $e->getMessage()); } @@ -2602,7 +2602,7 @@ public function testArrayAttribute(): void 'names' => ['Joe', 100], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "names[\'1\']" has invalid type. Value must be a valid string and no longer than 255 chars', $e->getMessage()); } @@ -2611,7 +2611,7 @@ public function testArrayAttribute(): void 'age' => 1.5, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid integer', $e->getMessage()); } @@ -2620,7 +2620,7 @@ public function testArrayAttribute(): void 'age' => -100, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid range between 0 and 2,147,483,647', $e->getMessage()); } @@ -2649,7 +2649,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->assertEquals('"Fulltext" index is forbidden on array attributes', $e->getMessage()); } else { @@ -2660,7 +2660,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_KEY, ['numbers', 'names'], [100,100]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('An index may only contain one array attribute', $e->getMessage()); } @@ -2681,7 +2681,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx_numbers', Database::INDEX_KEY, ['tv_show', 'numbers'], [], []); // [700, 255] $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Index length is longer than the maximum: 768', $e->getMessage()); } } @@ -2692,7 +2692,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx4', Database::INDEX_KEY, ['age', 'names'], [10, 255], []); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Cannot set a length on "integer" attributes', $e->getMessage()); } @@ -2705,7 +2705,7 @@ public function testArrayAttribute(): void Query::equal('names', ['Joe']), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query equal on attribute "names" because it is an array.', $e->getMessage()); } @@ -2714,7 +2714,7 @@ public function testArrayAttribute(): void Query::contains('age', [10]) ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "age" because it is not an array or string.', $e->getMessage()); } @@ -3150,7 +3150,7 @@ public function testFindContains(): void Query::contains('price', [10.5]), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "price" because it is not an array or string.', $e->getMessage()); $this->assertTrue($e instanceof DatabaseException); } @@ -4057,7 +4057,7 @@ public function testOrSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: Or queries require at least two queries', $e->getMessage()); } } @@ -4117,7 +4117,7 @@ public function testAndSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: And queries require at least two queries', $e->getMessage()); } } @@ -4965,7 +4965,7 @@ public function testStructureValidationAfterRelationsAttribute(): void 'name' => 'Frozen', // Unknown attribute 'name' after relation attribute ])); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(StructureException::class, $e); } } @@ -5040,7 +5040,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void try { static::getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); @@ -15517,98 +15517,6 @@ public function testTransformations(): void $this->assertTrue($result->isEmpty()); } - public function testEvents(): void - { - Authorization::skip(function () { - $database = static::getDatabase(); - - $events = [ - Database::EVENT_DATABASE_CREATE, - Database::EVENT_DATABASE_LIST, - Database::EVENT_COLLECTION_CREATE, - Database::EVENT_COLLECTION_LIST, - Database::EVENT_COLLECTION_READ, - Database::EVENT_ATTRIBUTE_CREATE, - Database::EVENT_ATTRIBUTE_UPDATE, - Database::EVENT_INDEX_CREATE, - Database::EVENT_DOCUMENT_CREATE, - Database::EVENT_DOCUMENT_UPDATE, - Database::EVENT_DOCUMENT_READ, - Database::EVENT_DOCUMENT_FIND, - Database::EVENT_DOCUMENT_FIND, - Database::EVENT_DOCUMENT_COUNT, - Database::EVENT_DOCUMENT_SUM, - Database::EVENT_DOCUMENT_INCREASE, - Database::EVENT_DOCUMENT_DECREASE, - Database::EVENT_INDEX_DELETE, - Database::EVENT_DOCUMENT_DELETE, - Database::EVENT_ATTRIBUTE_DELETE, - Database::EVENT_COLLECTION_DELETE, - Database::EVENT_DATABASE_DELETE, - ]; - - $database->on(Database::EVENT_ALL, 'test', function ($event, $data) use (&$events) { - $shifted = array_shift($events); - - $this->assertEquals($shifted, $event); - }); - - if ($this->getDatabase()->getAdapter()->getSupportForSchemas()) { - $database->setDatabase('hellodb'); - $database->create(); - } else { - array_shift($events); - } - - $database->list(); - - $database->setDatabase($this->testDatabase); - - $collectionId = ID::unique(); - $database->createCollection($collectionId); - $database->listCollections(); - $database->getCollection($collectionId); - $database->createAttribute($collectionId, 'attr1', Database::VAR_INTEGER, 2, false); - $database->updateAttributeRequired($collectionId, 'attr1', true); - $indexId1 = 'index2_' . uniqid(); - $database->createIndex($collectionId, $indexId1, Database::INDEX_KEY, ['attr1']); - - $document = $database->createDocument($collectionId, new Document([ - '$id' => 'doc1', - 'attr1' => 10, - '$permissions' => [ - Permission::delete(Role::any()), - Permission::update(Role::any()), - Permission::read(Role::any()), - ], - ])); - - $executed = false; - $database->on(Database::EVENT_ALL, 'should-not-execute', function ($event, $data) use (&$executed) { - $executed = true; - }); - - $database->silent(function () use ($database, $collectionId, $document) { - $database->updateDocument($collectionId, 'doc1', $document->setAttribute('attr1', 15)); - $database->getDocument($collectionId, 'doc1'); - $database->find($collectionId); - $database->findOne($collectionId); - $database->count($collectionId); - $database->sum($collectionId, 'attr1'); - $database->increaseDocumentAttribute($collectionId, $document->getId(), 'attr1'); - $database->decreaseDocumentAttribute($collectionId, $document->getId(), 'attr1'); - }, ['should-not-execute']); - - $this->assertFalse($executed); - - $database->deleteIndex($collectionId, $indexId1); - $database->deleteDocument($collectionId, 'doc1'); - $database->deleteAttribute($collectionId, 'attr1'); - $database->deleteCollection($collectionId); - $database->delete('hellodb'); - }); - } - public function propegateBulkDocuments(bool $documentSecurity = false): void { for ($i = 0; $i < 10; $i++) { @@ -15739,4 +15647,96 @@ public function testDeleteBulkDocumentsRelationships(): void // Cascade } + + public function testEvents(): void + { + Authorization::skip(function () { + $database = static::getDatabase(); + + $events = [ + Database::EVENT_DATABASE_CREATE, + Database::EVENT_DATABASE_LIST, + Database::EVENT_COLLECTION_CREATE, + Database::EVENT_COLLECTION_LIST, + Database::EVENT_COLLECTION_READ, + Database::EVENT_ATTRIBUTE_CREATE, + Database::EVENT_ATTRIBUTE_UPDATE, + Database::EVENT_INDEX_CREATE, + Database::EVENT_DOCUMENT_CREATE, + Database::EVENT_DOCUMENT_UPDATE, + Database::EVENT_DOCUMENT_READ, + Database::EVENT_DOCUMENT_FIND, + Database::EVENT_DOCUMENT_FIND, + Database::EVENT_DOCUMENT_COUNT, + Database::EVENT_DOCUMENT_SUM, + Database::EVENT_DOCUMENT_INCREASE, + Database::EVENT_DOCUMENT_DECREASE, + Database::EVENT_INDEX_DELETE, + Database::EVENT_DOCUMENT_DELETE, + Database::EVENT_ATTRIBUTE_DELETE, + Database::EVENT_COLLECTION_DELETE, + Database::EVENT_DATABASE_DELETE, + ]; + + $database->on(Database::EVENT_ALL, 'test', function ($event, $data) use (&$events) { + $shifted = array_shift($events); + + $this->assertEquals($shifted, $event); + }); + + if ($this->getDatabase()->getAdapter()->getSupportForSchemas()) { + $database->setDatabase('hellodb'); + $database->create(); + } else { + array_shift($events); + } + + $database->list(); + + $database->setDatabase($this->testDatabase); + + $collectionId = ID::unique(); + $database->createCollection($collectionId); + $database->listCollections(); + $database->getCollection($collectionId); + $database->createAttribute($collectionId, 'attr1', Database::VAR_INTEGER, 2, false); + $database->updateAttributeRequired($collectionId, 'attr1', true); + $indexId1 = 'index2_' . uniqid(); + $database->createIndex($collectionId, $indexId1, Database::INDEX_KEY, ['attr1']); + + $document = $database->createDocument($collectionId, new Document([ + '$id' => 'doc1', + 'attr1' => 10, + '$permissions' => [ + Permission::delete(Role::any()), + Permission::update(Role::any()), + Permission::read(Role::any()), + ], + ])); + + $executed = false; + $database->on(Database::EVENT_ALL, 'should-not-execute', function ($event, $data) use (&$executed) { + $executed = true; + }); + + $database->silent(function () use ($database, $collectionId, $document) { + $database->updateDocument($collectionId, 'doc1', $document->setAttribute('attr1', 15)); + $database->getDocument($collectionId, 'doc1'); + $database->find($collectionId); + $database->findOne($collectionId); + $database->count($collectionId); + $database->sum($collectionId, 'attr1'); + $database->increaseDocumentAttribute($collectionId, $document->getId(), 'attr1'); + $database->decreaseDocumentAttribute($collectionId, $document->getId(), 'attr1'); + }, ['should-not-execute']); + + $this->assertFalse($executed); + + $database->deleteIndex($collectionId, $indexId1); + $database->deleteDocument($collectionId, 'doc1'); + $database->deleteAttribute($collectionId, 'attr1'); + $database->deleteCollection($collectionId); + $database->delete('hellodb'); + }); + } } From 4f3e91e575ead30d1eeeb200cbff6b9c48061079 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 17 Sep 2024 14:43:36 +0900 Subject: [PATCH 045/103] Run Linter --- src/Database/Adapter/MariaDB.php | 22 +++++++++++----------- src/Database/Adapter/Mongo.php | 11 +++++------ src/Database/Adapter/Postgres.php | 16 ++++++++-------- src/Database/Adapter/SQL.php | 6 +++--- src/Database/Adapter/SQLite.php | 12 ++++++------ src/Database/Database.php | 8 ++++---- src/Database/Exception.php | 2 +- src/Database/Query.php | 4 ++-- src/Database/Validator/Datetime.php | 18 +++++++++--------- src/Database/Validator/Index.php | 14 +++++++------- src/Database/Validator/Queries.php | 4 ++-- src/Database/Validator/Query/Filter.php | 18 +++++++++--------- src/Database/Validator/Structure.php | 2 +- tests/unit/Validator/DateTimeTest.php | 2 +- 14 files changed, 69 insertions(+), 70 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 7b1537d11..a3776fa98 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -687,7 +687,7 @@ public function createIndex(string $collection, string $id, string $type, array $attributes[$i] = "`{$attr}`{$length} {$order}"; - if(!empty($collectionAttribute['array']) && $this->castIndexArray()) { + if (!empty($collectionAttribute['array']) && $this->castIndexArray()) { $attributes[$i] = '(CAST(' . $attr . ' AS char(' . Database::ARRAY_INDEX_LENGTH . ') ARRAY))'; } } @@ -871,7 +871,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions->execute(); } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -919,7 +919,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_createdAt'] = $document->getCreatedAt(); $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if(!empty($document->getInternalId())) { + if (!empty($document->getInternalId())) { $attributes['_id'] = $document->getInternalId(); } @@ -999,7 +999,7 @@ public function createDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1247,7 +1247,7 @@ public function updateDocument(string $collection, Document $document): Document } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1504,7 +1504,7 @@ public function updateDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1651,7 +1651,7 @@ public function deleteDocuments(string $collection, array $queries): bool $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1786,7 +1786,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1914,7 +1914,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2131,7 +2131,7 @@ protected function getSQLCondition(Query $query): string return "`table_main`.{$attribute} {$this->getSQLOperator($query->getMethod())}"; case Query::TYPE_CONTAINS: - if($this->getSupportForJSONOverlaps() && $query->onArray()) { + if ($this->getSupportForJSONOverlaps() && $query->onArray()) { return "JSON_OVERLAPS(`table_main`.{$attribute}, :{$placeholder}_0)"; } @@ -2157,7 +2157,7 @@ protected function getSQLCondition(Query $query): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSON'; } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 41c3c147e..729e06755 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -3,7 +3,6 @@ namespace Utopia\Database\Adapter; use Exception; - use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -291,7 +290,7 @@ public function getSizeOfCollection(string $collection): int } else { throw new DatabaseException('No size found'); } - } catch(Exception $e) { + } catch (Exception $e) { throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); } } @@ -935,8 +934,8 @@ public function deleteDocuments(string $collection, array $queries): bool try { $res = $this->client->delete( - collection: $name, - filters: $filters, + collection: $name, + filters: $filters, options: $options, limit: 0 ); @@ -1406,7 +1405,7 @@ protected function buildFilters(array $queries, string $separator = '$and'): arr $queries = Query::groupByType($queries)['filters']; foreach ($queries as $query) { /* @var $query Query */ - if($query->isNested()) { + if ($query->isNested()) { $operator = $this->getQueryOperator($query->getMethod()); $filters[$separator][] = $this->buildFilters($query->getValues(), $operator); } else { @@ -1460,7 +1459,7 @@ protected function buildFilter(Query $query): array } elseif ($operator == '$ne' && \is_array($value)) { $filter[$attribute]['$nin'] = $value; } elseif ($operator == '$in') { - if($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { + if ($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { $filter[$attribute]['$regex'] = new Regex(".*{$this->escapeWildcards($value)}.*", 'i'); } else { $filter[$attribute]['$in'] = $query->getValues(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 9162ea12e..eb667c4a4 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -841,7 +841,7 @@ public function createDocument(string $collection, Document $document): Document $queryPermissions = $this->trigger(Database::EVENT_PERMISSIONS_CREATE, $queryPermissions); $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($sqlTenant) { + if ($sqlTenant) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -900,7 +900,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1232,7 +1232,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1424,7 +1424,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); } - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(':_tenant', $this->tenant); } @@ -1575,7 +1575,7 @@ public function deleteDocuments(string $collection, array $queries): bool $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1708,7 +1708,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1836,7 +1836,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2076,7 +2076,7 @@ protected function getFulltextValue(string $value): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSONB'; } diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index dd6d822c6..e73515a57 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -818,14 +818,14 @@ protected function bindConditionValue(mixed $stmt, Query $query): void return; } - if($query->isNested()) { + if ($query->isNested()) { foreach ($query->getValues() as $value) { $this->bindConditionValue($stmt, $value); } return; } - if($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { + if ($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { $placeholder = $this->getSQLPlaceholder($query) . '_0'; $stmt->bindValue($placeholder, json_encode($query->getValues()), PDO::PARAM_STR); return; @@ -1071,7 +1071,7 @@ public function getSQLConditions(array $queries = [], string $separator = 'AND') continue; } - if($query->isNested()) { + if ($query->isNested()) { $conditions[] = $this->getSQLConditions($query->getValues(), $query->getMethod()); } else { $conditions[] = $this->getSQLCondition($query); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 9f7441f6b..193f9b19c 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -448,7 +448,7 @@ public function createDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -522,7 +522,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -567,7 +567,7 @@ public function updateDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -701,7 +701,7 @@ public function updateDocument(string $collection, Document $document): Document $stmtAddPermissions = $this->getPDO()->prepare($sql); $stmtAddPermissions->bindValue(":_uid", $document->getId()); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(":_tenant", $this->tenant); } @@ -814,7 +814,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1012,7 +1012,7 @@ public function updateDocuments(string $collection, array $documents, int $batch $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); } - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(':_tenant', $this->tenant); } diff --git a/src/Database/Database.php b/src/Database/Database.php index 944c3bea0..b3f42f047 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4331,7 +4331,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4426,7 +4426,7 @@ public function decreaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4521,7 +4521,7 @@ public function deleteDocument(string $collection, string $id): bool $this->getDocument($collection->getId(), $id, forUpdate: true) )); - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -5190,7 +5190,7 @@ public function find(string $collection, array $queries = []): array $results = $skipAuth ? Authorization::skip($getResults) : $getResults(); - foreach ($results as &$node) { + foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { $node = $this->silent(fn () => $this->populateDocumentRelationships($collection, $node, $nestedSelections)); } diff --git a/src/Database/Exception.php b/src/Database/Exception.php index 64ad3c997..94099c6ae 100644 --- a/src/Database/Exception.php +++ b/src/Database/Exception.php @@ -8,7 +8,7 @@ class Exception extends \Exception { public function __construct(string $message, int|string $code = 0, Throwable $previous = null) { - if(\is_string($code)) { + if (\is_string($code)) { if (\is_numeric($code)) { $code = (int) $code; } else { diff --git a/src/Database/Query.php b/src/Database/Query.php index 6af553415..aab17c195 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -297,7 +297,7 @@ public function toArray(): array { $array = ['method' => $this->method]; - if(!empty($this->attribute)) { + if (!empty($this->attribute)) { $array['attribute'] = $this->attribute; } @@ -690,7 +690,7 @@ public static function groupByType(array $queries): array */ public function isNested(): bool { - if(in_array($this->getMethod(), self::LOGICAL_TYPES)) { + if (in_array($this->getMethod(), self::LOGICAL_TYPES)) { return true; } diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index e8ffee5ff..812669d7a 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -33,7 +33,7 @@ class Datetime extends Validator */ public function __construct(bool $requireDateInFuture = false, string $precision = self::PRECISION_ANY, int $offset = 0) { - if($offset < 0) { + if ($offset < 0) { throw new \Exception('Offset must be a positive number.'); } @@ -50,13 +50,13 @@ public function getDescription(): string { $message = 'Value must be valid date'; - if($this->offset > 0) { + if ($this->offset > 0) { $message .= " at least " . $this->offset . " seconds in future"; - } elseif($this->requireDateInFuture) { + } elseif ($this->requireDateInFuture) { $message .= " in future"; } - if($this->precision !== self::PRECISION_ANY) { + if ($this->precision !== self::PRECISION_ANY) { $message .= " with " . $this->precision . " precision"; } @@ -84,9 +84,9 @@ public function isValid($value): bool return false; } - if($this->offset !== 0) { + if ($this->offset !== 0) { $diff = $date->getTimestamp() - $now->getTimestamp(); - if($diff <= $this->offset) { + if ($diff <= $this->offset) { return false; } } @@ -109,12 +109,12 @@ public function isValid($value): bool break; } - foreach($denyConstants as $constant) { - if(\intval($date->format($constant)) !== 0) { + foreach ($denyConstants as $constant) { + if (\intval($date->format($constant)) !== 0) { return false; } } - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index b24e39f73..fdaa1efe0 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -126,30 +126,30 @@ public function checkArrayIndex(Document $index): bool foreach ($attributes as $attributePosition => $attributeName) { $attribute = $this->attributes[\strtolower($attributeName)] ?? new Document(); - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { // Database::INDEX_UNIQUE Is not allowed! since mariaDB VS MySQL makes the unique Different on values - if($index->getAttribute('type') != Database::INDEX_KEY) { + if ($index->getAttribute('type') != Database::INDEX_KEY) { $this->message = '"' . ucfirst($index->getAttribute('type')) . '" index is forbidden on array attributes'; return false; } - if(empty($lengths[$attributePosition])) { + if (empty($lengths[$attributePosition])) { $this->message = 'Index length for array not specified'; return false; } $arrayAttributes[] = $attribute->getAttribute('key', ''); - if(count($arrayAttributes) > 1) { + if (count($arrayAttributes) > 1) { $this->message = 'An index may only contain one array attribute'; return false; } $direction = $orders[$attributePosition] ?? ''; - if(!empty($direction)) { + if (!empty($direction)) { $this->message = 'Invalid index order "' . $direction . '" on array attribute "'. $attribute->getAttribute('key', '') .'"'; return false; } - } elseif($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { + } elseif ($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { $this->message = 'Cannot set a length on "'. $attribute->getAttribute('type') . '" attributes'; return false; } @@ -188,7 +188,7 @@ public function checkIndexLength(Document $index): bool break; } - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { $attributeSize = Database::ARRAY_INDEX_LENGTH; $indexLength = Database::ARRAY_INDEX_LENGTH; } diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index 2e4aac71a..b1d67aad0 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -71,8 +71,8 @@ public function isValid($value): bool } } - if($query->isNested()) { - if(!self::isValid($query->getValues())) { + if ($query->isNested()) { + if (!self::isValid($query->getValues())) { return false; } } diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index 635fa4732..1fb50f9fc 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -131,29 +131,29 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s } } - if($attributeSchema['type'] === 'relationship') { + if ($attributeSchema['type'] === 'relationship') { /** * We can not disable relationship query since we have logic that use it, * so instead we validate against the relation type */ $options = $attributeSchema['options']; - if($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { + if ($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_MANY) { + if ($options['relationType'] === Database::RELATION_MANY_TO_MANY) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } @@ -161,7 +161,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s $array = $attributeSchema['array'] ?? false; - if( + if ( !$array && $method === Query::TYPE_CONTAINS && $attributeSchema['type'] !== Database::VAR_STRING @@ -170,7 +170,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s return false; } - if( + if ( $array && !in_array($method, [Query::TYPE_CONTAINS, Query::TYPE_IS_NULL, Query::TYPE_IS_NOT_NULL]) ) { @@ -253,12 +253,12 @@ public function isValid($value): bool case Query::TYPE_AND: $filters = Query::groupByType($value->getValues())['filters']; - if(count($value->getValues()) !== count($filters)) { + if (count($value->getValues()) !== count($filters)) { $this->message = \ucfirst($method) . ' queries can only contain filter queries'; return false; } - if(count($filters) < 2) { + if (count($filters) < 2) { $this->message = \ucfirst($method) . ' queries require at least two queries'; return false; } diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 12b753824..991a32240 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -257,7 +257,7 @@ public function isValid($document): bool continue; } - if($type === Database::VAR_RELATIONSHIP) { + if ($type === Database::VAR_RELATIONSHIP) { continue; } diff --git a/tests/unit/Validator/DateTimeTest.php b/tests/unit/Validator/DateTimeTest.php index b9157e8b8..d8ababb6f 100644 --- a/tests/unit/Validator/DateTimeTest.php +++ b/tests/unit/Validator/DateTimeTest.php @@ -128,7 +128,7 @@ public function testOffset(): void $threwException = false; try { $dateValidator = new DatetimeValidator(offset: -60); - } catch(\Exception $e) { + } catch (\Exception $e) { $threwException = true; } $this->assertTrue($threwException); From c3115b5ea2973cc70825187f470b30d4b1090608 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 17 Sep 2024 15:29:12 +0900 Subject: [PATCH 046/103] Update Authorisation Validator --- src/Database/Database.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index b7adc87ee..827ef51ef 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -5012,15 +5012,14 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba } foreach ($affectedDocuments as $document) { - $validator = new Authorization(self::PERMISSION_DELETE); - if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - if (!$validator->isValid([ + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ ...$collection->getDelete(), ...($documentSecurity ? $document->getDelete() : []) - ])) { - throw new AuthorizationException($validator->getDescription()); + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); } } From 1b3d2e9478a123d67179856377c2cd515e06e4cd Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 17 Sep 2024 18:02:59 +0900 Subject: [PATCH 047/103] Make findOne return empty document instead of false when no matches are found --- src/Database/Database.php | 24 ++++++++++++--------- tests/e2e/Adapter/Base.php | 44 +++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index d98347969..f934956b2 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4039,10 +4039,10 @@ private function updateDocumentRelationships(Document $collection, Document $old } if ( $oldValue?->getId() !== $value - && $this->skipRelationships(fn () => $this->findOne($relatedCollection->getId(), [ + && !($this->skipRelationships(fn () => $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$value]), - ])) + ]))->isEmpty()) ) { // Have to do this here because otherwise relations would be updated before the database can throw the unique violation throw new DuplicateException('Document already has a related document'); @@ -4060,10 +4060,10 @@ private function updateDocumentRelationships(Document $collection, Document $old if ( $oldValue?->getId() !== $value->getId() - && $this->skipRelationships(fn () => $this->findOne($relatedCollection->getId(), [ + && !($this->skipRelationships(fn () => $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$value->getId()]), - ])) + ]))->isEmpty()) ) { // Have to do this here because otherwise relations would be updated before the database can throw the unique violation throw new DuplicateException('Document already has a related document'); @@ -4726,7 +4726,7 @@ private function deleteRestrict( Query::equal($twoWayKey, [$document->getId()]) ]); - if (!$related instanceof Document) { + if ($related->isEmpty()) { return; } @@ -4749,7 +4749,7 @@ private function deleteRestrict( Query::equal($twoWayKey, [$document->getId()]) ])); - if ($related) { + if (!$related->isEmpty()) { throw new RestrictedException('Cannot delete document because it has at least one related document.'); } } @@ -4793,7 +4793,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection $related = $this->getDocument($relatedCollection->getId(), $value->getId(), [Query::select(['$id'])]); } - if (!$related instanceof Document) { + if ($related->isEmpty()) { return; } @@ -5172,10 +5172,10 @@ public function find(string $collection, array $queries = []): array /** * @param string $collection * @param array $queries - * @return false|Document + * @return Document * @throws DatabaseException */ - public function findOne(string $collection, array $queries = []): false|Document + public function findOne(string $collection, array $queries = []): Document { $results = $this->silent(fn () => $this->find($collection, \array_merge([ Query::limit(1) @@ -5185,7 +5185,11 @@ public function findOne(string $collection, array $queries = []): false|Document $this->trigger(self::EVENT_DOCUMENT_FIND, $found); - return $found; + if (!$found) { + return new Document(); + } else { + return $found; + } } /** diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 088535c60..6b4978ed4 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -4232,13 +4232,13 @@ public function testFindOne(): void Query::orderAsc('name') ]); - $this->assertTrue($document instanceof Document); + $this->assertFalse($document->isEmpty()); $this->assertEquals('Frozen', $document->getAttribute('name')); $document = $this->getDatabase()->findOne('movies', [ Query::offset(10) ]); - $this->assertEquals(false, $document); + $this->assertTrue($document->isEmpty()); } public function testFindNull(): void @@ -5475,7 +5475,7 @@ public function testRenameAttribute(): void // Document should be there if adapter migrated properly $document = $database->findOne('colors'); - $this->assertTrue($document instanceof Document); + $this->assertFalse($document->isEmpty()); $this->assertEquals('black', $document->getAttribute('verbose')); $this->assertEquals('#000000', $document->getAttribute('hex')); $this->assertEquals(null, $document->getAttribute('name')); @@ -6519,7 +6519,7 @@ public function testOneToOneOneWayRelationship(): void Query::select(['*', 'library.name']) ]); - if (!$person instanceof Document) { + if ($person->isEmpty()) { throw new Exception('Person not found'); } @@ -6995,7 +6995,7 @@ public function testOneToOneTwoWayRelationship(): void Query::select(['*', 'city.name']) ]); - if (!$country instanceof Document) { + if ($country->isEmpty()) { throw new Exception('Country not found'); } @@ -7569,7 +7569,7 @@ public function testOneToManyOneWayRelationship(): void Query::select(['*', 'albums.name']) ]); - if (!$artist instanceof Document) { + if ($artist->isEmpty()) { $this->fail('Artist not found'); } @@ -8002,7 +8002,7 @@ public function testOneToManyTwoWayRelationship(): void Query::select(['*', 'accounts.name']) ]); - if (!$customer instanceof Document) { + if ($customer->isEmpty()) { throw new Exception('Customer not found'); } @@ -8414,7 +8414,7 @@ public function testManyToOneOneWayRelationship(): void Query::select(['*', 'movie.name']) ]); - if (!$review instanceof Document) { + if ($review->isEmpty()) { throw new Exception('Review not found'); } @@ -8791,7 +8791,7 @@ public function testManyToOneTwoWayRelationship(): void Query::select(['*', 'store.name']) ]); - if (!$product instanceof Document) { + if ($product->isEmpty()) { throw new Exception('Product not found'); } @@ -9173,7 +9173,7 @@ public function testManyToManyOneWayRelationship(): void Query::select(['*', 'songs.name']) ]); - if (!$playlist instanceof Document) { + if ($playlist->isEmpty()) { throw new Exception('Playlist not found'); } @@ -9555,7 +9555,7 @@ public function testManyToManyTwoWayRelationship(): void Query::select(['*', 'classes.name']) ]); - if (!$student instanceof Document) { + if ($student->isEmpty()) { throw new Exception('Student not found'); } @@ -9859,7 +9859,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', 'models.name']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9881,7 +9881,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$id']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9896,7 +9896,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$internalId']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9911,7 +9911,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$collection']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9926,7 +9926,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$createdAt']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9941,7 +9941,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$updatedAt']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9956,7 +9956,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name', '$permissions']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9972,7 +9972,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['*', 'models.year']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -9988,7 +9988,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['*', 'models.*']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -10005,7 +10005,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['models.*']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } @@ -10021,7 +10021,7 @@ public function testSelectRelationshipAttributes(): void Query::select(['name']), ]); - if (!$make instanceof Document) { + if ($make->isEmpty()) { throw new Exception('Make not found'); } From ddca76107864c67bc18ee5a877d9d7897e9b2670 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 23 Sep 2024 19:22:22 +0900 Subject: [PATCH 048/103] Add get collection size data method --- src/Database/Adapter.php | 11 +++++++- src/Database/Adapter/MariaDB.php | 45 +++++++++++++++++++++++++++++++ src/Database/Adapter/Mongo.php | 29 ++++++++++++++++++++ src/Database/Adapter/Postgres.php | 35 ++++++++++++++++++++++++ src/Database/Adapter/SQLite.php | 40 +++++++++++++++++++++++++++ src/Database/Database.php | 26 ++++++++++++++++++ tests/e2e/Adapter/Base.php | 33 +++++++++++++++++++++++ 7 files changed, 218 insertions(+), 1 deletion(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 44f7f3ddc..4b176771f 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -659,7 +659,7 @@ abstract public function sum(string $collection, string $attribute, array $queri abstract public function count(string $collection, array $queries = [], ?int $max = null): int; /** - * Get Collection Size + * Get Collection Size on the disk * * @param string $collection * @return int @@ -667,6 +667,15 @@ abstract public function count(string $collection, array $queries = [], ?int $ma */ abstract public function getSizeOfCollection(string $collection): int; + /** + * Get Collection Size of the raw data + * + * @param string $collection + * @return int + * @throws DatabaseException + */ + abstract public function getSizeOfCollectionData(string $collection): int; + /** * Get max STRING limit * diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 03c0a33e6..027d824d0 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -246,6 +246,51 @@ public function getSizeOfCollection(string $collection): int return $size; } + /** + * Get Collection Size of the raw data + * + * @param string $collection + * @return int + * @throws DatabaseException + */ + public function getSizeOfCollectionData(string $collection): int + { + $collection = $this->filter($collection); + $collection = $this->getNamespace() . '_' . $collection; + $database = $this->getDatabase(); + $name = $collection; + $permissions = $collection . '_perms'; + + $collectionSize = $this->getPDO()->prepare(" + SELECT SUM(data_length + index_length) + FROM information_schema.TABLES + WHERE table_name = :name AND + table_schema = :database + "); + + $permissionsSize = $this->getPDO()->prepare(" + SELECT SUM(data_length + index_length) + FROM INFORMATION_SCHEMA.TABLES + WHERE table_name = :permissions AND + table_schema = :database + "); + + $collectionSize->bindParam(':name', $collection); + $collectionSize->bindParam(':database', $database); + $permissionsSize->bindParam(':permissions', $permissions); + $permissionsSize->bindParam(':database', $database); + + try { + $collectionSize->execute(); + $permissionsSize->execute(); + $size = $collectionSize->fetchColumn() + $permissionsSize->fetchColumn(); + } catch (PDOException $e) { + throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); + } + + return $size; + } + /** * Delete collection * diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 693c18965..a1cc5ebe5 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -295,6 +295,35 @@ public function getSizeOfCollection(string $collection): int } } + /** + * Get Collection Size + * @param string $collection + * @return int + * @throws DatabaseException + */ + public function getSizeOfCollectionData(string $collection): int + { + $namespace = $this->getNamespace(); + $collection = $this->filter($collection); + $collection = $namespace. '_' . $collection; + + $command = [ + 'collStats' => $collection, + 'scale' => 1 + ]; + + try { + $result = $this->getClient()->query($command); + if (is_object($result)) { + return $result->totalSize; + } else { + throw new DatabaseException('No size found'); + } + } catch (Exception $e) { + throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); + } + } + /** * Delete Collection * diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 92445569f..8789ee4e5 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -226,6 +226,41 @@ public function getSizeOfCollection(string $collection): int return $size; } + /** + * Get Collection Size + * @param string $collection + * @return int + * @throws DatabaseException + * + */ + public function getSizeOfCollectionData(string $collection): int + { + $collection = $this->filter($collection); + $name = $this->getSQLTable($collection); + $permissions = $this->getSQLTable($collection . '_perms'); + + $collectionSize = $this->getPDO()->prepare(" + SELECT pg_total_relation_size(:name); + "); + + $permissionsSize = $this->getPDO()->prepare(" + SELECT pg_total_relation_size(:permissions); + "); + + $collectionSize->bindParam(':name', $name); + $permissionsSize->bindParam(':permissions', $permissions); + + try { + $collectionSize->execute(); + $permissionsSize->execute(); + $size = $collectionSize->fetchColumn() + $permissionsSize->fetchColumn(); + } catch (PDOException $e) { + throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); + } + + return $size; + } + /** * Delete Collection * diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 193f9b19c..66f6389ac 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -227,6 +227,46 @@ public function getSizeOfCollection(string $collection): int return $size; } + /** + * Get Collection Size + * @param string $collection + * @return int + * @throws DatabaseException + * + */ + public function getSizeOfCollectionData(string $collection): int + { + $collection = $this->filter($collection); + $namespace = $this->getNamespace(); + $name = $namespace . '_' . $collection; + $permissions = $namespace . '_' . $collection . '_perms'; + + $collectionSize = $this->getPDO()->prepare(" + SELECT SUM(\"pgsize\") + FROM \"dbstat\" + WHERE name = :name; + "); + + $permissionsSize = $this->getPDO()->prepare(" + SELECT SUM(\"pgsize\") + FROM \"dbstat\" + WHERE name = :name; + "); + + $collectionSize->bindParam(':name', $name); + $permissionsSize->bindParam(':name', $permissions); + + try { + $collectionSize->execute(); + $permissionsSize->execute(); + $size = $collectionSize->fetchColumn() + $permissionsSize->fetchColumn(); + } catch (PDOException $e) { + throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); + } + + return $size; + } + /** * Delete Collection * @param string $id diff --git a/src/Database/Database.php b/src/Database/Database.php index f934956b2..36e48a324 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -1265,6 +1265,32 @@ public function getSizeOfCollection(string $collection): int return $this->adapter->getSizeOfCollection($collection->getId()); } + /** + * Get Collection Size Data + * + * @param string $collection + * + * @return int + */ + public function getSizeOfCollectionData(string $collection): int + { + if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { + throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); + } + + $collection = $this->silent(fn () => $this->getCollection($collection)); + + if ($collection->isEmpty()) { + throw new DatabaseException('Collection not found'); + } + + if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { + throw new DatabaseException('Collection not found'); + } + + return $this->adapter->getSizeOfCollectionData($collection->getId()); + } + /** * Delete Collection * diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 6b4978ed4..eee460865 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1076,6 +1076,39 @@ public function testSizeCollection(): void $this->assertGreaterThan($size1, $size2); } + public function testSizeCollectionData(): void + { + $this->getDatabase()->createCollection('sizeTest1'); + $this->getDatabase()->createCollection('sizeTest2'); + + $size1 = $this->getDatabase()->getSizeOfCollectionData('sizeTest1'); + $size2 = $this->getDatabase()->getSizeOfCollectionData('sizeTest2'); + $sizeDifference = abs($size1 - $size2); + // Size of an empty collection returns either 172032 or 167936 bytes randomly + // Therefore asserting with a tolerance of 5000 bytes + $byteDifference = 5000; + $this->assertLessThan($byteDifference, $sizeDifference); + + $this->getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 20000, true); + $this->getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + + $loopCount = 40; + + for ($i = 0; $i < $loopCount; $i++) { + $this->getDatabase()->createDocument('sizeTest2', new Document([ + 'string1' => 'string1' . $i, + 'string2' => 'string2' . $i, + 'string3' => 'string3' . $i, + ])); + } + + $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + + $this->assertGreaterThan($size1, $size2); + } + public function testSizeFullText(): void { // SQLite does not support fulltext indexes From 25bbfd4174a8010fb8d6206cb020ef40c8b8b3fa Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 23 Sep 2024 19:28:04 +0900 Subject: [PATCH 049/103] Run Linter --- src/Database/Adapter.php | 2 +- src/Database/Adapter/MariaDB.php | 2 +- src/Database/Adapter/Mongo.php | 2 +- src/Database/Adapter/Postgres.php | 2 +- src/Database/Adapter/SQLite.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 4b176771f..f179dd4de 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -669,7 +669,7 @@ abstract public function getSizeOfCollection(string $collection): int; /** * Get Collection Size of the raw data - * + * * @param string $collection * @return int * @throws DatabaseException diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 027d824d0..fccac813e 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -248,7 +248,7 @@ public function getSizeOfCollection(string $collection): int /** * Get Collection Size of the raw data - * + * * @param string $collection * @return int * @throws DatabaseException diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index a1cc5ebe5..fed829ca5 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -295,7 +295,7 @@ public function getSizeOfCollection(string $collection): int } } - /** + /** * Get Collection Size * @param string $collection * @return int diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8789ee4e5..739846b37 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -226,7 +226,7 @@ public function getSizeOfCollection(string $collection): int return $size; } - /** + /** * Get Collection Size * @param string $collection * @return int diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 66f6389ac..77dafe740 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -227,7 +227,7 @@ public function getSizeOfCollection(string $collection): int return $size; } - /** + /** * Get Collection Size * @param string $collection * @return int From 79da9b5c447264667566bb631b5c2ded01cf6a96 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 23 Sep 2024 19:32:54 +0900 Subject: [PATCH 050/103] Address comments --- src/Database/Adapter.php | 4 ++-- src/Database/Adapter/MariaDB.php | 6 +++--- src/Database/Adapter/Mongo.php | 8 ++++---- src/Database/Adapter/MySQL.php | 4 ++-- src/Database/Adapter/Postgres.php | 8 ++++---- src/Database/Adapter/SQLite.php | 8 ++++---- src/Database/Database.php | 12 ++++++------ tests/e2e/Adapter/Base.php | 6 +++--- 8 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index f179dd4de..9a6558b19 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -665,7 +665,7 @@ abstract public function count(string $collection, array $queries = [], ?int $ma * @return int * @throws DatabaseException */ - abstract public function getSizeOfCollection(string $collection): int; + abstract public function getSizeOfCollectionOnDisk(string $collection): int; /** * Get Collection Size of the raw data @@ -674,7 +674,7 @@ abstract public function getSizeOfCollection(string $collection): int; * @return int * @throws DatabaseException */ - abstract public function getSizeOfCollectionData(string $collection): int; + abstract public function getSizeOfCollection(string $collection): int; /** * Get max STRING limit diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index fccac813e..b4341bd23 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -206,13 +206,13 @@ public function createCollection(string $name, array $attributes = [], array $in } /** - * Get collection size + * Get collection size on disk * * @param string $collection * @return int * @throws DatabaseException */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { $collection = $this->filter($collection); $collection = $this->getNamespace() . '_' . $collection; @@ -253,7 +253,7 @@ public function getSizeOfCollection(string $collection): int * @return int * @throws DatabaseException */ - public function getSizeOfCollectionData(string $collection): int + public function getSizeOfCollection(string $collection): int { $collection = $this->filter($collection); $collection = $this->getNamespace() . '_' . $collection; diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index fed829ca5..b06fc5c61 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -267,12 +267,12 @@ public function listCollections(): array } /** - * Get Collection Size + * Get Collection Size on disk * @param string $collection * @return int * @throws DatabaseException */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { $namespace = $this->getNamespace(); $collection = $this->filter($collection); @@ -296,12 +296,12 @@ public function getSizeOfCollection(string $collection): int } /** - * Get Collection Size + * Get Collection Size of raw data * @param string $collection * @return int * @throws DatabaseException */ - public function getSizeOfCollectionData(string $collection): int + public function getSizeOfCollection(string $collection): int { $namespace = $this->getNamespace(); $collection = $this->filter($collection); diff --git a/src/Database/Adapter/MySQL.php b/src/Database/Adapter/MySQL.php index aaf258e30..061a76d57 100644 --- a/src/Database/Adapter/MySQL.php +++ b/src/Database/Adapter/MySQL.php @@ -37,12 +37,12 @@ public function setTimeout(int $milliseconds, string $event = Database::EVENT_AL } /** - * Get Collection Size + * Get Collection Size on disk * @param string $collection * @return int * @throws DatabaseException */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { $collection = $this->filter($collection); $collection = $this->getNamespace() . '_' . $collection; diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 739846b37..e630fc474 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -192,13 +192,13 @@ public function createCollection(string $name, array $attributes = [], array $in } /** - * Get Collection Size + * Get Collection Size on disk * @param string $collection * @return int * @throws DatabaseException * */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { $collection = $this->filter($collection); $name = $this->getSQLTable($collection); @@ -227,13 +227,13 @@ public function getSizeOfCollection(string $collection): int } /** - * Get Collection Size + * Get Collection Size of raw data * @param string $collection * @return int * @throws DatabaseException * */ - public function getSizeOfCollectionData(string $collection): int + public function getSizeOfCollection(string $collection): int { $collection = $this->filter($collection); $name = $this->getSQLTable($collection); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 77dafe740..5c56d64d0 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -188,13 +188,13 @@ public function createCollection(string $name, array $attributes = [], array $in } /** - * Get Collection Size + * Get Collection Size on disk * @param string $collection * @return int * @throws DatabaseException * */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { $collection = $this->filter($collection); $namespace = $this->getNamespace(); @@ -228,13 +228,13 @@ public function getSizeOfCollection(string $collection): int } /** - * Get Collection Size + * Get Collection Size of raw data * @param string $collection * @return int * @throws DatabaseException * */ - public function getSizeOfCollectionData(string $collection): int + public function getSizeOfCollection(string $collection): int { $collection = $this->filter($collection); $namespace = $this->getNamespace(); diff --git a/src/Database/Database.php b/src/Database/Database.php index 36e48a324..078044b29 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -1240,13 +1240,13 @@ public function listCollections(int $limit = 25, int $offset = 0): array } /** - * Get Collection Size + * Get Collection Size on disk * * @param string $collection * * @return int */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -1262,17 +1262,17 @@ public function getSizeOfCollection(string $collection): int throw new DatabaseException('Collection not found'); } - return $this->adapter->getSizeOfCollection($collection->getId()); + return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); } /** - * Get Collection Size Data + * Get Collection Size of Data * * @param string $collection * * @return int */ - public function getSizeOfCollectionData(string $collection): int + public function getSizeOfCollection(string $collection): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -1288,7 +1288,7 @@ public function getSizeOfCollectionData(string $collection): int throw new DatabaseException('Collection not found'); } - return $this->adapter->getSizeOfCollectionData($collection->getId()); + return $this->adapter->getSizeOfCollection($collection->getId()); } /** diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index eee460865..c70e18249 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1076,13 +1076,13 @@ public function testSizeCollection(): void $this->assertGreaterThan($size1, $size2); } - public function testSizeCollectionData(): void + public function testSizeCollectionOnDisk(): void { $this->getDatabase()->createCollection('sizeTest1'); $this->getDatabase()->createCollection('sizeTest2'); - $size1 = $this->getDatabase()->getSizeOfCollectionData('sizeTest1'); - $size2 = $this->getDatabase()->getSizeOfCollectionData('sizeTest2'); + $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTest1'); + $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTest2'); $sizeDifference = abs($size1 - $size2); // Size of an empty collection returns either 172032 or 167936 bytes randomly // Therefore asserting with a tolerance of 5000 bytes From 496b574c3396e26ae650c237597083db00656816 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 23 Sep 2024 20:22:05 +0900 Subject: [PATCH 051/103] Get tests working for MariaDB --- src/Database/Adapter/MariaDB.php | 1 - tests/e2e/Adapter/Base.php | 39 +++++++++++++++++++++----------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index b4341bd23..db5f27ed2 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -258,7 +258,6 @@ public function getSizeOfCollection(string $collection): int $collection = $this->filter($collection); $collection = $this->getNamespace() . '_' . $collection; $database = $this->getDatabase(); - $name = $collection; $permissions = $collection . '_perms'; $collectionSize = $this->getPDO()->prepare(" diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index c70e18249..64561eae7 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1065,46 +1065,59 @@ public function testSizeCollection(): void for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->createDocument('sizeTest2', new Document([ - 'string1' => 'string1' . $i, - 'string2' => 'string2' . $i, - 'string3' => 'string3' . $i, + '$id' => 'doc' . $i, + 'string1' => 'string1' . $i . str_repeat('A', 10000), + 'string2' => 'string2', + 'string3' => 'string3', ])); } $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertGreaterThan($size1, $size2); + + self::$authorization->skip(function () use ($loopCount) { + for ($i = 0; $i < $loopCount; $i++) { + $this->getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); + } + }); + + sleep(10); // Let DB clean up + + $size3 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + + $this->assertLessThan($size2, $size3); } public function testSizeCollectionOnDisk(): void { - $this->getDatabase()->createCollection('sizeTest1'); - $this->getDatabase()->createCollection('sizeTest2'); + $this->getDatabase()->createCollection('sizeTestDisk1'); + $this->getDatabase()->createCollection('sizeTestDisk2'); - $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTest1'); - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTest2'); + $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk1'); + $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); $sizeDifference = abs($size1 - $size2); // Size of an empty collection returns either 172032 or 167936 bytes randomly // Therefore asserting with a tolerance of 5000 bytes $byteDifference = 5000; $this->assertLessThan($byteDifference, $sizeDifference); - $this->getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 20000, true); - $this->getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + $this->getDatabase()->createAttribute('sizeTestDisk2', 'string1', Database::VAR_STRING, 20000, true); + $this->getDatabase()->createAttribute('sizeTestDisk2', 'string2', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createAttribute('sizeTestDisk2', 'string3', Database::VAR_STRING, 254 + 1, true); + $this->getDatabase()->createIndex('sizeTestDisk2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 40; for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->createDocument('sizeTest2', new Document([ + $this->getDatabase()->createDocument('sizeTestDisk2', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, ])); } - $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); $this->assertGreaterThan($size1, $size2); } From 96a8d605c859eb517929aa1cc85eb2a94a3b7e23 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 27 Sep 2024 17:01:39 +0900 Subject: [PATCH 052/103] Sync with 0.53.x branch version --- composer.lock | 26 ++++++++++----------- src/Database/Adapter/MariaDB.php | 20 +++++++++++++++- src/Database/Adapter/Mongo.php | 32 +++++++++++-------------- src/Database/Adapter/Postgres.php | 22 ++++++++++++++--- src/Database/Adapter/SQLite.php | 11 +++++++++ src/Database/Database.php | 11 +++++++++ tests/e2e/Adapter/Base.php | 39 ++++++++++++++++++++++++------- 7 files changed, 116 insertions(+), 45 deletions(-) diff --git a/composer.lock b/composer.lock index 6ec1690e1..2490075e9 100644 --- a/composer.lock +++ b/composer.lock @@ -738,16 +738,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.19.1", + "version": "v4.19.2", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "4e1b88d21c69391150ace211e9eaf05810858d0b" + "reference": "0ed4c8949a32986043e977dbe14776c14d644c45" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/4e1b88d21c69391150ace211e9eaf05810858d0b", - "reference": "4e1b88d21c69391150ace211e9eaf05810858d0b", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/0ed4c8949a32986043e977dbe14776c14d644c45", + "reference": "0ed4c8949a32986043e977dbe14776c14d644c45", "shasum": "" }, "require": { @@ -788,9 +788,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.1" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.2" }, - "time": "2024-03-17T08:10:35+00:00" + "time": "2024-09-17T19:36:00+00:00" }, { "name": "pcov/clobber", @@ -1323,16 +1323,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.20", + "version": "9.6.21", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "49d7820565836236411f5dc002d16dd689cde42f" + "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/49d7820565836236411f5dc002d16dd689cde42f", - "reference": "49d7820565836236411f5dc002d16dd689cde42f", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", + "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", "shasum": "" }, "require": { @@ -1347,7 +1347,7 @@ "phar-io/manifest": "^2.0.4", "phar-io/version": "^3.2.1", "php": ">=7.3", - "phpunit/php-code-coverage": "^9.2.31", + "phpunit/php-code-coverage": "^9.2.32", "phpunit/php-file-iterator": "^3.0.6", "phpunit/php-invoker": "^3.1.1", "phpunit/php-text-template": "^2.0.4", @@ -1406,7 +1406,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.20" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.21" }, "funding": [ { @@ -1422,7 +1422,7 @@ "type": "tidelift" } ], - "time": "2024-07-10T11:45:39+00:00" + "time": "2024-09-19T10:50:18+00:00" }, { "name": "psr/container", diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index db5f27ed2..bcff516e1 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -262,7 +262,7 @@ public function getSizeOfCollection(string $collection): int $collectionSize = $this->getPDO()->prepare(" SELECT SUM(data_length + index_length) - FROM information_schema.TABLES + FROM INFORMATION_SCHEMA.TABLES WHERE table_name = :name AND table_schema = :database "); @@ -2299,4 +2299,22 @@ protected function processException(PDOException $e): void throw $e; } + + + /** + * Analyze a collection updating it's metadata on the database. + * This Locks the table and should be avoided if possible + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + $name = $this->filter($collection); + + $sql = "ANALYZE TABLE {$this->getSQLTable($name)}"; + + $stmt = $this->getPDO()->prepare($sql); + return $stmt->execute(); + } } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index b06fc5c61..fc2eb009a 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -274,25 +274,7 @@ public function listCollections(): array */ public function getSizeOfCollectionOnDisk(string $collection): int { - $namespace = $this->getNamespace(); - $collection = $this->filter($collection); - $collection = $namespace. '_' . $collection; - - $command = [ - 'collStats' => $collection, - 'scale' => 1 - ]; - - try { - $result = $this->getClient()->query($command); - if (is_object($result)) { - return $result->totalSize; - } else { - throw new DatabaseException('No size found'); - } - } catch (Exception $e) { - throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); - } + return $this->getSizeOfCollection($collection); } /** @@ -1863,4 +1845,16 @@ public function clearTimeout(string $event): void $this->timeout = null; } + + + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return false; + } } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index e630fc474..6d40898b4 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -196,7 +196,6 @@ public function createCollection(string $name, array $attributes = [], array $in * @param string $collection * @return int * @throws DatabaseException - * */ public function getSizeOfCollectionOnDisk(string $collection): int { @@ -240,11 +239,11 @@ public function getSizeOfCollection(string $collection): int $permissions = $this->getSQLTable($collection . '_perms'); $collectionSize = $this->getPDO()->prepare(" - SELECT pg_total_relation_size(:name); + SELECT pg_relation_size(:name); "); $permissionsSize = $this->getPDO()->prepare(" - SELECT pg_total_relation_size(:permissions); + SELECT pg_relation_size(:permissions); "); $collectionSize->bindParam(':name', $name); @@ -2265,4 +2264,21 @@ public function getLikeOperator(): string { return 'ILIKE'; } + + /** + * Analyze a collection updating it's metadata on the database. + * This Locks the table and should be avoided if possible + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + $name = $this->filter($collection); + + $sql = "ANALYZE {$this->getSQLTable($name)}"; + + $stmt = $this->getPDO()->prepare($sql); + return $stmt->execute(); + } } diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 5c56d64d0..e52ccf68d 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -1419,4 +1419,15 @@ protected function processException(PDOException $e): void throw $e; } + + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return false; + } } diff --git a/src/Database/Database.php b/src/Database/Database.php index 078044b29..e575785ac 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -5744,4 +5744,15 @@ public function getInternalAttributes(): array return $attributes; } + + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return $this->adapter->analyzeCollection($collection); + } } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 64561eae7..2b8484376 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1061,7 +1061,7 @@ public function testSizeCollection(): void $this->getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); $this->getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); - $loopCount = 40; + $loopCount = 100; for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->createDocument('sizeTest2', new Document([ @@ -1072,6 +1072,10 @@ public function testSizeCollection(): void ])); } + static::getDatabase()->analyzeCollection('sizeTest2'); + + sleep(5); // Let DB analyze + $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertGreaterThan($size1, $size2); @@ -1082,10 +1086,13 @@ public function testSizeCollection(): void } }); - sleep(10); // Let DB clean up + static::getDatabase()->analyzeCollection('sizeTest2'); + sleep(5); // Let DB clean up $size3 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + var_dump($size1, $size2, $size3); + $this->assertLessThan($size2, $size3); } @@ -1111,15 +1118,29 @@ public function testSizeCollectionOnDisk(): void for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->createDocument('sizeTestDisk2', new Document([ - 'string1' => 'string1' . $i, - 'string2' => 'string2' . $i, - 'string3' => 'string3' . $i, + '$id' => 'doc' . $i, + 'string1' => 'string1' . $i . str_repeat('A', 10000), + 'string2' => 'string2', + 'string3' => 'string3', ])); } - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); + $this->getDatabase()->analyzeCollection('sizeTestDisk2'); + $size2 = $this->getDatabase()->getSizeOfCollection('sizeTestDisk2'); $this->assertGreaterThan($size1, $size2); + + self::$authorization->skip(function () use ($loopCount) { + for ($i = 0; $i < $loopCount; $i++) { + $this->getDatabase()->deleteDocument('sizeTestDisk2', 'doc' . $i); + } + }); + + sleep(10); // Let DB clean up + + $size3 = $this->getDatabase()->getSizeOfCollection('sizeTestDisk2'); + + $this->assertLessThan($size2, $size3); } public function testSizeFullText(): void @@ -1132,7 +1153,7 @@ public function testSizeFullText(): void $this->getDatabase()->createCollection('fullTextSizeTest'); - $size1 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); $this->getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); @@ -1149,13 +1170,13 @@ public function testSizeFullText(): void ])); } - $size2 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size1, $size2); $this->getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); - $size3 = $this->getDatabase()->getSizeOfCollection('fullTextSizeTest'); + $size3 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size2, $size3); } From 04d801572983a50de691bedc6d8c1363ec107e6b Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 1 Oct 2024 15:58:20 +0900 Subject: [PATCH 053/103] Use ID based deletion, add more tests --- src/Database/Adapter.php | 4 +- src/Database/Adapter/MariaDB.php | 85 +++++++++++++++++---------- src/Database/Adapter/Mongo.php | 7 +-- src/Database/Adapter/Postgres.php | 85 +++++++++++++++++---------- src/Database/Database.php | 29 ++++++---- tests/e2e/Adapter/Base.php | 96 ++++++++++++++++++++++++++++--- 6 files changed, 219 insertions(+), 87 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index c655e1e59..eec087661 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -621,11 +621,11 @@ abstract public function deleteDocument(string $collection, string $id): bool; * Delete Documents * * @param string $collection - * @param array<\Utopia\Database\Query> $queries + * @param array $ids * * @return bool */ - abstract public function deleteDocuments(string $collection, array $queries): bool; + abstract public function deleteDocuments(string $collection, array $ids): bool; /** * Find Documents diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 504d131f1..129a0b229 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1636,51 +1636,76 @@ public function deleteDocument(string $collection, string $id): bool * Delete Documents * * @param string $collection - * @param array<\Utopia\Database\Query> $queries + * @param array $ids * * @return bool */ - public function deleteDocuments(string $collection, array $queries): bool + public function deleteDocuments(string $collection, array $ids): bool { - $name = $this->filter($collection); - $where = []; + try { + $name = $this->filter($collection); + $where = []; - $queries = array_map(fn ($query) => clone $query, $queries); + if ($this->sharedTables) { + $where[] = "_tenant = :_tenant"; + } - $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { - $where[] = $conditions; - } + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; - if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; - } + $sqlWhere = !empty($where) ? 'WHERE ' . \implode(' AND ', $where) : ''; - $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + $sql = " + DELETE FROM {$this->getSQLTable($name)} + {$sqlWhere}; + "; - $sql = " - DELETE FROM {$this->getSQLTable($name)} - {$sqlWhere}; - "; + $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); - $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + $stmt = $this->getPDO()->prepare($sql); - $stmt = $this->getPDO()->prepare($sql); + foreach ($ids as $id => $value) { + $stmt->bindValue(":_id_{$id}", $value); + } - foreach ($queries as $query) { - $this->bindConditionValue($stmt, $query); - } - if ($this->sharedTables) { - $stmt->bindValue(':_tenant', $this->tenant); - } + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } - try { - $stmt->execute(); - } catch (PDOException $e) { - $this->processException($e); + $sql = " + DELETE FROM {$this->getSQLTable($name . '_perms')} + WHERE _document IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ") + "; + + if ($this->sharedTables) { + $sql .= ' AND _tenant = :_tenant'; + } + + $sql = $this->trigger(Database::EVENT_PERMISSIONS_DELETE, $sql); + + $stmtPermissions = $this->getPDO()->prepare($sql); + + foreach ($ids as $id => $value) { + $stmtPermissions->bindValue(":_id_{$id}", $value); + } + + if ($this->sharedTables) { + $stmtPermissions->bindValue(':_tenant', $this->tenant); + } + + if (!$stmt->execute()) { + throw new DatabaseException('Failed to delete documents'); + } + + $deleted = $stmt->rowCount(); + + if (!$stmtPermissions->execute()) { + throw new DatabaseException('Failed to delete permissions'); + } + } catch (\Throwable $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return true; + return $deleted; } /** diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index c54ed20ea..7841c51b0 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -912,16 +912,15 @@ public function deleteDocument(string $collection, string $id): bool * Delete Documents * * @param string $collection - * @param array<\Utopia\Database\Query> $queries + * @param array $ids * * @return bool */ - public function deleteDocuments(string $collection, array $queries): bool + public function deleteDocuments(string $collection, array $ids): bool { $name = $this->getNamespace() . '_' . $this->filter($collection); - $queries = array_map(fn ($query) => clone $query, $queries); - $filters = $this->buildFilters($queries); + $filters = $this->buildFilters([new Query(Query::TYPE_EQUAL, '_uid', $ids)]); if ($this->sharedTables) { $filters['_tenant'] = (string)$this->getTenant(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 92b91ca4e..16788d26b 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1561,51 +1561,76 @@ public function deleteDocument(string $collection, string $id): bool * Delete Documents * * @param string $collection - * @param array<\Utopia\Database\Query> $queries + * @param array $ids * * @return bool */ - public function deleteDocuments(string $collection, array $queries): bool + public function deleteDocuments(string $collection, array $ids): bool { - $name = $this->filter($collection); - $where = []; + try { + $name = $this->filter($collection); + $where = []; - $queries = array_map(fn ($query) => clone $query, $queries); + if ($this->sharedTables) { + $where[] = "_tenant = :_tenant"; + } - $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { - $where[] = $conditions; - } + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; - if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; - } + $sqlWhere = !empty($where) ? 'WHERE ' . \implode(' AND ', $where) : ''; - $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + $sql = " + DELETE FROM {$this->getSQLTable($name)} + {$sqlWhere}; + "; - $sql = " - DELETE FROM {$this->getSQLTable($name)} - {$sqlWhere} - "; + $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); - $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + $stmt = $this->getPDO()->prepare($sql); - $stmt = $this->getPDO()->prepare($sql); + foreach ($ids as $id => $value) { + $stmt->bindValue(":_id_{$id}", $value); + } - foreach ($queries as $query) { - $this->bindConditionValue($stmt, $query); - } - if ($this->sharedTables) { - $stmt->bindValue(':_tenant', $this->tenant); - } + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } - try { - $stmt->execute(); - } catch (PDOException $e) { - $this->processException($e); + $sql = " + DELETE FROM {$this->getSQLTable($name . '_perms')} + WHERE _document IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ") + "; + + if ($this->sharedTables) { + $sql .= ' AND _tenant = :_tenant'; + } + + $sql = $this->trigger(Database::EVENT_PERMISSIONS_DELETE, $sql); + + $stmtPermissions = $this->getPDO()->prepare($sql); + + foreach ($ids as $id => $value) { + $stmtPermissions->bindValue(":_id_{$id}", $value); + } + + if ($this->sharedTables) { + $stmtPermissions->bindValue(':_tenant', $this->tenant); + } + + if (!$stmt->execute()) { + throw new DatabaseException('Failed to delete documents'); + } + + $deleted = $stmt->rowCount(); + + if (!$stmtPermissions->execute()) { + throw new DatabaseException('Failed to delete permissions'); + } + } catch (\Throwable $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return true; + return $deleted; } /** diff --git a/src/Database/Database.php b/src/Database/Database.php index 827ef51ef..7bb9826ab 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4993,24 +4993,29 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); + $affectedDocumentIds = []; - $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize) { + $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; while (true) { - $affectedDocuments = $this->find($collection->getId(), array_merge( - empty($lastDocument) ? [ - Query::limit($batchSize), - ] : [ - Query::limit($batchSize), - Query::cursorAfter($lastDocument), - ], - $queries, - )); + $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + return $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + )); + }); if (empty($affectedDocuments)) { break; } + $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); + foreach ($affectedDocuments as $document) { if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); @@ -5035,7 +5040,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $this->purgeCachedDocument($collection->getId(), $document->getId()); } - if (count($affectedDocuments) < 100) { + if (count($affectedDocuments) < $batchSize) { break; } else { $lastDocument = end($affectedDocuments); @@ -5043,7 +5048,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba } // Mass delete using adapter with query - return $this->adapter->deleteDocuments($collection->getId(), $queries); + return $this->adapter->deleteDocuments($collection->getId(), $affectedDocumentIds); }); return $deleted; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 8b340b0bd..d155e338c 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15642,27 +15642,105 @@ public function testDeleteBulkDocuments(): void static::getDatabase()->deleteCollection('bulk_delete'); } - - public function testDeleteBulkDocumentsRelationships(): void + public function testDeleteBulkDocumentsOneToOneRelationship(): void { if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - static::getDatabase()->createCollection('bulk_delete_r_1'); - static::getDatabase()->createCollection('bulk_delete_r_2'); + $this->getDatabase()->createCollection('bulk_delete_person'); + $this->getDatabase()->createCollection('bulk_delete_library'); - // ONE_TO_ONE - static::getDatabase()->createRelationship( - collection: 'bulk_delete_r_1', - relatedCollection: 'bulk_delete_r_2', + $this->getDatabase()->createAttribute('bulk_delete_person', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library', 'area', Database::VAR_STRING, 255, true); + + // Restrict + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person', + relatedCollection: 'bulk_delete_library', type: Database::RELATION_ONE_TO_ONE, + onDelete: Database::RELATION_MUTATE_RESTRICT ); - // Restrict + $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library' => [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person1->getAttribute('bulk_delete_library'); + $this->assertEquals('library1', $library['$id']); + $this->assertArrayNotHasKey('bulk_delete_person', $library); + + // Delete person + try { + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->fail('Failed to throw exception'); + } catch (RestrictedException $e) { + $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); + } + + $this->getDatabase()->updateDocument('bulk_delete_person', 'person1', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library' => null, + ])); + + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); // NULL + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person', + relatedCollection: 'bulk_delete_library', + type: Database::RELATION_ONE_TO_ONE, + onDelete: Database::RELATION_MUTATE_SET_NULL + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library' => [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + ])); // Cascade } From 87a6e3a835301a8e88c66712bddde8fc2f83239a Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 1 Oct 2024 17:22:54 +0900 Subject: [PATCH 054/103] Linter and CodeQL --- src/Database/Adapter.php | 2 +- src/Database/Adapter/MariaDB.php | 6 ++---- src/Database/Adapter/Postgres.php | 6 ++---- src/Database/Database.php | 2 +- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index eec087661..349193da1 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -621,7 +621,7 @@ abstract public function deleteDocument(string $collection, string $id): bool; * Delete Documents * * @param string $collection - * @param array $ids + * @param array $ids * * @return bool */ diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 129a0b229..3649b63da 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1696,16 +1696,14 @@ public function deleteDocuments(string $collection, array $ids): bool throw new DatabaseException('Failed to delete documents'); } - $deleted = $stmt->rowCount(); - if (!$stmtPermissions->execute()) { throw new DatabaseException('Failed to delete permissions'); - } + } } catch (\Throwable $e) { throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return $deleted; + return true; } /** diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 16788d26b..cc5ccce6c 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1621,16 +1621,14 @@ public function deleteDocuments(string $collection, array $ids): bool throw new DatabaseException('Failed to delete documents'); } - $deleted = $stmt->rowCount(); - if (!$stmtPermissions->execute()) { throw new DatabaseException('Failed to delete permissions'); - } + } } catch (\Throwable $e) { throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return $deleted; + return true; } /** diff --git a/src/Database/Database.php b/src/Database/Database.php index 7bb9826ab..1cacdf3f6 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4998,7 +4998,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; while (true) { - $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { return $this->find($collection->getId(), array_merge( empty($lastDocument) ? [ Query::limit($batchSize), From 22abde7ade5e1bdc4b11d1c4f4560650056a0d76 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 1 Oct 2024 17:34:42 +0900 Subject: [PATCH 055/103] CodeQL --- src/Database/Adapter/MariaDB.php | 7 +------ src/Database/Adapter/Postgres.php | 7 +------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 3649b63da..ab9254afc 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1652,12 +1652,7 @@ public function deleteDocuments(string $collection, array $ids): bool $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; - $sqlWhere = !empty($where) ? 'WHERE ' . \implode(' AND ', $where) : ''; - - $sql = " - DELETE FROM {$this->getSQLTable($name)} - {$sqlWhere}; - "; + $sql = "DELETE FROM {$this->getSQLTable($name)} WHERE " . \implode(' AND ', $where); $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index cc5ccce6c..8c667dce5 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1577,12 +1577,7 @@ public function deleteDocuments(string $collection, array $ids): bool $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; - $sqlWhere = !empty($where) ? 'WHERE ' . \implode(' AND ', $where) : ''; - - $sql = " - DELETE FROM {$this->getSQLTable($name)} - {$sqlWhere}; - "; + $sql = "DELETE FROM {$this->getSQLTable($name)} WHERE " . \implode(' AND ', $where); $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); From 19e6029edf64d1fe777165f902865b7064b9a850 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 2 Oct 2024 12:28:58 +0900 Subject: [PATCH 056/103] Continue to add more tests --- src/Database/Adapter/MariaDB.php | 4 ++ src/Database/Adapter/Postgres.php | 4 ++ tests/e2e/Adapter/Base.php | 71 +++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index ab9254afc..4788c67fc 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1642,6 +1642,10 @@ public function deleteDocument(string $collection, string $id): bool */ public function deleteDocuments(string $collection, array $ids): bool { + if (empty($ids)) { + return true; + } + try { $name = $this->filter($collection); $where = []; diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8c667dce5..437c44914 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1567,6 +1567,10 @@ public function deleteDocument(string $collection, string $id): bool */ public function deleteDocuments(string $collection, array $ids): bool { + if (empty($ids)) { + return true; + } + try { $name = $this->filter($collection); $where = []; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index d155e338c..66aa4290b 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15742,7 +15742,78 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); + $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person1->getAttribute('bulk_delete_library'); + $this->assertEquals('library1', $library['$id']); + $this->assertArrayNotHasKey('bulk_delete_person', $library); + + $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + + $this->getDatabase()->deleteDocuments('bulk_delete_library'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person')); + + $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person->getAttribute('bulk_delete_library'); + $this->assertNull($library); + + // NULL - Cleanup + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); + // Cascade + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person', + relatedCollection: 'bulk_delete_library', + type: Database::RELATION_ONE_TO_ONE, + onDelete: Database::RELATION_MUTATE_CASCADE + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library' => [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person1->getAttribute('bulk_delete_library'); + $this->assertEquals('library1', $library['$id']); + $this->assertArrayNotHasKey('bulk_delete_person', $library); + + $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + + $this->getDatabase()->deleteDocuments('bulk_delete_library'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person')); + + $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person->getAttribute('bulk_delete_library'); + $this->assertEmpty($library); + $this->assertNotNull($library); + + // Cascade - Cleanup + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); } public function testEvents(): void From d3264dcae23f55d344ce2db4ae8d3a84103b5235 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 2 Oct 2024 12:45:38 +0900 Subject: [PATCH 057/103] Fix Cascade --- src/Database/Database.php | 2 +- tests/e2e/Adapter/Base.php | 48 +++++++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 1cacdf3f6..7116c9740 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4895,7 +4895,7 @@ private function deleteCascade(Document $collection, Document $relatedCollection $this->deleteDocument( $relatedCollection->getId(), - $value->getId() + ($value instanceof Document) ? $value->getId() : $value ); \array_pop($this->relationshipDeleteStack); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 66aa4290b..6851db6e2 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15712,13 +15712,11 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); $this->getDatabase()->deleteDocuments('bulk_delete_library'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); // NULL - $this->getDatabase()->createRelationship( + $this->getDatabase()->updateRelationship( collection: 'bulk_delete_person', - relatedCollection: 'bulk_delete_library', - type: Database::RELATION_ONE_TO_ONE, + id: 'bulk_delete_library', onDelete: Database::RELATION_MUTATE_SET_NULL ); @@ -15762,13 +15760,11 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); $this->getDatabase()->deleteDocuments('bulk_delete_library'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); // Cascade - $this->getDatabase()->createRelationship( + $this->getDatabase()->updateRelationship( collection: 'bulk_delete_person', - relatedCollection: 'bulk_delete_library', - type: Database::RELATION_ONE_TO_ONE, + id: 'bulk_delete_library', onDelete: Database::RELATION_MUTATE_CASCADE ); @@ -15808,12 +15804,42 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void $this->assertEmpty($library); $this->assertNotNull($library); - // Cascade - Cleanup + // Test Bulk delete parent + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library' => [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $library = $person1->getAttribute('bulk_delete_library'); + $this->assertEquals('library1', $library['$id']); + $this->assertArrayNotHasKey('bulk_delete_person', $library); + $this->getDatabase()->deleteDocuments('bulk_delete_person'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - $this->assertTrue($this->getDatabase()->deleteRelationship('bulk_delete_person', 'bulk_delete_library')); + + $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library'); } public function testEvents(): void From 1241b0ac6c20c530429408b1fa41b207a650fe9f Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 2 Oct 2024 12:48:49 +0900 Subject: [PATCH 058/103] Run Linter --- docker-compose.yml | 2 +- tests/e2e/Adapter/Base.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 23b135ba9..5497f4e28 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: . args: - DEBUG: false + DEBUG: true networks: - database volumes: diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 6851db6e2..e0ef94059 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15760,7 +15760,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); $this->getDatabase()->deleteDocuments('bulk_delete_library'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - + // Cascade $this->getDatabase()->updateRelationship( collection: 'bulk_delete_person', From becd847b03c114a03c7e16b5247d31072b4efc0a Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 4 Oct 2024 13:53:21 +0900 Subject: [PATCH 059/103] Fix sizeOfDisk tests --- src/Database/Adapter.php | 8 ++++ src/Database/Adapter/MariaDB.php | 2 +- tests/e2e/Adapter/Base.php | 63 ++++++++++---------------------- 3 files changed, 28 insertions(+), 45 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 9a6558b19..951213f2c 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -966,4 +966,12 @@ public function clearTimeout(string $event): void // Clear existing callback $this->before($event, 'timeout', null); } + + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + abstract public function analyzeCollection(string $collection): bool; } diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index bcff516e1..df05e99a2 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -262,7 +262,7 @@ public function getSizeOfCollection(string $collection): int $collectionSize = $this->getPDO()->prepare(" SELECT SUM(data_length + index_length) - FROM INFORMATION_SCHEMA.TABLES + FROM INFORMATION_SCHEMA.TABLES WHERE table_name = :name AND table_schema = :database "); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 2b8484376..952f0eada 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1045,26 +1045,32 @@ public function testCreateListExistsDeleteCollection(): void public function testSizeCollection(): void { - $this->getDatabase()->createCollection('sizeTest1'); - $this->getDatabase()->createCollection('sizeTest2'); + static::getDatabase()->createCollection('sizeTest1'); + static::getDatabase()->createCollection('sizeTest2'); - $size1 = $this->getDatabase()->getSizeOfCollection('sizeTest1'); - $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + $size1 = static::getDatabase()->getSizeOfCollection('sizeTest1'); + $size2 = static::getDatabase()->getSizeOfCollection('sizeTest2'); $sizeDifference = abs($size1 - $size2); // Size of an empty collection returns either 172032 or 167936 bytes randomly // Therefore asserting with a tolerance of 5000 bytes $byteDifference = 5000; + + if (!static::getDatabase()->analyzeCollection('sizeTest2')) { + $this->expectNotToPerformAssertions(); + return; + } + $this->assertLessThan($byteDifference, $sizeDifference); - $this->getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 20000, true); - $this->getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + static::getDatabase()->createAttribute('sizeTest2', 'string1', Database::VAR_STRING, 20000, true); + static::getDatabase()->createAttribute('sizeTest2', 'string2', Database::VAR_STRING, 254 + 1, true); + static::getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); + static::getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 100; for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->createDocument('sizeTest2', new Document([ + static::getDatabase()->createDocument('sizeTest2', new Document([ '$id' => 'doc' . $i, 'string1' => 'string1' . $i . str_repeat('A', 10000), 'string2' => 'string2', @@ -1074,26 +1080,9 @@ public function testSizeCollection(): void static::getDatabase()->analyzeCollection('sizeTest2'); - sleep(5); // Let DB analyze - $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertGreaterThan($size1, $size2); - - self::$authorization->skip(function () use ($loopCount) { - for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); - } - }); - - static::getDatabase()->analyzeCollection('sizeTest2'); - sleep(5); // Let DB clean up - - $size3 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); - - var_dump($size1, $size2, $size3); - - $this->assertLessThan($size2, $size3); } public function testSizeCollectionOnDisk(): void @@ -1118,29 +1107,15 @@ public function testSizeCollectionOnDisk(): void for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->createDocument('sizeTestDisk2', new Document([ - '$id' => 'doc' . $i, - 'string1' => 'string1' . $i . str_repeat('A', 10000), - 'string2' => 'string2', - 'string3' => 'string3', + 'string1' => 'string1' . $i, + 'string2' => 'string2' . $i, + 'string3' => 'string3' . $i, ])); } - $this->getDatabase()->analyzeCollection('sizeTestDisk2'); - $size2 = $this->getDatabase()->getSizeOfCollection('sizeTestDisk2'); + $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); $this->assertGreaterThan($size1, $size2); - - self::$authorization->skip(function () use ($loopCount) { - for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->deleteDocument('sizeTestDisk2', 'doc' . $i); - } - }); - - sleep(10); // Let DB clean up - - $size3 = $this->getDatabase()->getSizeOfCollection('sizeTestDisk2'); - - $this->assertLessThan($size2, $size3); } public function testSizeFullText(): void From e6eae09eeb40ed9fcd3204024e558d611f7966a5 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 4 Oct 2024 17:00:25 +0900 Subject: [PATCH 060/103] Remove unnecessary cleanup --- tests/e2e/Adapter/Base.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index e0ef94059..b4162b9f0 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15836,10 +15836,6 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void $this->getDatabase()->deleteDocuments('bulk_delete_person'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - - $this->getDatabase()->deleteDocuments('bulk_delete_person'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); } public function testEvents(): void From f1a9eb5ebf9a2dc7adcc2d314781af29beefcc9b Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 4 Oct 2024 17:02:05 +0900 Subject: [PATCH 061/103] Disable debug in compose file --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5497f4e28..23b135ba9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: . args: - DEBUG: true + DEBUG: false networks: - database volumes: From 794b845f030c53df88d2fa715990a530d1b15588 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 7 Oct 2024 11:11:24 +0900 Subject: [PATCH 062/103] Sync findOne style from 0.53 to main --- src/Database/Database.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index e575785ac..992d175bf 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -5213,9 +5213,9 @@ public function findOne(string $collection, array $queries = []): Document if (!$found) { return new Document(); - } else { - return $found; } + + return $found; } /** From ce3c916acd80e66f4633b108eeda30280b168081 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Mon, 7 Oct 2024 14:20:36 -0400 Subject: [PATCH 063/103] chore: merge --- src/Database/Adapter.php | 9 ------- src/Database/Adapter/MariaDB.php | 44 -------------------------------- src/Database/Adapter/Mongo.php | 11 -------- src/Database/Adapter/SQLite.php | 39 ---------------------------- src/Database/Database.php | 26 ------------------- tests/e2e/Adapter/Base.php | 23 +---------------- 6 files changed, 1 insertion(+), 151 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index e357357e3..a496238bd 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -658,15 +658,6 @@ abstract public function sum(string $collection, string $attribute, array $queri */ abstract public function count(string $collection, array $queries = [], ?int $max = null): int; - /** - * Get Collection Size on the disk - * - * @param string $collection - * @return int - * @throws DatabaseException - */ - abstract public function getSizeOfCollectionOnDisk(string $collection): int; - /** * Get Collection Size of the raw data * diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index c5dc5ba14..045000813 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -246,50 +246,6 @@ public function getSizeOfCollectionOnDisk(string $collection): int return $size; } - /** - * Get Collection Size of the raw data - * - * @param string $collection - * @return int - * @throws DatabaseException - */ - public function getSizeOfCollection(string $collection): int - { - $collection = $this->filter($collection); - $collection = $this->getNamespace() . '_' . $collection; - $database = $this->getDatabase(); - $permissions = $collection . '_perms'; - - $collectionSize = $this->getPDO()->prepare(" - SELECT SUM(data_length + index_length) - FROM INFORMATION_SCHEMA.TABLES - WHERE table_name = :name AND - table_schema = :database - "); - - $permissionsSize = $this->getPDO()->prepare(" - SELECT SUM(data_length + index_length) - FROM INFORMATION_SCHEMA.TABLES - WHERE table_name = :permissions AND - table_schema = :database - "); - - $collectionSize->bindParam(':name', $collection); - $collectionSize->bindParam(':database', $database); - $permissionsSize->bindParam(':permissions', $permissions); - $permissionsSize->bindParam(':database', $database); - - try { - $collectionSize->execute(); - $permissionsSize->execute(); - $size = $collectionSize->fetchColumn() + $permissionsSize->fetchColumn(); - } catch (PDOException $e) { - throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); - } - - return $size; - } - /** * Get Collection Size of the raw data * diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index e0314c50b..1d7dd8b85 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -306,17 +306,6 @@ public function getSizeOfCollection(string $collection): int } } - /** - * Get Collection Size on disk - * @param string $collection - * @return int - * @throws DatabaseException - */ - public function getSizeOfCollectionOnDisk(string $collection): int - { - return $this->getSizeOfCollection($collection); - } - /** * Delete Collection * diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 73af5fac8..6165e139b 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -187,45 +187,6 @@ public function createCollection(string $name, array $attributes = [], array $in return true; } - /** - * Get Collection Size on disk - * @param string $collection - * @return int - * @throws DatabaseException - * - */ - public function getSizeOfCollectionOnDisk(string $collection): int - { - $collection = $this->filter($collection); - $namespace = $this->getNamespace(); - $name = $namespace . '_' . $collection; - $permissions = $namespace . '_' . $collection . '_perms'; - - $collectionSize = $this->getPDO()->prepare(" - SELECT SUM(\"pgsize\") - FROM \"dbstat\" - WHERE name = :name; - "); - - $permissionsSize = $this->getPDO()->prepare(" - SELECT SUM(\"pgsize\") - FROM \"dbstat\" - WHERE name = :name; - "); - - $collectionSize->bindParam(':name', $name); - $permissionsSize->bindParam(':name', $permissions); - - try { - $collectionSize->execute(); - $permissionsSize->execute(); - $size = $collectionSize->fetchColumn() + $permissionsSize->fetchColumn(); - } catch (PDOException $e) { - throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); - } - - return $size; - } /** * Get Collection Size of raw data diff --git a/src/Database/Database.php b/src/Database/Database.php index d02007a75..f47df72c7 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -1291,32 +1291,6 @@ public function getSizeOfCollection(string $collection): int return $this->adapter->getSizeOfCollection($collection->getId()); } - /** - * Get Collection Size on disk - * - * @param string $collection - * - * @return int - */ - public function getSizeOfCollectionOnDisk(string $collection): int - { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - - $collection = $this->silent(fn () => $this->getCollection($collection)); - - if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); - } - - if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); - } - - return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); - } - /** * Delete Collection * diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 90cb71a56..c242f1f40 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1085,7 +1085,7 @@ public function testSizeCollection(): void $this->assertGreaterThan($size1, $size2); - $self::$authorization::skip(function () use ($loopCount) { + self::$authorization->skip(function () use ($loopCount) { for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); } @@ -1100,27 +1100,6 @@ public function testSizeCollection(): void $this->assertLessThan($size2, $size3); } - public function testSizeCollectionOnDisk(): void - { - $this->getDatabase()->createCollection('sizeTestDisk1'); - $this->getDatabase()->createCollection('sizeTestDisk2'); - - $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk1'); - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); - $sizeDifference = abs($size1 - $size2); - // Size of an empty collection returns either 172032 or 167936 bytes randomly - // Therefore asserting with a tolerance of 5000 bytes - $byteDifference = 5000; - $this->assertLessThan($byteDifference, $sizeDifference); - - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string1', Database::VAR_STRING, 20000, true); - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string2', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string3', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createIndex('sizeTestDisk2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); - - $loopCount = 40; - } - public function testSizeCollectionOnDisk(): void { $this->getDatabase()->createCollection('sizeTestDisk1'); From e5ace7933176e07d876ab991687ec6c84fddb220 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Mon, 7 Oct 2024 14:21:33 -0400 Subject: [PATCH 064/103] chore: package update --- composer.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.lock b/composer.lock index 2490075e9..6f14f0fca 100644 --- a/composer.lock +++ b/composer.lock @@ -738,16 +738,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.19.2", + "version": "v4.19.4", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "0ed4c8949a32986043e977dbe14776c14d644c45" + "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/0ed4c8949a32986043e977dbe14776c14d644c45", - "reference": "0ed4c8949a32986043e977dbe14776c14d644c45", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/715f4d25e225bc47b293a8b997fe6ce99bf987d2", + "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2", "shasum": "" }, "require": { @@ -756,7 +756,7 @@ }, "require-dev": { "ircmaxell/php-yacc": "^0.0.7", - "phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0" + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" }, "bin": [ "bin/php-parse" @@ -788,9 +788,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.2" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.4" }, - "time": "2024-09-17T19:36:00+00:00" + "time": "2024-09-29T15:01:53+00:00" }, { "name": "pcov/clobber", From b2e2681daf8f479c1d26b5be3eb61a80df40209b Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Mon, 7 Oct 2024 14:22:23 -0400 Subject: [PATCH 065/103] chore: format --- src/Database/Adapter/Mongo.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 1d7dd8b85..14186b193 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -301,7 +301,7 @@ public function getSizeOfCollection(string $collection): int } else { throw new DatabaseException('No size found'); } - } catch(Exception $e) { + } catch (Exception $e) { throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); } } From ed5227cf05f5bdb28cfe4200a3b77031d68239d5 Mon Sep 17 00:00:00 2001 From: Binyamin Yawitz <316103+byawitz@users.noreply.github.com> Date: Mon, 7 Oct 2024 14:42:07 -0400 Subject: [PATCH 066/103] fix: review --- src/Database/Adapter/Postgres.php | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 6bc863e99..d7a6c0177 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -2267,20 +2267,15 @@ public function getLikeOperator(): string return 'ILIKE'; } + /** - * Analyze a collection updating it's metadata on the database. - * This Locks the table and should be avoided if possible + * Analyze a collection updating it's metadata on the database engine * * @param string $collection * @return bool */ public function analyzeCollection(string $collection): bool { - $name = $this->filter($collection); - - $sql = "ANALYZE {$this->getSQLTable($name)}"; - - $stmt = $this->getPDO()->prepare($sql); - return $stmt->execute(); + return false; } } From 09a217ff41fd9c26bc1e6e5e68984eb8db92ebc1 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 9 Oct 2024 15:32:38 +0900 Subject: [PATCH 067/103] Continue work on batch updates --- composer.lock | 18 +- src/Database/Adapter.php | 10 +- src/Database/Adapter/MariaDB.php | 287 ++++---------------- src/Database/Adapter/Mongo.php | 30 +- src/Database/Adapter/Postgres.php | 247 +---------------- src/Database/Adapter/SQLite.php | 252 +---------------- src/Database/Database.php | 121 +++++---- src/Database/Validator/PartialStructure.php | 284 +++++++++++++++++++ src/Database/Validator/Structure.php | 131 +++++++++ tests/e2e/Adapter/Base.php | 108 ++++---- 10 files changed, 636 insertions(+), 852 deletions(-) create mode 100644 src/Database/Validator/PartialStructure.php diff --git a/composer.lock b/composer.lock index 2490075e9..2ad152cc9 100644 --- a/composer.lock +++ b/composer.lock @@ -738,16 +738,16 @@ }, { "name": "nikic/php-parser", - "version": "v4.19.2", + "version": "v4.19.4", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "0ed4c8949a32986043e977dbe14776c14d644c45" + "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/0ed4c8949a32986043e977dbe14776c14d644c45", - "reference": "0ed4c8949a32986043e977dbe14776c14d644c45", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/715f4d25e225bc47b293a8b997fe6ce99bf987d2", + "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2", "shasum": "" }, "require": { @@ -756,7 +756,7 @@ }, "require-dev": { "ircmaxell/php-yacc": "^0.0.7", - "phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0" + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" }, "bin": [ "bin/php-parse" @@ -788,9 +788,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.2" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.4" }, - "time": "2024-09-17T19:36:00+00:00" + "time": "2024-09-29T15:01:53+00:00" }, { "name": "pcov/clobber", @@ -2689,7 +2689,7 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": {}, "prefer-stable": false, "prefer-lowest": false, "platform": { @@ -2697,6 +2697,6 @@ "ext-mbstring": "*", "php": ">=8.0" }, - "platform-dev": [], + "platform-dev": {}, "plugin-api-version": "2.6.0" } diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 951213f2c..34c84a9a1 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -595,17 +595,17 @@ abstract public function createDocuments(string $collection, array $documents, i abstract public function updateDocument(string $collection, Document $document): Document; /** - * Update Documents in batches + * Batch update documents * * @param string $collection - * @param array $documents - * @param int $batchSize + * @param Document $update + * @param array $queries * - * @return array + * @return bool * * @throws DatabaseException */ - abstract public function updateDocuments(string $collection, array $documents, int $batchSize): array; + abstract public function updateDocuments(string $collection, Document $update, array $queries): bool; /** * Delete Document diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index df05e99a2..0aeed6182 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1303,260 +1303,87 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Update Documents in batches + * Batch update documents * * @param string $collection - * @param array $documents - * @param int $batchSize + * @param Document $update + * @param array $queries * - * @return array + * @return bool * - * @throws DuplicateException - * @throws \Throwable + * @throws DatabaseException */ - public function updateDocuments(string $collection, array $documents, int $batchSize = Database::INSERT_BATCH_SIZE): array + public function updateDocuments(string $collection, Document $update, array $queries): bool { - if (empty($documents)) { - return $documents; - } - - try { - $name = $this->filter($collection); - $batches = \array_chunk($documents, max(1, $batchSize)); - - foreach ($batches as $batch) { - $bindIndex = 0; - $batchKeys = []; - $bindValues = []; - - $removeQuery = ''; - $removeBindValues = []; - - $addQuery = ''; - $addBindValues = []; - /* @var $document Document */ - foreach ($batch as $index => $document) { - $attributes = $document->getAttributes(); - $attributes['_uid'] = $document->getId(); - $attributes['_createdAt'] = $document->getCreatedAt(); - $attributes['_updatedAt'] = $document->getUpdatedAt(); - $attributes['_permissions'] = json_encode($document->getPermissions()); - - if ($this->sharedTables) { - $attributes['_tenant'] = $this->tenant; - } - - $columns = \array_map(function ($attribute) { - return "`" . $this->filter($attribute) . "`"; - }, \array_keys($attributes)); - - $bindKeys = []; - - foreach ($attributes as $value) { - if (\is_array($value)) { - $value = json_encode($value); - } - $value = (is_bool($value)) ? (int)$value : $value; - $bindKey = 'key_' . $bindIndex; - $bindKeys[] = ':' . $bindKey; - $bindValues[$bindKey] = $value; - $bindIndex++; - } - - $batchKeys[] = '(' . implode(', ', $bindKeys) . ')'; - - // Permissions logic - $sql = " - SELECT _type, _permission - FROM {$this->getSQLTable($name . '_perms')} - WHERE _document = :_uid - "; - - if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; - } - - $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); - - $permissionsStmt = $this->getPDO()->prepare($sql); - $permissionsStmt->bindValue(':_uid', $document->getId()); - - if ($this->sharedTables) { - $permissionsStmt->bindValue(':_tenant', $this->tenant); - } - - $permissionsStmt->execute(); - $permissions = $permissionsStmt->fetchAll(); - - $initial = []; - foreach (Database::PERMISSIONS as $type) { - $initial[$type] = []; - } - - $permissions = \array_reduce($permissions, function (array $carry, array $item) { - $carry[$item['_type']][] = $item['_permission']; - return $carry; - }, $initial); - - // Get removed Permissions - $removals = []; - foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $document->getPermissionsByType($type)); - if (!empty($diff)) { - $removals[$type] = $diff; - } - } - - // Build inner query to remove permissions - if (!empty($removals)) { - foreach ($removals as $type => $permissionsToRemove) { - $bindKey = 'uid_' . $index; - $removeBindKeys[] = ':uid_' . $index; - $removeBindValues[$bindKey] = $document->getId(); - - $tenantQuery = ''; - if ($this->sharedTables) { - $tenantQuery = ' AND _tenant = :_tenant'; - } - - $removeQuery .= "( - _document = :uid_{$index} - {$tenantQuery} - AND _type = '{$type}' - AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { - $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; - $removeBindKeys[] = ':' . $bindKey; - $removeBindValues[$bindKey] = $permissionsToRemove[$i]; - - return ':' . $bindKey; - }, \array_keys($permissionsToRemove))) . - ") - )"; - - if ($type !== \array_key_last($removals)) { - $removeQuery .= ' OR '; - } - } - - if ($index !== \array_key_last($batch)) { - $removeQuery .= ' OR '; - } - } - - // Get added Permissions - $additions = []; - foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($document->getPermissionsByType($type), $permissions[$type]); - if (!empty($diff)) { - $additions[$type] = $diff; - } - } - - // Build inner query to add permissions - if (!empty($additions)) { - foreach ($additions as $type => $permissionsToAdd) { - foreach ($permissionsToAdd as $i => $permission) { - $bindKey = 'uid_' . $index; - $addBindValues[$bindKey] = $document->getId(); - - $bindKey = 'add_' . $type . '_' . $index . '_' . $i; - $addBindValues[$bindKey] = $permission; - - $addQuery .= "(:uid_{$index}, '{$type}', :{$bindKey}"; - - if ($this->sharedTables) { - $addQuery .= ", :_tenant)"; - } else { - $addQuery .= ")"; - } + $attributes = $update->getAttributes(); - if ($i !== \array_key_last($permissionsToAdd) || $type !== \array_key_last($additions)) { - $addQuery .= ', '; - } - } - } - if ($index !== \array_key_last($batch)) { - $addQuery .= ', '; - } - } - } + if (empty($attributes)) { + return true; + } - $updateClause = ''; - for ($i = 0; $i < \count($columns); $i++) { - $column = $columns[$i]; - if (!empty($updateClause)) { - $updateClause .= ', '; - } - $updateClause .= "{$column} = VALUES({$column})"; - } + $name = $this->filter($collection); + $columns = ''; - $stmt = $this->getPDO()->prepare(" - INSERT INTO {$this->getSQLTable($name)} (" . \implode(", ", $columns) . ") - VALUES " . \implode(', ', $batchKeys) . " - ON DUPLICATE KEY UPDATE $updateClause - "); + $where = []; - foreach ($bindValues as $key => $value) { - $stmt->bindValue($key, $value, $this->getPDOType($value)); - } + $queries = array_map(fn ($query) => clone $query, $queries); - $stmt->execute(); + $conditions = $this->getSQLConditions($queries); + if (!empty($conditions)) { + $where[] = $conditions; + } - if (!empty($removeQuery)) { - $stmtRemovePermissions = $this->getPDO()->prepare(" - DELETE - FROM {$this->getSQLTable($name . '_perms')} - WHERE ({$removeQuery}) - "); + if ($this->sharedTables) { + $where[] = "table_main._tenant = :_tenant"; + } - foreach ($removeBindValues as $key => $value) { - $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); - } - if ($this->sharedTables) { - $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); - } - $stmtRemovePermissions->execute(); - } + $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; - if (!empty($addQuery)) { - $sqlAddPermissions = " - INSERT INTO {$this->getSQLTable($name . '_perms')} (`_document`, `_type`, `_permission` - "; + $bindIndex = 0; + foreach ($attributes as $attribute => $value) { + $column = $this->filter($attribute); + $bindKey = 'key_' . $bindIndex; + $columns .= "`{$column}`" . '=:' . $bindKey; - if ($this->sharedTables) { - $sqlAddPermissions .= ', `_tenant`)'; - } else { - $sqlAddPermissions .= ')'; - } + if ($bindIndex > 0) { + $columns .= ','; + } - $sqlAddPermissions .= " VALUES {$addQuery}"; + $bindIndex++; + } - $stmtAddPermissions = $this->getPDO()->prepare($sqlAddPermissions); + $sql = " + UPDATE {$this->getSQLTable($name)} + SET {$columns} + {$sqlWhere} + "; + + $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); + $stmt = $this->getPDO()->prepare($sql); - foreach ($addBindValues as $key => $value) { - $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); - } + foreach ($queries as $query) { + $this->bindConditionValue($stmt, $query); + } - if ($this->sharedTables) { - $stmtAddPermissions->bindValue(':_tenant', $this->tenant); - } + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } - $stmtAddPermissions->execute(); - } - } - } catch (\Throwable $e) { - if ($e instanceof PDOException) { - switch ($e->getCode()) { - case 1062: - case 23000: - throw new DuplicateException('Duplicated document: ' . $e->getMessage(), previous: $e); - } + $attributeIndex = 0; + foreach ($attributes as $attribute => $value) { + if (is_array($value)) { + $value = json_encode($value); } - throw $e; + $bindKey = 'key_' . $attributeIndex; + $value = (is_bool($value)) ? (int)$value : $value; + $stmt->bindValue(':' . $bindKey, $value, $this->getPDOType($value)); + $attributeIndex++; } - return $documents; + $stmt->execute(); + + return true; } /** diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index fc2eb009a..28d6bf9f9 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -820,35 +820,19 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Update Documents in batches + * Batch update documents * * @param string $collection - * @param array $documents - * @param int $batchSize + * @param Document $update + * @param array $queries * - * @return array + * @return bool * - * @throws Duplicate + * @throws DatabaseException */ - public function updateDocuments(string $collection, array $documents, int $batchSize): array + public function updateDocuments(string $collection, Document $update, array $queries): bool { - $name = $this->getNamespace() . '_' . $this->filter($collection); - - foreach ($documents as $index => $document) { - $document = $document->getArrayCopy(); - $document = $this->replaceChars('$', '_', $document); - $document = $this->timeToMongo($document); - - $filters = []; - $filters['_uid'] = $document['_uid']; - if ($this->sharedTables) { - $filters['_tenant'] = (string)$this->getTenant(); - } - - $this->client->update($name, $filters, $document); - } - - return $documents; + throw new Exception('Not implemented'); } /** diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 6d40898b4..6942f0dfb 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1226,252 +1226,19 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Update Documents in batches + * Batch update documents * * @param string $collection - * @param array $documents - * @param int $batchSize + * @param Document $update + * @param array $queries * - * @return array + * @return bool * - * @throws Duplicate + * @throws DatabaseException */ - public function updateDocuments(string $collection, array $documents, int $batchSize = Database::INSERT_BATCH_SIZE): array + public function updateDocuments(string $collection, Document $update, array $queries): bool { - if (empty($documents)) { - return $documents; - } - - try { - $name = $this->filter($collection); - $batches = \array_chunk($documents, max(1, $batchSize)); - - foreach ($batches as $batch) { - $bindIndex = 0; - $batchKeys = []; - $bindValues = []; - - $removeQuery = ''; - $removeBindValues = []; - - $addQuery = ''; - $addBindValues = []; - - foreach ($batch as $index => $document) { - $attributes = $document->getAttributes(); - $attributes['_uid'] = $document->getId(); - $attributes['_createdAt'] = $document->getCreatedAt(); - $attributes['_updatedAt'] = $document->getUpdatedAt(); - $attributes['_permissions'] = json_encode($document->getPermissions()); - - if ($this->sharedTables) { - $attributes['_tenant'] = $this->tenant; - } - - $columns = \array_map(function ($attribute) { - return '"' . $this->filter($attribute) . '"'; - }, \array_keys($attributes)); - - $bindKeys = []; - - foreach ($attributes as $value) { - if (\is_array($value)) { - $value = json_encode($value); - } - $value = (is_bool($value)) ? (int)$value : $value; - $bindKey = 'key_' . $bindIndex; - $bindKeys[] = ':' . $bindKey; - $bindValues[$bindKey] = $value; - $bindIndex++; - } - - $batchKeys[] = '(' . implode(', ', $bindKeys) . ')'; - - // Permissions logic - $sql = " - SELECT _type, _permission - FROM {$this->getSQLTable($name . '_perms')} - WHERE _document = :_uid - "; - - if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; - } - - $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); - - $permissionsStmt = $this->getPDO()->prepare($sql); - $permissionsStmt->bindValue(':_uid', $document->getId()); - - if ($this->sharedTables) { - $permissionsStmt->bindValue(':_tenant', $this->tenant); - } - - $permissionsStmt->execute(); - $permissions = $permissionsStmt->fetchAll(); - - $initial = []; - foreach (Database::PERMISSIONS as $type) { - $initial[$type] = []; - } - - $permissions = \array_reduce($permissions, function (array $carry, array $item) { - $carry[$item['_type']][] = $item['_permission']; - return $carry; - }, $initial); - - // Get removed Permissions - $removals = []; - foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $document->getPermissionsByType($type)); - if (!empty($diff)) { - $removals[$type] = $diff; - } - } - - // Build inner query to remove permissions - if (!empty($removals)) { - foreach ($removals as $type => $permissionsToRemove) { - $bindKey = 'uid_' . $index; - $removeBindKeys[] = ':uid_' . $index; - $removeBindValues[$bindKey] = $document->getId(); - - $tenantQuery = ''; - if ($this->sharedTables) { - $tenantQuery = ' AND _tenant = :_tenant'; - } - - $removeQuery .= "( - _document = :uid_{$index} - {$tenantQuery} - AND _type = '{$type}' - AND _permission IN (" . implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { - $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; - $removeBindKeys[] = ':' . $bindKey; - $removeBindValues[$bindKey] = $permissionsToRemove[$i]; - - return ':' . $bindKey; - }, \array_keys($permissionsToRemove))) . - ") - )"; - - if ($type !== \array_key_last($removals)) { - $removeQuery .= ' OR '; - } - } - - if ($index !== \array_key_last($batch)) { - $removeQuery .= ' OR '; - } - } - - // Get added Permissions - $additions = []; - foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($document->getPermissionsByType($type), $permissions[$type]); - if (!empty($diff)) { - $additions[$type] = $diff; - } - } - - // Build inner query to add permissions - if (!empty($additions)) { - foreach ($additions as $type => $permissionsToAdd) { - foreach ($permissionsToAdd as $i => $permission) { - $bindKey = 'uid_' . $index; - $addBindValues[$bindKey] = $document->getId(); - - $bindKey = 'add_' . $type . '_' . $index . '_' . $i; - $addBindValues[$bindKey] = $permission; - - $tenantQuery = $this->sharedTables ? ', :_tenant' : ''; - - $addQuery .= "(:uid_{$index}, '{$type}', :{$bindKey} {$tenantQuery})"; - - if ($i !== \array_key_last($permissionsToAdd) || $type !== \array_key_last($additions)) { - $addQuery .= ', '; - } - } - } - if ($index !== \array_key_last($batch)) { - $addQuery .= ', '; - } - } - } - - $updateClause = ''; - for ($i = 0; $i < \count($columns); $i++) { - $column = $columns[$i]; - if (!empty($updateClause)) { - $updateClause .= ', '; - } - $updateClause .= "{$column} = excluded.{$column}"; - } - - $sql = " - INSERT INTO {$this->getSQLTable($name)} (" . \implode(", ", $columns) . ") - VALUES " . \implode(', ', $batchKeys) . " - "; - - if ($this->sharedTables) { - $sql .= "ON CONFLICT (_tenant, LOWER(_uid)) DO UPDATE SET $updateClause"; - } else { - $sql .= "ON CONFLICT (LOWER(_uid)) DO UPDATE SET $updateClause"; - } - - $stmt = $this->getPDO()->prepare($sql); - - foreach ($bindValues as $key => $value) { - $stmt->bindValue($key, $value, $this->getPDOType($value)); - } - - $stmt->execute(); - - if (!empty($removeQuery)) { - $stmtRemovePermissions = $this->getPDO()->prepare(" - DELETE - FROM {$this->getSQLTable($name . '_perms')} - WHERE ({$removeQuery}) - "); - - foreach ($removeBindValues as $key => $value) { - $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); - } - if ($this->sharedTables) { - $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); - } - - $stmtRemovePermissions->execute(); - } - - if (!empty($addQuery)) { - $tenantQuery = $this->sharedTables ? ', _tenant' : ''; - - $stmtAddPermissions = $this->getPDO()->prepare(" - INSERT INTO {$this->getSQLTable($name . '_perms')} (_document, _type, _permission {$tenantQuery}) - VALUES {$addQuery} - "); - - foreach ($addBindValues as $key => $value) { - $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); - } - - if ($this->sharedTables) { - $stmtAddPermissions->bindValue(':_tenant', $this->tenant); - } - - $stmtAddPermissions->execute(); - } - } - - return $documents; - } catch (PDOException $e) { - - throw match ($e->getCode()) { - 1062, 23000 => new Duplicate('Duplicated document: ' . $e->getMessage()), - default => $e, - }; - } + throw new Exception('Not implemented'); } /** diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index e52ccf68d..062bd42d6 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -816,257 +816,19 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Update Documents in batches + * Batch update documents * * @param string $collection - * @param array $documents - * @param int $batchSize + * @param Document $update + * @param array $queries * - * @return array + * @return bool * - * @throws Duplicate + * @throws DatabaseException */ - public function updateDocuments(string $collection, array $documents, int $batchSize = Database::INSERT_BATCH_SIZE): array + public function updateDocuments(string $collection, Document $update, array $queries): bool { - if (empty($documents)) { - return $documents; - } - - try { - $name = $this->filter($collection); - $batches = \array_chunk($documents, max(1, $batchSize)); - - foreach ($batches as $batch) { - $bindIndex = 0; - $batchKeys = []; - $bindValues = []; - - $removeQuery = ''; - $removeBindValues = []; - - $addQuery = ''; - $addBindValues = []; - - foreach ($batch as $index => $document) { - $attributes = $document->getAttributes(); - $attributes['_uid'] = $document->getId(); - $attributes['_createdAt'] = $document->getCreatedAt(); - $attributes['_updatedAt'] = $document->getUpdatedAt(); - $attributes['_permissions'] = json_encode($document->getPermissions()); - - if ($this->sharedTables) { - $attributes['_tenant'] = $this->tenant; - } - - $columns = \array_map(function ($attribute) { - return "`" . $this->filter($attribute) . "`"; - }, \array_keys($attributes)); - - $bindKeys = []; - - foreach ($attributes as $value) { - if (\is_array($value)) { - $value = json_encode($value); - } - $value = (is_bool($value)) ? (int)$value : $value; - $bindKey = 'key_' . $bindIndex; - $bindKeys[] = ':' . $bindKey; - $bindValues[$bindKey] = $value; - $bindIndex++; - } - - $batchKeys[] = '(' . implode(', ', $bindKeys) . ')'; - - // Permissions logic - $sql = " - SELECT _type, _permission - FROM {$this->getSQLTable($name . '_perms')} - WHERE _document = :_uid - "; - - if ($this->sharedTables) { - $sql .= " AND _tenant = :_tenant"; - } - - $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); - - /** - * Get current permissions from the database - */ - $permissionsStmt = $this->getPDO()->prepare($sql); - - $permissionsStmt->bindValue(':_uid', $document->getId()); - - if ($this->sharedTables) { - $permissionsStmt->bindValue(':_tenant', $this->tenant); - } - - $permissionsStmt->execute(); - $permissions = $permissionsStmt->fetchAll(); - - $initial = []; - foreach (Database::PERMISSIONS as $type) { - $initial[$type] = []; - } - - $permissions = \array_reduce($permissions, function (array $carry, array $item) { - $carry[$item['_type']][] = $item['_permission']; - return $carry; - }, $initial); - - // Get removed Permissions - $removals = []; - foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $document->getPermissionsByType($type)); - if (!empty($diff)) { - $removals[$type] = $diff; - } - } - - // Build inner query to remove permissions - if (!empty($removals)) { - foreach ($removals as $type => $permissionsToRemove) { - $bindKey = 'uid_' . $index; - $removeBindKeys[] = ':uid_' . $index; - $removeBindValues[$bindKey] = $document->getId(); - - $tenantQuery = ''; - if ($this->sharedTables) { - $tenantQuery = ' AND _tenant = :_tenant'; - } - - $removeQuery .= "( - _document = :uid_{$index} - {$tenantQuery} - AND _type = '{$type}' - AND _permission IN (" . implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { - $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; - $removeBindKeys[] = ':' . $bindKey; - $removeBindValues[$bindKey] = $permissionsToRemove[$i]; - - return ':' . $bindKey; - }, \array_keys($permissionsToRemove))) . - ") - )"; - - if ($type !== \array_key_last($removals)) { - $removeQuery .= ' OR '; - } - } - - if ($index !== \array_key_last($batch)) { - $removeQuery .= ' OR '; - } - } - - // Get added Permissions - $additions = []; - foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($document->getPermissionsByType($type), $permissions[$type]); - if (!empty($diff)) { - $additions[$type] = $diff; - } - } - - // Build inner query to add permissions - if (!empty($additions)) { - foreach ($additions as $type => $permissionsToAdd) { - foreach ($permissionsToAdd as $i => $permission) { - $bindKey = 'uid_' . $index; - $addBindValues[$bindKey] = $document->getId(); - - $bindKey = 'add_' . $type . '_' . $index . '_' . $i; - $addBindValues[$bindKey] = $permission; - - $tenantQuery = $this->sharedTables ? ', :_tenant' : ''; - - $addQuery .= "(:uid_{$index}, '{$type}', :{$bindKey} {$tenantQuery})"; - - if ($i !== \array_key_last($permissionsToAdd) || $type !== \array_key_last($additions)) { - $addQuery .= ', '; - } - } - } - if ($index !== \array_key_last($batch)) { - $addQuery .= ', '; - } - } - } - - $updateClause = ''; - for ($i = 0; $i < \count($columns); $i++) { - $column = $columns[$i]; - if (!empty($updateClause)) { - $updateClause .= ', '; - } - $updateClause .= "{$column} = excluded.{$column}"; - } - - $sql = " - INSERT INTO {$this->getSQLTable($name)} (" . \implode(", ", $columns) . ") - VALUES " . \implode(', ', $batchKeys) . " - - "; - - if ($this->sharedTables) { - $sql .= "ON CONFLICT (_tenant, _uid) DO UPDATE SET $updateClause"; - } else { - $sql .= "ON CONFLICT (_uid) DO UPDATE SET $updateClause"; - } - - $stmt = $this->getPDO()->prepare($sql); - - foreach ($bindValues as $key => $value) { - $stmt->bindValue($key, $value, $this->getPDOType($value)); - } - - $stmt->execute(); - - if (!empty($removeQuery)) { - $stmtRemovePermissions = $this->getPDO()->prepare(" - DELETE - FROM {$this->getSQLTable($name . '_perms')} - WHERE ({$removeQuery}) - "); - - foreach ($removeBindValues as $key => $value) { - $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); - } - - if ($this->sharedTables) { - $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); - } - - $stmtRemovePermissions->execute(); - } - - if (!empty($addQuery)) { - $tenantQuery = $this->sharedTables ? ', _tenant' : ''; - - $stmtAddPermissions = $this->getPDO()->prepare(" - INSERT INTO {$this->getSQLTable($name . '_perms')} (_document, _type, _permission {$tenantQuery}) - VALUES {$addQuery} - "); - - foreach ($addBindValues as $key => $value) { - $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); - } - - if ($this->sharedTables) { - $stmtAddPermissions->bindValue(':_tenant', $this->tenant); - } - - $stmtAddPermissions->execute(); - } - } - - return $documents; - } catch (PDOException $e) { - throw match ($e->getCode()) { - 1062, 23000 => new Duplicate('Duplicated document: ' . $e->getMessage()), - default => $e, - }; - } + throw new Exception('Not implemented'); } /** diff --git a/src/Database/Database.php b/src/Database/Database.php index e575785ac..669214116 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -20,6 +20,7 @@ use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\Authorization\Input; use Utopia\Database\Validator\Index as IndexValidator; +use Utopia\Database\Validator\PartialStructure; use Utopia\Database\Validator\Permissions; use Utopia\Database\Validator\Queries\Document as DocumentValidator; use Utopia\Database\Validator\Queries\Documents as DocumentsValidator; @@ -3884,83 +3885,97 @@ public function updateDocument(string $collection, string $id, Document $documen } /** - * Update Documents in a batch - * + * Batch update documents + * * @param string $collection - * @param array $documents - * @param int $batchSize - * - * @return array - * - * @throws AuthorizationException - * @throws Exception - * @throws StructureException + * @param Document $updates + * @param array $queries + * + * @return bool + * + * @throws DatabaseException */ - public function updateDocuments(string $collection, array $documents, int $batchSize = self::INSERT_BATCH_SIZE): array + public function updateDocuments(string $collection, Document $update, array $queries, int $batchSize = self::INSERT_BATCH_SIZE): bool { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - if (empty($documents)) { - return []; + if (empty($update)) { + return true; } + $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); - $documents = $this->withTransaction(function () use ($collection, $documents, $batchSize) { - $time = DateTime::now(); + // Check new document structure + $validator = new PartialStructure($collection); + if (!$validator->isValid($update)) { + throw new StructureException($validator->getDescription()); + } - foreach ($documents as $key => $document) { - if (!$document->getId()) { - throw new DatabaseException('Must define $id attribute for each document'); - } + $affectedDocumentIds = []; - $updatedAt = $document->getUpdatedAt(); - $document->setAttribute('$updatedAt', empty($updatedAt) || !$this->preserveDates ? $time : $updatedAt); - $document = $this->encode($collection, $document); - - $old = $this->authorization->skip(fn () => $this->silent( - fn () => $this->getDocument( - $collection->getId(), - $document->getId(), - forUpdate: true - ) - )); + $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds, $update) { + $lastDocument = null; + $documentSecurity = $collection->getAttribute('documentSecurity', false); - if ( - $collection->getId() !== self::METADATA - && !$this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $old->getUpdate())) - ) { - throw new AuthorizationException($this->authorization->getDescription()); - } + while (true) { + $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + return $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + )); + }); - $validator = new Structure($collection); - if (!$validator->isValid($document)) { - throw new StructureException($validator->getDescription()); + if (empty($affectedDocuments)) { + break; } - if ($this->resolveRelationships) { - $documents[$key] = $this->silent(fn () => $this->updateDocumentRelationships($collection, $old, $document)); - } - } + $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); + + foreach ($affectedDocuments as $document) { + // Check permissions for document security + if ($collection->getId() !== self::METADATA) { + $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + ...$collection->getUpdate(), + ...($documentSecurity ? $document->getUpdate() : []) + ])); + if (!$isValid) { + throw new AuthorizationException($this->authorization->getDescription()); + } + } - return $this->adapter->updateDocuments($collection->getId(), $documents, $batchSize); - }); + // Update relationship, TODO: Figure out. + if ($this->resolveRelationships) { - foreach ($documents as $key => $document) { - if ($this->resolveRelationships) { - $document = $this->silent(fn () => $this->populateDocumentRelationships($collection, $document)); + } + } + + if (count($affectedDocuments) < $batchSize) { + break; + } else { + $lastDocument = end($affectedDocuments); + } } - $documents[$key] = $this->decode($collection, $document); + $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); - $this->purgeCachedDocument($collection->getId(), $document->getId()); - } + $this->adapter->updateDocuments( + $collection->getId(), + $update, + $queries + ); + }); - $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $documents); + $this->purgeCachedCollection($collection->getId()); - return $documents; + return true; } /** diff --git a/src/Database/Validator/PartialStructure.php b/src/Database/Validator/PartialStructure.php new file mode 100644 index 000000000..0f839857d --- /dev/null +++ b/src/Database/Validator/PartialStructure.php @@ -0,0 +1,284 @@ + + */ + protected static array $formats = []; + + /** + * @var string + */ + protected string $message = 'General Error'; + + /** + * Structure constructor. + * + */ + public function __construct(Document $collection) + { + $this->collection = $collection; + } + + /** + * Remove a Validator + * + * @return array + */ + public static function getFormats(): array + { + return self::$formats; + } + + /** + * Add a new Validator + * Stores a callback and required params to create Validator + * + * @param string $name + * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Http\Validator + * @param string $type Primitive data type for validation + */ + public static function addFormat(string $name, Closure $callback, string $type): void + { + self::$formats[$name] = [ + 'callback' => $callback, + 'type' => $type, + ]; + } + + /** + * Check if validator has been added + * + * @param string $name + * + * @return bool + */ + public static function hasFormat(string $name, string $type): bool + { + if (isset(self::$formats[$name]) && self::$formats[$name]['type'] === $type) { + return true; + } + + return false; + } + + /** + * Get a Format array to create Validator + * + * @param string $name + * @param string $type + * + * @return array{callback: callable, type: string} + * @throws Exception + */ + public static function getFormat(string $name, string $type): array + { + if (isset(self::$formats[$name])) { + if (self::$formats[$name]['type'] !== $type) { + throw new DatabaseException('Format "'.$name.'" not available for attribute type "'.$type.'"'); + } + + return self::$formats[$name]; + } + + throw new DatabaseException('Unknown format validator "'.$name.'"'); + } + + /** + * Remove a Validator + * + * @param string $name + */ + public static function removeFormat(string $name): void + { + unset(self::$formats[$name]); + } + + /** + * Get Description. + * + * Returns validator description + * + * @return string + */ + public function getDescription(): string + { + return 'Invalid document structure: '.$this->message; + } + + /** + * Is valid. + * + * Returns true if valid or false if not. + * + * @param mixed $document + * + * @return bool + */ + public function isValid($document): bool + { + if (!$document instanceof Document) { + $this->message = 'Value must be an instance of Document'; + return false; + } + + if (empty($this->collection->getId()) || Database::METADATA !== $this->collection->getCollection()) { + $this->message = 'Collection not found'; + return false; + } + + $keys = []; + $structure = $document->getArrayCopy(); + $attributes = $this->collection->getAttribute('attributes', []); + + $keys = []; + foreach ($attributes as $attribute) { + $keys[$attribute['$id']] = $attribute; + } + + foreach ($structure as $key => $value) { + if (!array_key_exists($key, $keys)) { // Check no unknown attributes are set + $this->message = 'Unknown attribute: "'.$key.'"'; + return false; + } + + $attribute = $keys[$key] ?? []; + $type = $attribute['type'] ?? ''; + $array = $attribute['array'] ?? false; + $format = $attribute['format'] ?? ''; + $required = $attribute['required'] ?? false; + $size = $attribute['size'] ?? 0; + $signed = $attribute['signed'] ?? true; + + if ($required === false && is_null($value)) { // Allow null value to optional params + continue; + } + + if ($type === Database::VAR_RELATIONSHIP) { + continue; + } + + $validators = []; + + switch ($type) { + case Database::VAR_STRING: + $validators[] = new Text($size, min: 0); + break; + + case Database::VAR_INTEGER: + // We need both Integer and Range because Range implicitly casts non-numeric values + $validators[] = new Integer(); + $max = $size >= 8 ? Database::BIG_INT_MAX : Database::INT_MAX; + $min = $signed ? -$max : 0; + $validators[] = new Range($min, $max, Database::VAR_INTEGER); + break; + + case Database::VAR_FLOAT: + // We need both Float and Range because Range implicitly casts non-numeric values + $validators[] = new FloatValidator(); + $min = $signed ? -Database::DOUBLE_MAX : 0; + $validators[] = new Range($min, Database::DOUBLE_MAX, Database::VAR_FLOAT); + break; + + case Database::VAR_BOOLEAN: + $validators[] = new Boolean(); + break; + + case Database::VAR_DATETIME: + $validators[] = new DatetimeValidator(); + break; + + default: + $this->message = 'Unknown attribute type "'.$type.'"'; + return false; + } + + /** Error message label, either 'format' or 'type' */ + $label = ($format) ? 'format' : 'type'; + + if ($format) { + // Format encoded as json string containing format name and relevant format options + $format = self::getFormat($format, $type); + $validators[] = $format['callback']($attribute); + } + + if ($array) { // Validate attribute type for arrays - format for arrays handled separately + if (!$required && ((is_array($value) && empty($value)) || is_null($value))) { // Allow both null and [] for optional arrays + continue; + } + + if (!\is_array($value) || !\array_is_list($value)) { + $this->message = 'Attribute "'.$key.'" must be an array'; + return false; + } + + foreach ($value as $x => $child) { + if (!$required && is_null($child)) { // Allow null value to optional params + continue; + } + + foreach ($validators as $validator) { + if (!$validator->isValid($child)) { + $this->message = 'Attribute "'.$key.'[\''.$x.'\']" has invalid '.$label.'. '.$validator->getDescription(); + return false; + } + } + } + } else { + foreach ($validators as $validator) { + if (!$validator->isValid($value)) { + $this->message = 'Attribute "'.$key.'" has invalid '.$label.'. '.$validator->getDescription(); + return false; + } + } + } + } + + return true; + } + + /** + * Is array + * + * Function will return true if object is array. + * + * @return bool + */ + public function isArray(): bool + { + return false; + } + + /** + * Get Type + * + * Returns validator type. + * + * @return string + */ + public function getType(): string + { + return self::TYPE_ARRAY; + } +} diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 4820009f7..dab0f4682 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -340,6 +340,137 @@ public function isValid($document): bool return true; } + /** + * Is Update Valid + * + * Returns true if an update is valid or false if not. Ignores fields not in the update. + * + * @param mixed $document + * + * @return bool + */ + public function isUpdateValid($document): bool + { + if (!$document instanceof Document) { + $this->message = 'Value must be an instance of Document'; + return false; + } + + if (empty($this->collection->getId()) || Database::METADATA !== $this->collection->getCollection()) { + $this->message = 'Collection not found'; + return false; + } + + $keys = []; + $structure = $document->getArrayCopy(); + $attributes = $this->collection->getAttribute('attributes', []); + + $keys = []; + foreach ($attributes as $attribute) { + $keys[$attribute['$id']] = $attribute; + } + + foreach ($structure as $key => $value) { + if (!array_key_exists($key, $keys)) { // Check no unknown attributes are set + $this->message = 'Unknown attribute: "'.$key.'"'; + return false; + } + + $attribute = $keys[$key] ?? []; + $type = $attribute['type'] ?? ''; + $array = $attribute['array'] ?? false; + $format = $attribute['format'] ?? ''; + $required = $attribute['required'] ?? false; + $size = $attribute['size'] ?? 0; + $signed = $attribute['signed'] ?? true; + + if ($required === false && is_null($value)) { // Allow null value to optional params + continue; + } + + if ($type === Database::VAR_RELATIONSHIP) { + continue; + } + + $validators = []; + + switch ($type) { + case Database::VAR_STRING: + $validators[] = new Text($size, min: 0); + break; + + case Database::VAR_INTEGER: + // We need both Integer and Range because Range implicitly casts non-numeric values + $validators[] = new Integer(); + $max = $size >= 8 ? Database::BIG_INT_MAX : Database::INT_MAX; + $min = $signed ? -$max : 0; + $validators[] = new Range($min, $max, Database::VAR_INTEGER); + break; + + case Database::VAR_FLOAT: + // We need both Float and Range because Range implicitly casts non-numeric values + $validators[] = new FloatValidator(); + $min = $signed ? -Database::DOUBLE_MAX : 0; + $validators[] = new Range($min, Database::DOUBLE_MAX, Database::VAR_FLOAT); + break; + + case Database::VAR_BOOLEAN: + $validators[] = new Boolean(); + break; + + case Database::VAR_DATETIME: + $validators[] = new DatetimeValidator(); + break; + + default: + $this->message = 'Unknown attribute type "'.$type.'"'; + return false; + } + + /** Error message label, either 'format' or 'type' */ + $label = ($format) ? 'format' : 'type'; + + if ($format) { + // Format encoded as json string containing format name and relevant format options + $format = self::getFormat($format, $type); + $validators[] = $format['callback']($attribute); + } + + if ($array) { // Validate attribute type for arrays - format for arrays handled separately + if (!$required && ((is_array($value) && empty($value)) || is_null($value))) { // Allow both null and [] for optional arrays + continue; + } + + if (!\is_array($value) || !\array_is_list($value)) { + $this->message = 'Attribute "'.$key.'" must be an array'; + return false; + } + + foreach ($value as $x => $child) { + if (!$required && is_null($child)) { // Allow null value to optional params + continue; + } + + foreach ($validators as $validator) { + if (!$validator->isValid($child)) { + $this->message = 'Attribute "'.$key.'[\''.$x.'\']" has invalid '.$label.'. '.$validator->getDescription(); + return false; + } + } + } + } else { + foreach ($validators as $validator) { + if (!$validator->isValid($value)) { + $this->message = 'Attribute "'.$key.'" has invalid '.$label.'. '.$validator->getDescription(); + return false; + } + } + } + } + + return true; + } + /** * Is array * diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 952f0eada..b2f90bf03 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -2417,53 +2417,6 @@ public function testUpdateDocument(Document $document): Document return $document; } - /** - * @depends testCreateDocuments - * @param array $documents - */ - public function testUpdateDocuments(array $documents): void - { - $collection = 'testCreateDocuments'; - - foreach ($documents as $document) { - $document - ->setAttribute('string', 'text📝 updated') - ->setAttribute('integer', 6) - ->setAttribute('$permissions', [ - Permission::read(Role::users()), - Permission::create(Role::users()), - Permission::update(Role::users()), - Permission::delete(Role::users()), - ]); - } - - $documents = $this->getDatabase()->updateDocuments( - $collection, - $documents, - \count($documents) - ); - - foreach ($documents as $document) { - $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $this->assertEquals(6, $document->getAttribute('integer')); - } - - $documents = $this->getDatabase()->find($collection, [ - Query::limit(\count($documents)) - ]); - - foreach ($documents as $document) { - $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $this->assertEquals(6, $document->getAttribute('integer')); - $this->assertEquals([ - Permission::read(Role::users()), - Permission::create(Role::users()), - Permission::update(Role::users()), - Permission::delete(Role::users()), - ], $document->getAttribute('$permissions')); - } - } - /** * @depends testUpdateDocument */ @@ -15669,4 +15622,65 @@ public function testEvents(): void $database->delete('hellodb'); }); } + + public function testUpdateDocuments(): void + { + $collection = 'testUpdateDocuments'; + + $this->getDatabase()->createCollection($collection, attributes: [ + new Document([ + '$id' => ID::custom('string'), + 'type' => Database::VAR_STRING, + 'format' => '', + 'size' => 100, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ]), + new Document([ + '$id' => ID::custom('integer'), + 'type' => Database::VAR_INTEGER, + 'format' => '', + 'size' => 10000, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ]), + ]); + + for ($i = 0; $i < 10; $i++) { + $this->getDatabase()->createDocument($collection, new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝 ' . $i, + 'integer' => $i, + '$permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + ])); + } + + // Test Update half of the documents + $this->getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'text📝 updated', + ]), [ + Query::greaterThanEqual('integer', 5), + ]); + + $updatedDocuments = $this->getDatabase()->find($collection, [ + Query::greaterThanEqual('integer', 5), + ]); + + $this->assertEquals(count($updatedDocuments), 5); + + foreach ($updatedDocuments as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + } + } } From dbe77e979a235b9286d70a8849182754c929b13e Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 10 Oct 2024 11:16:49 +0900 Subject: [PATCH 068/103] Add more tests --- docker-compose.yml | 2 +- src/Database/Database.php | 20 +- tests/e2e/Adapter/Base.php | 453 ++++++++++++++++++++++++++++++++----- 3 files changed, 404 insertions(+), 71 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 23b135ba9..5497f4e28 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: . args: - DEBUG: false + DEBUG: true networks: - database volumes: diff --git a/src/Database/Database.php b/src/Database/Database.php index 7116c9740..417e5bea8 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4998,17 +4998,15 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; while (true) { - $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { - return $this->find($collection->getId(), array_merge( - empty($lastDocument) ? [ - Query::limit($batchSize), - ] : [ - Query::limit($batchSize), - Query::cursorAfter($lastDocument), - ], - $queries, - )); - }); + $affectedDocuments = $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + )); if (empty($affectedDocuments)) { break; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index b4162b9f0..4892b6318 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15649,22 +15649,22 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void return; } - $this->getDatabase()->createCollection('bulk_delete_person'); - $this->getDatabase()->createCollection('bulk_delete_library'); + $this->getDatabase()->createCollection('bulk_delete_person_o2o'); + $this->getDatabase()->createCollection('bulk_delete_library_o2o'); - $this->getDatabase()->createAttribute('bulk_delete_person', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library', 'area', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_person_o2o', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_o2o', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_o2o', 'area', Database::VAR_STRING, 255, true); // Restrict $this->getDatabase()->createRelationship( - collection: 'bulk_delete_person', - relatedCollection: 'bulk_delete_library', + collection: 'bulk_delete_person_o2o', + relatedCollection: 'bulk_delete_library_o2o', type: Database::RELATION_ONE_TO_ONE, onDelete: Database::RELATION_MUTATE_RESTRICT ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15672,7 +15672,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void Permission::delete(Role::any()), ], 'name' => 'Person 1', - 'bulk_delete_library' => [ + 'bulk_delete_library_o2o' => [ '$id' => 'library1', '$permissions' => [ Permission::read(Role::any()), @@ -15684,20 +15684,20 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person1->getAttribute('bulk_delete_library'); + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); - $this->assertArrayNotHasKey('bulk_delete_person', $library); + $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); // Delete person try { - $this->getDatabase()->deleteDocuments('bulk_delete_person'); + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); $this->fail('Failed to throw exception'); } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } - $this->getDatabase()->updateDocument('bulk_delete_person', 'person1', new Document([ + $this->getDatabase()->updateDocument('bulk_delete_person_o2o', 'person1', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15705,22 +15705,22 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void Permission::delete(Role::any()), ], 'name' => 'Person 1', - 'bulk_delete_library' => null, + 'bulk_delete_library_o2o' => null, ])); - $this->getDatabase()->deleteDocuments('bulk_delete_person'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); // NULL $this->getDatabase()->updateRelationship( - collection: 'bulk_delete_person', - id: 'bulk_delete_library', + collection: 'bulk_delete_person_o2o', + id: 'bulk_delete_library_o2o', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15728,7 +15728,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void Permission::delete(Role::any()), ], 'name' => 'Person 1', - 'bulk_delete_library' => [ + 'bulk_delete_library_o2o' => [ '$id' => 'library1', '$permissions' => [ Permission::read(Role::any()), @@ -15740,35 +15740,35 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person1->getAttribute('bulk_delete_library'); + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); - $this->assertArrayNotHasKey('bulk_delete_person', $library); + $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person_o2o')); - $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person->getAttribute('bulk_delete_library'); + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person->getAttribute('bulk_delete_library_o2o'); $this->assertNull($library); // NULL - Cleanup - $this->getDatabase()->deleteDocuments('bulk_delete_person'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); // Cascade $this->getDatabase()->updateRelationship( - collection: 'bulk_delete_person', - id: 'bulk_delete_library', + collection: 'bulk_delete_person_o2o', + id: 'bulk_delete_library_o2o', onDelete: Database::RELATION_MUTATE_CASCADE ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15776,7 +15776,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void Permission::delete(Role::any()), ], 'name' => 'Person 1', - 'bulk_delete_library' => [ + 'bulk_delete_library_o2o' => [ '$id' => 'library1', '$permissions' => [ Permission::read(Role::any()), @@ -15788,27 +15788,27 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person1->getAttribute('bulk_delete_library'); + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); - $this->assertArrayNotHasKey('bulk_delete_person', $library); + $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); - $this->getDatabase()->deleteDocuments('bulk_delete_library'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); - $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person_o2o')); - $person = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person->getAttribute('bulk_delete_library'); + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person->getAttribute('bulk_delete_library_o2o'); $this->assertEmpty($library); $this->assertNotNull($library); // Test Bulk delete parent - $this->getDatabase()->deleteDocuments('bulk_delete_person'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person', new Document([ + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15816,7 +15816,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void Permission::delete(Role::any()), ], 'name' => 'Person 1', - 'bulk_delete_library' => [ + 'bulk_delete_library_o2o' => [ '$id' => 'library1', '$permissions' => [ Permission::read(Role::any()), @@ -15828,14 +15828,349 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person', 'person1'); - $library = $person1->getAttribute('bulk_delete_library'); + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); - $this->assertArrayNotHasKey('bulk_delete_person', $library); + $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $this->getDatabase()->deleteDocuments('bulk_delete_person'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person')); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library')); + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + } + + public function testDeleteBulkDocumentsOneToManyRelationship(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + $this->expectNotToPerformAssertions(); + return; + } + + $this->getDatabase()->createCollection('bulk_delete_person_o2m'); + $this->getDatabase()->createCollection('bulk_delete_library_o2m'); + + $this->getDatabase()->createAttribute('bulk_delete_person_o2m', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_o2m', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_o2m', 'area', Database::VAR_STRING, 255, true); + + // Restrict + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person_o2m', + relatedCollection: 'bulk_delete_library_o2m', + type: Database::RELATION_ONE_TO_MANY, + onDelete: Database::RELATION_MUTATE_RESTRICT + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library_o2m' => [ + [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + [ + '$id' => 'library2', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 2', + 'area' => 'Area 2', + ], + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $libraries = $person1->getAttribute('bulk_delete_library_o2m'); + $this->assertCount(2, $libraries); + + // Delete person + try { + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + $this->fail('Failed to throw exception'); + } catch (RestrictedException $e) { + $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); + } + + // Restrict Cleanup + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2m')); + + // NULL + $this->getDatabase()->updateRelationship( + collection: 'bulk_delete_person_o2m', + id: 'bulk_delete_library_o2m', + onDelete: Database::RELATION_MUTATE_SET_NULL + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library_o2m' => [ + [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + [ + '$id' => 'library2', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 2', + 'area' => 'Area 2', + ], + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $libraries = $person1->getAttribute('bulk_delete_library_o2m'); + $this->assertCount(2, $libraries); + + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $libraries = $person->getAttribute('bulk_delete_library_o2m'); + $this->assertEmpty($libraries); + + // NULL - Cleanup + $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2m')); + + + // Cascade + $this->getDatabase()->updateRelationship( + collection: 'bulk_delete_person_o2m', + id: 'bulk_delete_library_o2m', + onDelete: Database::RELATION_MUTATE_CASCADE + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library_o2m' => [ + [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + [ + '$id' => 'library2', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 2', + 'area' => 'Area 2', + ], + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $libraries = $person1->getAttribute('bulk_delete_library_o2m'); + $this->assertCount(2, $libraries); + + $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + + $person = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $libraries = $person->getAttribute('bulk_delete_library_o2m'); + $this->assertEmpty($libraries); + } + + public function testDeleteBulkDocumentsManyToManyRelationship(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + $this->expectNotToPerformAssertions(); + return; + } + + $this->getDatabase()->createCollection('bulk_delete_person_m2m'); + $this->getDatabase()->createCollection('bulk_delete_library_m2m'); + + $this->getDatabase()->createAttribute('bulk_delete_person_m2m', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'area', Database::VAR_STRING, 255, true); + + // Many-to-Many Relationship + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person_m2m', + relatedCollection: 'bulk_delete_library_m2m', + type: Database::RELATION_MANY_TO_MANY, + onDelete: Database::RELATION_MUTATE_RESTRICT + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2m', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library_m2m' => [ + [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + [ + '$id' => 'library2', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 2', + 'area' => 'Area 2', + ], + ], + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2m', 'person1'); + $libraries = $person1->getAttribute('bulk_delete_library_m2m'); + $this->assertCount(2, $libraries); + + // Delete person + try { + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); + $this->fail('Failed to throw exception'); + } catch (RestrictedException $e) { + $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); + } + + // Restrict Cleanup + $this->getDatabase()->deleteRelationship('bulk_delete_person_m2m', 'bulk_delete_library_m2m'); + $this->getDatabase()->deleteDocuments('bulk_delete_library_m2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2m')); + + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2m')); + } + + public function testDeleteBulkDocumentsManyToOneRelationship(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + $this->expectNotToPerformAssertions(); + return; + } + + $this->getDatabase()->createCollection('bulk_delete_person_m2o'); + $this->getDatabase()->createCollection('bulk_delete_library_m2o'); + + $this->getDatabase()->createAttribute('bulk_delete_person_m2o', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'name', Database::VAR_STRING, 255, true); + $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'area', Database::VAR_STRING, 255, true); + + // Many-to-One Relationship + $this->getDatabase()->createRelationship( + collection: 'bulk_delete_person_m2o', + relatedCollection: 'bulk_delete_library_m2o', + type: Database::RELATION_MANY_TO_ONE, + onDelete: Database::RELATION_MUTATE_RESTRICT + ); + + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ + '$id' => 'person1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 1', + 'bulk_delete_library_m2o' => [ + '$id' => 'library1', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Library 1', + 'area' => 'Area 1', + ], + ])); + + $person2 = $this->getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ + '$id' => 'person2', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'name' => 'Person 2', + 'bulk_delete_library_m2o' => [ + '$id' => 'library1', + ] + ])); + + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2o', 'person1'); + $library = $person1->getAttribute('bulk_delete_library_m2o'); + $this->assertEquals('library1', $library['$id']); + + // Delete library + try { + $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); + $this->fail('Failed to throw exception'); + } catch (RestrictedException $e) { + $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); + } + + $this->assertEquals(2, count($this->getDatabase()->find('bulk_delete_person_m2o'))); + + // Test delete people + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); + $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete_person_m2o'))); + + // Restrict Cleanup + $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2o')); + + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); + $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2o')); } public function testEvents(): void From c75b4bf3b105992d6e9bcd2c97a176a947fae65a Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 10 Oct 2024 11:17:31 +0900 Subject: [PATCH 069/103] Remove debug flag in compose file --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5497f4e28..23b135ba9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: . args: - DEBUG: true + DEBUG: false networks: - database volumes: From 4121f7f62899cc0b4f36696108f87cf5adf28805 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 10 Oct 2024 11:21:22 +0900 Subject: [PATCH 070/103] Run Linter --- tests/e2e/Adapter/Base.php | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 4892b6318..82694ec7a 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15964,7 +15964,7 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void // NULL - Cleanup $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2m')); - + // Cascade $this->getDatabase()->updateRelationship( @@ -16023,14 +16023,14 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void $this->expectNotToPerformAssertions(); return; } - + $this->getDatabase()->createCollection('bulk_delete_person_m2m'); $this->getDatabase()->createCollection('bulk_delete_library_m2m'); - + $this->getDatabase()->createAttribute('bulk_delete_person_m2m', 'name', Database::VAR_STRING, 255, true); $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'name', Database::VAR_STRING, 255, true); $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'area', Database::VAR_STRING, 255, true); - + // Many-to-Many Relationship $this->getDatabase()->createRelationship( collection: 'bulk_delete_person_m2m', @@ -16038,7 +16038,7 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void type: Database::RELATION_MANY_TO_MANY, onDelete: Database::RELATION_MUTATE_RESTRICT ); - + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2m', new Document([ '$id' => 'person1', '$permissions' => [ @@ -16070,11 +16070,11 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void ], ], ])); - + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2m', 'person1'); $libraries = $person1->getAttribute('bulk_delete_library_m2m'); $this->assertCount(2, $libraries); - + // Delete person try { $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); @@ -16082,30 +16082,30 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } - + // Restrict Cleanup $this->getDatabase()->deleteRelationship('bulk_delete_person_m2m', 'bulk_delete_library_m2m'); $this->getDatabase()->deleteDocuments('bulk_delete_library_m2m'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2m')); - + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2m')); } - + public function testDeleteBulkDocumentsManyToOneRelationship(): void { if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - + $this->getDatabase()->createCollection('bulk_delete_person_m2o'); $this->getDatabase()->createCollection('bulk_delete_library_m2o'); - + $this->getDatabase()->createAttribute('bulk_delete_person_m2o', 'name', Database::VAR_STRING, 255, true); $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'name', Database::VAR_STRING, 255, true); $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'area', Database::VAR_STRING, 255, true); - + // Many-to-One Relationship $this->getDatabase()->createRelationship( collection: 'bulk_delete_person_m2o', @@ -16113,7 +16113,7 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void type: Database::RELATION_MANY_TO_ONE, onDelete: Database::RELATION_MUTATE_RESTRICT ); - + $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ '$id' => 'person1', '$permissions' => [ @@ -16146,11 +16146,11 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void '$id' => 'library1', ] ])); - + $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_m2o'); $this->assertEquals('library1', $library['$id']); - + // Delete library try { $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); @@ -16164,11 +16164,11 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void // Test delete people $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete_person_m2o'))); - + // Restrict Cleanup $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2o')); - + $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2o')); } From 5e819e8b5e2f9c055d08fb38eb327e4b2f0d0c37 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 14 Oct 2024 10:18:29 +0900 Subject: [PATCH 071/103] Get updateDocuments working for all adapters, add tests --- src/Database/Adapter/MariaDB.php | 4 +- src/Database/Adapter/Mongo.php | 20 +++- src/Database/Adapter/Postgres.php | 70 ++++++++++++- src/Database/Adapter/SQLite.php | 16 +-- src/Database/Database.php | 8 +- src/Database/Validator/Structure.php | 6 +- tests/e2e/Adapter/Base.php | 148 ++++++++++++++++----------- 7 files changed, 184 insertions(+), 88 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 0aeed6182..005af5183 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1334,7 +1334,7 @@ public function updateDocuments(string $collection, Document $update, array $que } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "_tenant = :_tenant"; } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; @@ -1357,7 +1357,7 @@ public function updateDocuments(string $collection, Document $update, array $que SET {$columns} {$sqlWhere} "; - + $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 28d6bf9f9..44340a984 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -832,7 +832,25 @@ public function updateDocument(string $collection, Document $document): Document */ public function updateDocuments(string $collection, Document $update, array $queries): bool { - throw new Exception('Not implemented'); + $name = $this->getNamespace() . '_' . $this->filter($collection); + $queries = array_map(fn ($query) => clone $query, $queries); + + $filters = $this->buildFilters($queries); + if ($this->sharedTables) { + $filters['_tenant'] = (string)$this->getTenant(); + } + + $updateQuery = [ + '$set' => $update->getArrayCopy(), + ]; + + try { + $this->client->update($name, $filters, $updateQuery, multi: true); + } catch (MongoException $e) { + throw new Duplicate($e->getMessage()); + } + + return true; } /** diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 6942f0dfb..675fcbca7 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1238,7 +1238,75 @@ public function updateDocument(string $collection, Document $document): Document */ public function updateDocuments(string $collection, Document $update, array $queries): bool { - throw new Exception('Not implemented'); + $attributes = $update->getAttributes(); + + if (empty($attributes)) { + return true; + } + + $name = $this->filter($collection); + $columns = ''; + + $where = []; + + $queries = array_map(fn ($query) => clone $query, $queries); + + $conditions = $this->getSQLConditions($queries); + if (!empty($conditions)) { + $where[] = $conditions; + } + + if ($this->sharedTables) { + $where[] = "_tenant = :_tenant"; + } + + $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + + $bindIndex = 0; + foreach ($attributes as $attribute => $value) { + $column = $this->filter($attribute); + $bindKey = 'key_' . $bindIndex; + $columns .= "\"{$column}\"" . '=:' . $bindKey; + + if ($bindIndex > 0) { + $columns .= ','; + } + + $bindIndex++; + } + + $sql = " + UPDATE {$this->getSQLTable($name)} + SET {$columns} + {$sqlWhere} + "; + + $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); + $stmt = $this->getPDO()->prepare($sql); + + foreach ($queries as $query) { + $this->bindConditionValue($stmt, $query); + } + + if ($this->sharedTables) { + $stmt->bindValue(':_tenant', $this->tenant); + } + + $attributeIndex = 0; + foreach ($attributes as $attribute => $value) { + if (is_array($value)) { + $value = json_encode($value); + } + + $bindKey = 'key_' . $attributeIndex; + $value = (is_bool($value)) ? (int)$value : $value; + $stmt->bindValue(':' . $bindKey, $value, $this->getPDOType($value)); + $attributeIndex++; + } + + $stmt->execute(); + + return true; } /** diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 062bd42d6..53b4639f1 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -815,21 +815,7 @@ public function updateDocument(string $collection, Document $document): Document return $document; } - /** - * Batch update documents - * - * @param string $collection - * @param Document $update - * @param array $queries - * - * @return bool - * - * @throws DatabaseException - */ - public function updateDocuments(string $collection, Document $update, array $queries): bool - { - throw new Exception('Not implemented'); - } + /** * Is schemas supported? diff --git a/src/Database/Database.php b/src/Database/Database.php index 669214116..a241422c1 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3886,16 +3886,16 @@ public function updateDocument(string $collection, string $id, Document $documen /** * Batch update documents - * + * * @param string $collection * @param Document $updates * @param array $queries - * + * * @return bool - * + * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries, int $batchSize = self::INSERT_BATCH_SIZE): bool + public function updateDocuments(string $collection, Document $update, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): bool { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index dab0f4682..fa105b054 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -342,11 +342,11 @@ public function isValid($document): bool /** * Is Update Valid - * + * * Returns true if an update is valid or false if not. Ignores fields not in the update. - * + * * @param mixed $document - * + * * @return bool */ public function isUpdateValid($document): bool diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index b2f90bf03..c13fb1530 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -762,7 +762,8 @@ public function testPreserveDatesUpdate(): void $doc2->setAttribute('$updatedAt', $newDate); $doc3->setAttribute('$updatedAt', $newDate); - $this->getDatabase()->updateDocuments('preserve_update_dates', [$doc2, $doc3], 2); + $this->getDatabase()->updateDocument('preserve_update_dates', 'doc2', $doc2); + $this->getDatabase()->updateDocument('preserve_update_dates', 'doc3', $doc3); $doc2 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc2'); $doc3 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc3'); @@ -15531,6 +15532,90 @@ public function testTransformations(): void $this->assertTrue($result->isEmpty()); } + public function testUpdateDocuments(): void + { + $collection = 'testUpdateDocuments'; + + $this->getDatabase()->createCollection($collection, attributes: [ + new Document([ + '$id' => ID::custom('string'), + 'type' => Database::VAR_STRING, + 'format' => '', + 'size' => 100, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ]), + new Document([ + '$id' => ID::custom('integer'), + 'type' => Database::VAR_INTEGER, + 'format' => '', + 'size' => 10000, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ]), + ]); + + for ($i = 0; $i < 10; $i++) { + $this->getDatabase()->createDocument($collection, new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝 ' . $i, + 'integer' => $i, + '$permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + ])); + } + + // Test Update half of the documents + $this->getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'text📝 updated', + ]), [ + Query::greaterThanEqual('integer', 5), + ]); + + $updatedDocuments = $this->getDatabase()->find($collection, [ + Query::greaterThanEqual('integer', 5), + ]); + + $this->assertEquals(count($updatedDocuments), 5); + + foreach ($updatedDocuments as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + } + + $controlDocuments = $this->getDatabase()->find($collection, [ + Query::lessThan('integer', 5), + ]); + + $this->assertEquals(count($controlDocuments), 5); + + foreach ($controlDocuments as $document) { + $this->assertNotEquals('text📝 updated', $document->getAttribute('string')); + } + + // Test Update all documents + $this->getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'text📝 updated all', + ])); + + $updatedDocuments = $this->getDatabase()->find($collection); + + $this->assertEquals(count($updatedDocuments), 10); + + foreach ($updatedDocuments as $document) { + $this->assertEquals('text📝 updated all', $document->getAttribute('string')); + } + } + public function testEvents(): void { self::$authorization->skip(function () { @@ -15622,65 +15707,4 @@ public function testEvents(): void $database->delete('hellodb'); }); } - - public function testUpdateDocuments(): void - { - $collection = 'testUpdateDocuments'; - - $this->getDatabase()->createCollection($collection, attributes: [ - new Document([ - '$id' => ID::custom('string'), - 'type' => Database::VAR_STRING, - 'format' => '', - 'size' => 100, - 'signed' => true, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => [], - ]), - new Document([ - '$id' => ID::custom('integer'), - 'type' => Database::VAR_INTEGER, - 'format' => '', - 'size' => 10000, - 'signed' => true, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => [], - ]), - ]); - - for ($i = 0; $i < 10; $i++) { - $this->getDatabase()->createDocument($collection, new Document([ - '$id' => 'doc' . $i, - 'string' => 'text📝 ' . $i, - 'integer' => $i, - '$permissions' => [ - Permission::read(Role::any()), - Permission::create(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], - ])); - } - - // Test Update half of the documents - $this->getDatabase()->updateDocuments($collection, new Document([ - 'string' => 'text📝 updated', - ]), [ - Query::greaterThanEqual('integer', 5), - ]); - - $updatedDocuments = $this->getDatabase()->find($collection, [ - Query::greaterThanEqual('integer', 5), - ]); - - $this->assertEquals(count($updatedDocuments), 5); - - foreach ($updatedDocuments as $document) { - $this->assertEquals('text📝 updated', $document->getAttribute('string')); - } - } } From 3acb215d46029560af616071f4351065f352e407 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 14 Oct 2024 10:23:15 +0900 Subject: [PATCH 072/103] Fix PHPStan issues --- src/Database/Database.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index a241422c1..9ad135bdb 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3888,8 +3888,9 @@ public function updateDocument(string $collection, string $id, Document $documen * Batch update documents * * @param string $collection - * @param Document $updates + * @param Document $update * @param array $queries + * @param int $batchSize * * @return bool * @@ -3901,7 +3902,7 @@ public function updateDocuments(string $collection, Document $update, array $que throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - if (empty($update)) { + if (empty($update->getArrayCopy())) { return true; } From e60df0df782050232d5449a526283f2c24a09c3b Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 14 Oct 2024 14:23:36 +0900 Subject: [PATCH 073/103] Get document permissions working --- src/Database/Adapter/MariaDB.php | 7 +- src/Database/Adapter/Mongo.php | 6 ++ src/Database/Adapter/Postgres.php | 7 +- src/Database/Adapter/SQL.php | 4 +- src/Database/Adapter/SQLite.php | 4 +- src/Database/Validator/Structure.php | 131 --------------------------- tests/e2e/Adapter/Base.php | 42 +++++++++ 7 files changed, 64 insertions(+), 137 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 005af5183..46c896c55 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1322,6 +1322,7 @@ public function updateDocuments(string $collection, Document $update, array $que } $name = $this->filter($collection); + $roles = $this->authorization->getRoles(); $columns = ''; $where = []; @@ -1333,6 +1334,10 @@ public function updateDocuments(string $collection, Document $update, array $que $where[] = $conditions; } + if ($this->authorization->getStatus()) { + $where[] = $this->getSQLPermissionsCondition($name, $roles, 'update'); + } + if ($this->sharedTables) { $where[] = "_tenant = :_tenant"; } @@ -1353,7 +1358,7 @@ public function updateDocuments(string $collection, Document $update, array $que } $sql = " - UPDATE {$this->getSQLTable($name)} + UPDATE {$this->getSQLTable($name)} AS table_main SET {$columns} {$sqlWhere} "; diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 44340a984..4e474bf72 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -840,6 +840,12 @@ public function updateDocuments(string $collection, Document $update, array $que $filters['_tenant'] = (string)$this->getTenant(); } + // permissions + if ($this->authorization->getStatus()) { // skip if authorization is disabled + $roles = \implode('|', $this->authorization->getRoles()); + $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; + } + $updateQuery = [ '$set' => $update->getArrayCopy(), ]; diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 675fcbca7..94c0ea9cd 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1245,6 +1245,7 @@ public function updateDocuments(string $collection, Document $update, array $que } $name = $this->filter($collection); + $roles = $this->authorization->getRoles(); $columns = ''; $where = []; @@ -1256,6 +1257,10 @@ public function updateDocuments(string $collection, Document $update, array $que $where[] = $conditions; } + if ($this->authorization->getStatus()) { + $where[] = $this->getSQLPermissionsCondition($name, $roles, 'update'); + } + if ($this->sharedTables) { $where[] = "_tenant = :_tenant"; } @@ -1276,7 +1281,7 @@ public function updateDocuments(string $collection, Document $update, array $que } $sql = " - UPDATE {$this->getSQLTable($name)} + UPDATE {$this->getSQLTable($name)} AS table_main SET {$columns} {$sqlWhere} "; diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index e73515a57..2049943cb 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -968,7 +968,7 @@ protected function getSQLIndexType(string $type): string * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = 'read'): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); @@ -981,7 +981,7 @@ protected function getSQLPermissionsCondition(string $collection, array $roles): SELECT _document FROM {$this->getSQLTable($collection . '_perms')} WHERE _permission IN (" . implode(', ', $roles) . ") - AND _type = 'read' + AND _type = '{$type}' {$tenantQuery} )"; } diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 53b4639f1..1ae62ac1c 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -963,14 +963,14 @@ protected function getSQLIndex(string $collection, string $id, string $type, arr * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = 'read'): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); return "table_main._uid IN ( SELECT distinct(_document) FROM `{$this->getNamespace()}_{$collection}_perms` WHERE _permission IN (" . implode(', ', $roles) . ") - AND _type = 'read' + AND _type = '{$type}' )"; } diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index fa105b054..4820009f7 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -340,137 +340,6 @@ public function isValid($document): bool return true; } - /** - * Is Update Valid - * - * Returns true if an update is valid or false if not. Ignores fields not in the update. - * - * @param mixed $document - * - * @return bool - */ - public function isUpdateValid($document): bool - { - if (!$document instanceof Document) { - $this->message = 'Value must be an instance of Document'; - return false; - } - - if (empty($this->collection->getId()) || Database::METADATA !== $this->collection->getCollection()) { - $this->message = 'Collection not found'; - return false; - } - - $keys = []; - $structure = $document->getArrayCopy(); - $attributes = $this->collection->getAttribute('attributes', []); - - $keys = []; - foreach ($attributes as $attribute) { - $keys[$attribute['$id']] = $attribute; - } - - foreach ($structure as $key => $value) { - if (!array_key_exists($key, $keys)) { // Check no unknown attributes are set - $this->message = 'Unknown attribute: "'.$key.'"'; - return false; - } - - $attribute = $keys[$key] ?? []; - $type = $attribute['type'] ?? ''; - $array = $attribute['array'] ?? false; - $format = $attribute['format'] ?? ''; - $required = $attribute['required'] ?? false; - $size = $attribute['size'] ?? 0; - $signed = $attribute['signed'] ?? true; - - if ($required === false && is_null($value)) { // Allow null value to optional params - continue; - } - - if ($type === Database::VAR_RELATIONSHIP) { - continue; - } - - $validators = []; - - switch ($type) { - case Database::VAR_STRING: - $validators[] = new Text($size, min: 0); - break; - - case Database::VAR_INTEGER: - // We need both Integer and Range because Range implicitly casts non-numeric values - $validators[] = new Integer(); - $max = $size >= 8 ? Database::BIG_INT_MAX : Database::INT_MAX; - $min = $signed ? -$max : 0; - $validators[] = new Range($min, $max, Database::VAR_INTEGER); - break; - - case Database::VAR_FLOAT: - // We need both Float and Range because Range implicitly casts non-numeric values - $validators[] = new FloatValidator(); - $min = $signed ? -Database::DOUBLE_MAX : 0; - $validators[] = new Range($min, Database::DOUBLE_MAX, Database::VAR_FLOAT); - break; - - case Database::VAR_BOOLEAN: - $validators[] = new Boolean(); - break; - - case Database::VAR_DATETIME: - $validators[] = new DatetimeValidator(); - break; - - default: - $this->message = 'Unknown attribute type "'.$type.'"'; - return false; - } - - /** Error message label, either 'format' or 'type' */ - $label = ($format) ? 'format' : 'type'; - - if ($format) { - // Format encoded as json string containing format name and relevant format options - $format = self::getFormat($format, $type); - $validators[] = $format['callback']($attribute); - } - - if ($array) { // Validate attribute type for arrays - format for arrays handled separately - if (!$required && ((is_array($value) && empty($value)) || is_null($value))) { // Allow both null and [] for optional arrays - continue; - } - - if (!\is_array($value) || !\array_is_list($value)) { - $this->message = 'Attribute "'.$key.'" must be an array'; - return false; - } - - foreach ($value as $x => $child) { - if (!$required && is_null($child)) { // Allow null value to optional params - continue; - } - - foreach ($validators as $validator) { - if (!$validator->isValid($child)) { - $this->message = 'Attribute "'.$key.'[\''.$x.'\']" has invalid '.$label.'. '.$validator->getDescription(); - return false; - } - } - } - } else { - foreach ($validators as $validator) { - if (!$validator->isValid($value)) { - $this->message = 'Attribute "'.$key.'" has invalid '.$label.'. '.$validator->getDescription(); - return false; - } - } - } - } - - return true; - } - /** * Is array * diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index c13fb1530..1fb053416 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15614,6 +15614,48 @@ public function testUpdateDocuments(): void foreach ($updatedDocuments as $document) { $this->assertEquals('text📝 updated all', $document->getAttribute('string')); } + + // Check collection level permissions + $this->getDatabase()->updateCollection($collection, permissions: [ + Permission::read(Role::user('asd')), + Permission::create(Role::user('asd')), + Permission::update(Role::user('asd')), + Permission::delete(Role::user('asd')), + ], documentSecurity: false); + + try { + $this->getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'text📝 updated all', + ])); + $this->fail('Failed to throw exception'); + } catch (AuthorizationException $e) { + $this->assertEquals('Missing "read" permission for role "user:asd". Only "["any"]" scopes are allowed and "["user:asd"]" was given.', $e->getMessage()); + } + + // Check document level permissions + $this->getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); + + $this->getDatabase()->updateDocument($collection, 'doc0', new Document([ + 'string' => 'text📝 updated all', + '$permissions' => [ + Permission::read(Role::user('asd')), + Permission::create(Role::user('asd')), + Permission::update(Role::user('asd')), + Permission::delete(Role::user('asd')), + ], + ])); + + $this->getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'permission text', + ])); + + self::$authorization->skip(function () use ($collection) { + $documents = $this->getDatabase()->find($collection, [ + Query::equal('string', ['permission text']), + ]); + + $this->assertCount(9, $documents); + }); } public function testEvents(): void From 2be9b334a423fea41469af3bb6919905cc07dd54 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 14 Oct 2024 16:15:59 +0900 Subject: [PATCH 074/103] Continue work on permissions --- src/Database/Adapter/MariaDB.php | 2 +- src/Database/Database.php | 42 +++++++++++++++----------------- tests/e2e/Adapter/Base.php | 19 ++++++++------- 3 files changed, 30 insertions(+), 33 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 46c896c55..60645b8ca 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1339,7 +1339,7 @@ public function updateDocuments(string $collection, Document $update, array $que } if ($this->sharedTables) { - $where[] = "_tenant = :_tenant"; + $where[] = "table_main._tenant = :_tenant"; } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; diff --git a/src/Database/Database.php b/src/Database/Database.php index 9ad135bdb..70399725e 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3919,19 +3919,24 @@ public function updateDocuments(string $collection, Document $update, array $que $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds, $update) { $lastDocument = null; - $documentSecurity = $collection->getAttribute('documentSecurity', false); + // Check Collection Security + $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $collection->getUpdate())); + + // Resolve and update relationships while (true) { - $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { - return $this->find($collection->getId(), array_merge( - empty($lastDocument) ? [ - Query::limit($batchSize), - ] : [ - Query::limit($batchSize), - Query::cursorAfter($lastDocument), - ], - $queries, - )); + $affectedDocuments = $this->authorization->skip(function () use ($collection, $queries, $batchSize, $lastDocument) { + $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + return $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + )); + }); }); if (empty($affectedDocuments)) { @@ -3941,17 +3946,6 @@ public function updateDocuments(string $collection, Document $update, array $que $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); foreach ($affectedDocuments as $document) { - // Check permissions for document security - if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ - ...$collection->getUpdate(), - ...($documentSecurity ? $document->getUpdate() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); - } - } - // Update relationship, TODO: Figure out. if ($this->resolveRelationships) { @@ -3967,11 +3961,13 @@ public function updateDocuments(string $collection, Document $update, array $que $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); - $this->adapter->updateDocuments( + $getResults = fn () => $this->adapter->updateDocuments( $collection->getId(), $update, $queries ); + + $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); }); $this->purgeCachedCollection($collection->getId()); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 1fb053416..41be48193 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15535,6 +15535,8 @@ public function testTransformations(): void public function testUpdateDocuments(): void { $collection = 'testUpdateDocuments'; + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); $this->getDatabase()->createCollection($collection, attributes: [ new Document([ @@ -15559,19 +15561,18 @@ public function testUpdateDocuments(): void 'array' => false, 'filters' => [], ]), - ]); + ], permissions: [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ], documentSecurity: false); for ($i = 0; $i < 10; $i++) { $this->getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, 'string' => 'text📝 ' . $i, - 'integer' => $i, - '$permissions' => [ - Permission::read(Role::any()), - Permission::create(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], + 'integer' => $i ])); } @@ -15629,7 +15630,7 @@ public function testUpdateDocuments(): void ])); $this->fail('Failed to throw exception'); } catch (AuthorizationException $e) { - $this->assertEquals('Missing "read" permission for role "user:asd". Only "["any"]" scopes are allowed and "["user:asd"]" was given.', $e->getMessage()); + $this->assertStringStartsWith('Missing "update" permission for role "user:asd".', $e->getMessage()); } // Check document level permissions From 35201c0581d3d68ab9ba31a5ddf99bbd27311ebb Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Tue, 15 Oct 2024 17:15:07 +0900 Subject: [PATCH 075/103] Add Permission Update code for MariaDB --- src/Database/Adapter.php | 4 +- src/Database/Adapter/MariaDB.php | 193 ++++++++++++++++++++++++++++-- src/Database/Adapter/Postgres.php | 2 +- src/Database/Database.php | 15 ++- 4 files changed, 194 insertions(+), 20 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 34c84a9a1..b06ca4f75 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -599,13 +599,13 @@ abstract public function updateDocument(string $collection, Document $document): * * @param string $collection * @param Document $update - * @param array $queries + * @param array $documents * * @return bool * * @throws DatabaseException */ - abstract public function updateDocuments(string $collection, Document $update, array $queries): bool; + abstract public function updateDocuments(string $collection, Document $update, array $documents): bool; /** * Delete Document diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 60645b8ca..ef706ceba 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1307,13 +1307,13 @@ public function updateDocument(string $collection, Document $document): Document * * @param string $collection * @param Document $update - * @param array $queries + * @param array $documents * * @return bool * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries): bool + public function updateDocuments(string $collection, Document $update, array $documents): bool { $attributes = $update->getAttributes(); @@ -1327,15 +1327,11 @@ public function updateDocuments(string $collection, Document $update, array $que $where = []; - $queries = array_map(fn ($query) => clone $query, $queries); - - $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { - $where[] = $conditions; - } + $ids = \array_map(fn ($document) => $document->getId(), $documents); + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles, 'update'); + $where[] = $this->getSQLPermissionsCondition($name, $roles, Database::PERMISSION_UPDATE); } if ($this->sharedTables) { @@ -1366,14 +1362,14 @@ public function updateDocuments(string $collection, Document $update, array $que $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); - foreach ($queries as $query) { - $this->bindConditionValue($stmt, $query); - } - if ($this->sharedTables) { $stmt->bindValue(':_tenant', $this->tenant); } + foreach ($ids as $id => $value) { + $stmt->bindValue(":_id_{$id}", $value); + } + $attributeIndex = 0; foreach ($attributes as $attribute => $value) { if (is_array($value)) { @@ -1388,6 +1384,177 @@ public function updateDocuments(string $collection, Document $update, array $que $stmt->execute(); + // Permissions logic + if (key_exists('_permissions', $attributes)) { + $removeQuery = ''; + $removeBindValues = []; + + $addQuery = ''; + $addBindValues = []; + + /* @var $document Document */ + foreach ($documents as $index => $document) { + $attributes['_permissions'] = json_encode($document->getPermissions()); + + // Permissions logic + $sql = " + SELECT _type, _permission + FROM {$this->getSQLTable($name . '_perms')} + WHERE _document = :_uid + "; + + if ($this->sharedTables) { + $sql .= ' AND _tenant = :_tenant'; + } + + $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); + + $permissionsStmt = $this->getPDO()->prepare($sql); + $permissionsStmt->bindValue(':_uid', $document->getId()); + + if ($this->sharedTables) { + $permissionsStmt->bindValue(':_tenant', $this->tenant); + } + + $permissionsStmt->execute(); + $permissions = $permissionsStmt->fetchAll(); + + $initial = []; + foreach (Database::PERMISSIONS as $type) { + $initial[$type] = []; + } + + $permissions = \array_reduce($permissions, function (array $carry, array $item) { + $carry[$item['_type']][] = $item['_permission']; + return $carry; + }, $initial); + + // Get removed Permissions + $removals = []; + foreach (Database::PERMISSIONS as $type) { + $diff = array_diff($permissions[$type], $document->getPermissionsByType($type)); + if (!empty($diff)) { + $removals[$type] = $diff; + } + } + + // Build inner query to remove permissions + if (!empty($removals)) { + foreach ($removals as $type => $permissionsToRemove) { + $bindKey = 'uid_' . $index; + $removeBindKeys[] = ':uid_' . $index; + $removeBindValues[$bindKey] = $document->getId(); + + $tenantQuery = ''; + if ($this->sharedTables) { + $tenantQuery = ' AND _tenant = :_tenant'; + } + + $removeQuery .= "( + _document = :uid_{$index} + {$tenantQuery} + AND _type = '{$type}' + AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { + $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; + $removeBindKeys[] = ':' . $bindKey; + $removeBindValues[$bindKey] = $permissionsToRemove[$i]; + + return ':' . $bindKey; + }, \array_keys($permissionsToRemove))) . + ") + )"; + + if ($type !== \array_key_last($removals)) { + $removeQuery .= ' OR '; + } + } + + if ($index !== \array_key_last($documents)) { + $removeQuery .= ' OR '; + } + } + + // Get added Permissions + $additions = []; + foreach (Database::PERMISSIONS as $type) { + $diff = \array_diff($document->getPermissionsByType($type), $permissions[$type]); + if (!empty($diff)) { + $additions[$type] = $diff; + } + } + + // Build inner query to add permissions + if (!empty($additions)) { + foreach ($additions as $type => $permissionsToAdd) { + foreach ($permissionsToAdd as $i => $permission) { + $bindKey = 'uid_' . $index; + $addBindValues[$bindKey] = $document->getId(); + + $bindKey = 'add_' . $type . '_' . $index . '_' . $i; + $addBindValues[$bindKey] = $permission; + + $addQuery .= "(:uid_{$index}, '{$type}', :{$bindKey}"; + + if ($this->sharedTables) { + $addQuery .= ", :_tenant)"; + } else { + $addQuery .= ")"; + } + + if ($i !== \array_key_last($permissionsToAdd) || $type !== \array_key_last($additions)) { + $addQuery .= ', '; + } + } + } + if ($index !== \array_key_last($documents)) { + $addQuery .= ', '; + } + } + } + + if (!empty($removeQuery)) { + $stmtRemovePermissions = $this->getPDO()->prepare(" + DELETE + FROM {$this->getSQLTable($name . '_perms')} + WHERE ({$removeQuery}) + "); + + foreach ($removeBindValues as $key => $value) { + $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); + } + if ($this->sharedTables) { + $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); + } + $stmtRemovePermissions->execute(); + } + + if (!empty($addQuery)) { + $sqlAddPermissions = " + INSERT INTO {$this->getSQLTable($name . '_perms')} (`_document`, `_type`, `_permission` + "; + + if ($this->sharedTables) { + $sqlAddPermissions .= ', `_tenant`)'; + } else { + $sqlAddPermissions .= ')'; + } + + $sqlAddPermissions .= " VALUES {$addQuery}"; + + $stmtAddPermissions = $this->getPDO()->prepare($sqlAddPermissions); + + foreach ($addBindValues as $key => $value) { + $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); + } + + if ($this->sharedTables) { + $stmtAddPermissions->bindValue(':_tenant', $this->tenant); + } + + $stmtAddPermissions->execute(); + } + } + return true; } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 94c0ea9cd..308991110 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1258,7 +1258,7 @@ public function updateDocuments(string $collection, Document $update, array $que } if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles, 'update'); + $where[] = $this->getSQLPermissionsCondition($name, $roles, Database::PERMISSION_UPDATE); } if ($this->sharedTables) { diff --git a/src/Database/Database.php b/src/Database/Database.php index 70399725e..ce6b2b641 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3909,15 +3909,21 @@ public function updateDocuments(string $collection, Document $update, array $que $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); + unset($update['$id']); + unset($update['$createdAt']); + unset($update['$updatedAt']); + unset($update['_tenant']); + // Check new document structure $validator = new PartialStructure($collection); if (!$validator->isValid($update)) { throw new StructureException($validator->getDescription()); } + $totalAffectedDocuments = []; $affectedDocumentIds = []; - $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds, $update) { + $this->withTransaction(function () use ($collection, $queries, $batchSize, $totalAffectedDocuments, $affectedDocumentIds, $update) { $lastDocument = null; // Check Collection Security @@ -3926,7 +3932,7 @@ public function updateDocuments(string $collection, Document $update, array $que // Resolve and update relationships while (true) { $affectedDocuments = $this->authorization->skip(function () use ($collection, $queries, $batchSize, $lastDocument) { - $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + return $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { return $this->find($collection->getId(), array_merge( empty($lastDocument) ? [ Query::limit($batchSize), @@ -3943,6 +3949,7 @@ public function updateDocuments(string $collection, Document $update, array $que break; } + $totalAffectedDocuments = array_merge($totalAffectedDocuments, $affectedDocuments); $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); foreach ($affectedDocuments as $document) { @@ -3964,10 +3971,10 @@ public function updateDocuments(string $collection, Document $update, array $que $getResults = fn () => $this->adapter->updateDocuments( $collection->getId(), $update, - $queries + $totalAffectedDocuments ); - $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + $skipAuth ? $this->authorization->skip($getResults) : $getResults(); }); $this->purgeCachedCollection($collection->getId()); From d058140c874ab4f00228049399a1b32ac1a1e4ed Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 16 Oct 2024 13:46:28 +0900 Subject: [PATCH 076/103] Get permission security working with tests apart from mongo --- src/Database/Adapter.php | 3 +- src/Database/Adapter/MariaDB.php | 33 ++- src/Database/Adapter/Mongo.php | 14 +- src/Database/Adapter/Postgres.php | 216 +++++++++++++++++--- src/Database/Database.php | 43 ++-- src/Database/Validator/PartialStructure.php | 17 ++ tests/e2e/Adapter/Base.php | 143 ++++++++++++- 7 files changed, 389 insertions(+), 80 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index b06ca4f75..23cc32d93 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -630,10 +630,11 @@ abstract public function deleteDocument(string $collection, string $id): bool; * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array */ - abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array; + abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::RELATION_SIDE_PARENT): array; /** * Sum an attribute diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index ef706ceba..69e7d5d2a 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1316,13 +1316,16 @@ public function updateDocument(string $collection, Document $document): Document public function updateDocuments(string $collection, Document $update, array $documents): bool { $attributes = $update->getAttributes(); + if (!empty($update->getPermissions())) { + $attributes['_permissions'] = json_encode($update->getPermissions()); + } if (empty($attributes)) { return true; } $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $columns = ''; $where = []; @@ -1330,10 +1333,6 @@ public function updateDocuments(string $collection, Document $update, array $doc $ids = \array_map(fn ($document) => $document->getId(), $documents); $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; - if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles, Database::PERMISSION_UPDATE); - } - if ($this->sharedTables) { $where[] = "table_main._tenant = :_tenant"; } @@ -1346,7 +1345,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $bindKey = 'key_' . $bindIndex; $columns .= "`{$column}`" . '=:' . $bindKey; - if ($bindIndex > 0) { + if ($attribute !== \array_key_last($attributes)) { $columns .= ','; } @@ -1354,10 +1353,10 @@ public function updateDocuments(string $collection, Document $update, array $doc } $sql = " - UPDATE {$this->getSQLTable($name)} AS table_main - SET {$columns} - {$sqlWhere} - "; + UPDATE {$this->getSQLTable($name)} AS table_main + SET {$columns} + {$sqlWhere} + "; $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); @@ -1384,8 +1383,9 @@ public function updateDocuments(string $collection, Document $update, array $doc $stmt->execute(); + // Permissions logic - if (key_exists('_permissions', $attributes)) { + if (!empty($update->getPermissions())) { $removeQuery = ''; $removeBindValues = []; @@ -1394,8 +1394,6 @@ public function updateDocuments(string $collection, Document $update, array $doc /* @var $document Document */ foreach ($documents as $index => $document) { - $attributes['_permissions'] = json_encode($document->getPermissions()); - // Permissions logic $sql = " SELECT _type, _permission @@ -1432,7 +1430,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get removed Permissions $removals = []; foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $document->getPermissionsByType($type)); + $diff = array_diff($permissions[$type], $update->getPermissionsByType($type)); if (!empty($diff)) { $removals[$type] = $diff; } @@ -1477,7 +1475,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get added Permissions $additions = []; foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($document->getPermissionsByType($type), $permissions[$type]); + $diff = \array_diff($update->getPermissionsByType($type), $permissions[$type]); if (!empty($diff)) { $additions[$type] = $diff; } @@ -1686,11 +1684,12 @@ public function deleteDocument(string $collection, string $id): bool * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * @return array * @throws DatabaseException * @throws TimeoutException */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); $roles = $this->authorization->getRoles(); @@ -1780,7 +1779,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles); + $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } if ($this->sharedTables) { diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 4e474bf72..759b8b523 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -840,14 +840,11 @@ public function updateDocuments(string $collection, Document $update, array $que $filters['_tenant'] = (string)$this->getTenant(); } - // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); - $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; - } + $record = $update->getArrayCopy(); + $record = $this->replaceChars('$', '_', $record); $updateQuery = [ - '$set' => $update->getArrayCopy(), + '$set' => $record, ]; try { @@ -961,12 +958,13 @@ public function updateAttribute(string $collection, string $id, string $type, in * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array * @throws Exception * @throws Timeout */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->getNamespace() . '_' . $this->filter($collection); $queries = array_map(fn ($query) => clone $query, $queries); @@ -980,7 +978,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, // permissions if ($this->authorization->getStatus()) { // skip if authorization is disabled $roles = \implode('|', $this->authorization->getRoles()); - $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; + $filters['_permissions']['$in'] = [new Regex("{$forPermission}\(\".*(?:{$roles}).*\"\)", 'i')]; } $options = []; diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 308991110..56a95571d 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1230,39 +1230,34 @@ public function updateDocument(string $collection, Document $document): Document * * @param string $collection * @param Document $update - * @param array $queries + * @param array $documents * * @return bool * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries): bool + public function updateDocuments(string $collection, Document $update, array $documents): bool { $attributes = $update->getAttributes(); + if (!empty($update->getPermissions())) { + $attributes['_permissions'] = json_encode($update->getPermissions()); + } if (empty($attributes)) { return true; } $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $columns = ''; $where = []; - $queries = array_map(fn ($query) => clone $query, $queries); - - $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { - $where[] = $conditions; - } - - if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles, Database::PERMISSION_UPDATE); - } + $ids = \array_map(fn ($document) => $document->getId(), $documents); + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; if ($this->sharedTables) { - $where[] = "_tenant = :_tenant"; + $where[] = "table_main._tenant = :_tenant"; } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; @@ -1273,7 +1268,7 @@ public function updateDocuments(string $collection, Document $update, array $que $bindKey = 'key_' . $bindIndex; $columns .= "\"{$column}\"" . '=:' . $bindKey; - if ($bindIndex > 0) { + if ($attribute !== \array_key_last($attributes)) { $columns .= ','; } @@ -1281,22 +1276,22 @@ public function updateDocuments(string $collection, Document $update, array $que } $sql = " - UPDATE {$this->getSQLTable($name)} AS table_main - SET {$columns} - {$sqlWhere} - "; + UPDATE {$this->getSQLTable($name)} AS table_main + SET {$columns} + {$sqlWhere} + "; $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); - foreach ($queries as $query) { - $this->bindConditionValue($stmt, $query); - } - if ($this->sharedTables) { $stmt->bindValue(':_tenant', $this->tenant); } + foreach ($ids as $id => $value) { + $stmt->bindValue(":_id_{$id}", $value); + } + $attributeIndex = 0; foreach ($attributes as $attribute => $value) { if (is_array($value)) { @@ -1311,6 +1306,176 @@ public function updateDocuments(string $collection, Document $update, array $que $stmt->execute(); + + // Permissions logic + if (!empty($update->getPermissions())) { + $removeQuery = ''; + $removeBindValues = []; + + $addQuery = ''; + $addBindValues = []; + + /* @var $document Document */ + foreach ($documents as $index => $document) { + // Permissions logic + $sql = " + SELECT _type, _permission + FROM {$this->getSQLTable($name . '_perms')} + WHERE _document = :_uid + "; + + if ($this->sharedTables) { + $sql .= ' AND _tenant = :_tenant'; + } + + $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); + + $permissionsStmt = $this->getPDO()->prepare($sql); + $permissionsStmt->bindValue(':_uid', $document->getId()); + + if ($this->sharedTables) { + $permissionsStmt->bindValue(':_tenant', $this->tenant); + } + + $permissionsStmt->execute(); + $permissions = $permissionsStmt->fetchAll(); + + $initial = []; + foreach (Database::PERMISSIONS as $type) { + $initial[$type] = []; + } + + $permissions = \array_reduce($permissions, function (array $carry, array $item) { + $carry[$item['_type']][] = $item['_permission']; + return $carry; + }, $initial); + + // Get removed Permissions + $removals = []; + foreach (Database::PERMISSIONS as $type) { + $diff = array_diff($permissions[$type], $update->getPermissionsByType($type)); + if (!empty($diff)) { + $removals[$type] = $diff; + } + } + + // Build inner query to remove permissions + if (!empty($removals)) { + foreach ($removals as $type => $permissionsToRemove) { + $bindKey = 'uid_' . $index; + $removeBindKeys[] = ':uid_' . $index; + $removeBindValues[$bindKey] = $document->getId(); + + $tenantQuery = ''; + if ($this->sharedTables) { + $tenantQuery = ' AND _tenant = :_tenant'; + } + + $removeQuery .= "( + _document = :uid_{$index} + {$tenantQuery} + AND _type = '{$type}' + AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { + $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; + $removeBindKeys[] = ':' . $bindKey; + $removeBindValues[$bindKey] = $permissionsToRemove[$i]; + + return ':' . $bindKey; + }, \array_keys($permissionsToRemove))) . + ") + )"; + + if ($type !== \array_key_last($removals)) { + $removeQuery .= ' OR '; + } + } + + if ($index !== \array_key_last($documents)) { + $removeQuery .= ' OR '; + } + } + + // Get added Permissions + $additions = []; + foreach (Database::PERMISSIONS as $type) { + $diff = \array_diff($update->getPermissionsByType($type), $permissions[$type]); + if (!empty($diff)) { + $additions[$type] = $diff; + } + } + + // Build inner query to add permissions + if (!empty($additions)) { + foreach ($additions as $type => $permissionsToAdd) { + foreach ($permissionsToAdd as $i => $permission) { + $bindKey = 'uid_' . $index; + $addBindValues[$bindKey] = $document->getId(); + + $bindKey = 'add_' . $type . '_' . $index . '_' . $i; + $addBindValues[$bindKey] = $permission; + + $addQuery .= "(:uid_{$index}, '{$type}', :{$bindKey}"; + + if ($this->sharedTables) { + $addQuery .= ", :_tenant)"; + } else { + $addQuery .= ")"; + } + + if ($i !== \array_key_last($permissionsToAdd) || $type !== \array_key_last($additions)) { + $addQuery .= ', '; + } + } + } + if ($index !== \array_key_last($documents)) { + $addQuery .= ', '; + } + } + } + + if (!empty($removeQuery)) { + $stmtRemovePermissions = $this->getPDO()->prepare(" + DELETE + FROM {$this->getSQLTable($name . '_perms')} + WHERE ({$removeQuery}) + "); + + foreach ($removeBindValues as $key => $value) { + $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); + } + if ($this->sharedTables) { + $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); + } + $stmtRemovePermissions->execute(); + } + + if (!empty($addQuery)) { + $sqlAddPermissions = " + INSERT INTO {$this->getSQLTable($name . '_perms')} (\"_document\", \"_type\", \"_permission\" + "; + + if ($this->sharedTables) { + $sqlAddPermissions .= ', "_tenant")'; + } else { + $sqlAddPermissions .= ')'; + } + + $sqlAddPermissions .= " VALUES {$addQuery}"; + + $stmtAddPermissions = $this->getPDO()->prepare($sqlAddPermissions); + + foreach ($addBindValues as $key => $value) { + $stmtAddPermissions->bindValue($key, $value, $this->getPDOType($value)); + } + + if ($this->sharedTables) { + $stmtAddPermissions->bindValue(':_tenant', $this->tenant); + } + + $stmtAddPermissions->execute(); + } + } + return true; } @@ -1443,13 +1608,14 @@ public function deleteDocument(string $collection, string $id): bool * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array * @throws Exception * @throws PDOException * @throws Timeout */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); $roles = $this->authorization->getRoles(); @@ -1537,7 +1703,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles); + $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; diff --git a/src/Database/Database.php b/src/Database/Database.php index ce6b2b641..93c629949 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3926,37 +3926,40 @@ public function updateDocuments(string $collection, Document $update, array $que $this->withTransaction(function () use ($collection, $queries, $batchSize, $totalAffectedDocuments, $affectedDocumentIds, $update) { $lastDocument = null; - // Check Collection Security + $documentSecurity = $collection->getAttribute('documentSecurity', false); + $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $collection->getUpdate())); + if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { + throw new AuthorizationException($this->authorization->getDescription()); + } + // Resolve and update relationships while (true) { - $affectedDocuments = $this->authorization->skip(function () use ($collection, $queries, $batchSize, $lastDocument) { - return $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { - return $this->find($collection->getId(), array_merge( - empty($lastDocument) ? [ - Query::limit($batchSize), - ] : [ - Query::limit($batchSize), - Query::cursorAfter($lastDocument), - ], - $queries, - )); - }); + $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { + return $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + ), forPermission: Database::PERMISSION_UPDATE); }); if (empty($affectedDocuments)) { break; } - $totalAffectedDocuments = array_merge($totalAffectedDocuments, $affectedDocuments); - $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); - foreach ($affectedDocuments as $document) { // Update relationship, TODO: Figure out. if ($this->resolveRelationships) { } + + $affectedDocumentIds[] = $document->getId(); + $totalAffectedDocuments[] = $document; } if (count($affectedDocuments) < $batchSize) { @@ -5059,13 +5062,14 @@ public function purgeCachedDocument(string $collectionId, string $id): bool * * @param string $collection * @param array $queries + * @param string $forPermission * * @return array * @throws DatabaseException * @throws QueryException * @throws TimeoutException */ - public function find(string $collection, array $queries = []): array + public function find(string $collection, array $queries = [], string $forPermission = Database::PERMISSION_READ): array { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -5089,7 +5093,7 @@ public function find(string $collection, array $queries = []): array $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + $skipAuth = $this->authorization->isValid(new Input($forPermission, $collection->getPermissionsByType($forPermission))); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { throw new AuthorizationException($this->authorization->getDescription()); @@ -5176,7 +5180,8 @@ public function find(string $collection, array $queries = []): array $orderAttributes, $orderTypes, $cursor, - $cursorDirection ?? Database::CURSOR_AFTER + $cursorDirection ?? Database::CURSOR_AFTER, + $forPermission ); $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); diff --git a/src/Database/Validator/PartialStructure.php b/src/Database/Validator/PartialStructure.php index 0f839857d..eb8b56928 100644 --- a/src/Database/Validator/PartialStructure.php +++ b/src/Database/Validator/PartialStructure.php @@ -22,6 +22,21 @@ class PartialStructure extends Validator */ protected Document $collection; + /** + * @var array> + */ + protected array $attributes = [ + [ + '$id' => '$permissions', + 'type' => Database::VAR_STRING, + 'size' => 67000, // medium text + 'required' => false, + 'signed' => true, + 'array' => true, + 'filters' => [], + ] + ]; + /** * @var array */ @@ -152,6 +167,8 @@ public function isValid($document): bool $structure = $document->getArrayCopy(); $attributes = $this->collection->getAttribute('attributes', []); + $attributes = \array_merge($this->attributes, $this->collection->getAttribute('attributes', [])); + $keys = []; foreach ($attributes as $attribute) { $keys[$attribute['$id']] = $attribute; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 41be48193..2bf54dc88 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15636,15 +15636,19 @@ public function testUpdateDocuments(): void // Check document level permissions $this->getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); - $this->getDatabase()->updateDocument($collection, 'doc0', new Document([ - 'string' => 'text📝 updated all', - '$permissions' => [ - Permission::read(Role::user('asd')), - Permission::create(Role::user('asd')), - Permission::update(Role::user('asd')), - Permission::delete(Role::user('asd')), - ], - ])); + $this::$authorization->skip(function () use ($collection) { + $this->getDatabase()->updateDocument($collection, 'doc0', new Document([ + 'string' => 'text📝 updated all', + '$permissions' => [ + Permission::read(Role::user('asd')), + Permission::create(Role::user('asd')), + Permission::update(Role::user('asd')), + Permission::delete(Role::user('asd')), + ], + ])); + }); + + $this::$authorization->addRole(Role::user('asd')->toString()); $this->getDatabase()->updateDocuments($collection, new Document([ 'string' => 'permission text', @@ -15655,10 +15659,129 @@ public function testUpdateDocuments(): void Query::equal('string', ['permission text']), ]); - $this->assertCount(9, $documents); + $this->assertCount(1, $documents); + + $unmodifiedDocuments = $this->getDatabase()->find($collection, [ + Query::equal('string', ['text📝 updated all']), + ]); + + $this->assertCount(9, $unmodifiedDocuments); }); } + public function testUpdateDocumentsPermissions(): void + { + $collection = 'testUpdateDocumentsPerms'; + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); + + $this->getDatabase()->createCollection($collection, attributes: [ + new Document([ + '$id' => ID::custom('string'), + 'type' => Database::VAR_STRING, + 'size' => 767, + 'required' => true, + ]) + ], permissions: [], documentSecurity: true); + + // Test we can bulk update permissions we have access to + $this::$authorization->skip(function () use ($collection) { + for ($i = 0; $i < 10; $i++) { + $this->getDatabase()->createDocument($collection, new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝 ' . $i, + '$permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ], + ])); + } + + $this->getDatabase()->createDocument($collection, new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝 ' . $i, + '$permissions' => [ + Permission::read(Role::user('user1')), + Permission::create(Role::user('user1')), + Permission::update(Role::user('user1')), + Permission::delete(Role::user('user1')) + ], + ])); + }); + + $this->getDatabase()->updateDocuments($collection, new Document([ + '$permissions' => [ + Permission::read(Role::user('user2')), + Permission::create(Role::user('user2')), + Permission::update(Role::user('user2')), + Permission::delete(Role::user('user2')) + ], + ])); + + $documents = $this::$authorization->skip(function () use ($collection) { + return $this->getDatabase()->find($collection); + }); + + $this->assertCount(11, $documents); + + $modifiedDocuments = array_filter($documents, function (Document $document) { + return $document->getAttribute('$permissions') == [ + Permission::read(Role::user('user2')), + Permission::create(Role::user('user2')), + Permission::update(Role::user('user2')), + Permission::delete(Role::user('user2')) + ]; + }); + + $this->assertCount(10, $modifiedDocuments); + + $unmodifiedDocuments = array_filter($documents, function (Document $document) { + return $document->getAttribute('$permissions') == [ + Permission::read(Role::user('user1')), + Permission::create(Role::user('user1')), + Permission::update(Role::user('user1')), + Permission::delete(Role::user('user1')) + ]; + }); + + $this->assertCount(1, $unmodifiedDocuments); + + $this::$authorization->addRole(Role::user('user2')->toString()); + + // Test Bulk permission update with data + $this->getDatabase()->updateDocuments($collection, new Document([ + '$permissions' => [ + Permission::read(Role::user('user3')), + Permission::create(Role::user('user3')), + Permission::update(Role::user('user3')), + Permission::delete(Role::user('user3')) + ], + 'string' => 'text📝 updated', + ])); + + $documents = $this::$authorization + ->skip(function () use ($collection) { + return $this->getDatabase()->find($collection); + }); + + $this->assertCount(11, $documents); + + $modifiedDocuments = array_filter($documents, function (Document $document) { + return $document->getAttribute('$permissions') == [ + Permission::read(Role::user('user3')), + Permission::create(Role::user('user3')), + Permission::update(Role::user('user3')), + Permission::delete(Role::user('user3')) + ]; + }); + + foreach ($modifiedDocuments as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + } + } + public function testEvents(): void { self::$authorization->skip(function () { From 31d6bea142eeb623e6282b1bbc34ff349c64221c Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 16 Oct 2024 15:07:12 +0900 Subject: [PATCH 077/103] Fix Mongo and phpstan issues --- src/Database/Adapter.php | 2 +- src/Database/Adapter/MariaDB.php | 2 +- src/Database/Adapter/Mongo.php | 9 ++++++--- src/Database/Adapter/Postgres.php | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 23cc32d93..eac26881b 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -599,7 +599,7 @@ abstract public function updateDocument(string $collection, Document $document): * * @param string $collection * @param Document $update - * @param array $documents + * @param array $documents * * @return bool * diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 69e7d5d2a..d33397140 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1337,7 +1337,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $where[] = "table_main._tenant = :_tenant"; } - $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + $sqlWhere = 'WHERE ' . implode(' AND ', $where); $bindIndex = 0; foreach ($attributes as $attribute => $value) { diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 759b8b523..ca307ab3f 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -824,17 +824,20 @@ public function updateDocument(string $collection, Document $document): Document * * @param string $collection * @param Document $update - * @param array $queries + * @param array $documents * * @return bool * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries): bool + public function updateDocuments(string $collection, Document $update, array $documents): bool { $name = $this->getNamespace() . '_' . $this->filter($collection); - $queries = array_map(fn ($query) => clone $query, $queries); + $queries = [ + Query::equal('$id', array_map(fn ($document) => $document->getId(), $documents)) + ]; + $filters = $this->buildFilters($queries); if ($this->sharedTables) { $filters['_tenant'] = (string)$this->getTenant(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 56a95571d..b31e2cb2f 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1260,7 +1260,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $where[] = "table_main._tenant = :_tenant"; } - $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; + $sqlWhere = 'WHERE ' . implode(' AND ', $where); $bindIndex = 0; foreach ($attributes as $attribute => $value) { From 161b561126794f4956c7fc57f1af6a07a590567f Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 16 Oct 2024 15:09:23 +0900 Subject: [PATCH 078/103] Run Linter --- src/Database/Adapter/Mongo.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index ca307ab3f..41c64efb9 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -837,7 +837,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $queries = [ Query::equal('$id', array_map(fn ($document) => $document->getId(), $documents)) ]; - + $filters = $this->buildFilters($queries); if ($this->sharedTables) { $filters['_tenant'] = (string)$this->getTenant(); From 66e0736104adb4d3fb6d165a70a1ae7e2e471b0c Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Wed, 16 Oct 2024 15:41:28 +0900 Subject: [PATCH 079/103] Use new event for bulk delete --- src/Database/Database.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 417e5bea8..22d056d63 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -114,6 +114,7 @@ class Database public const EVENT_DOCUMENT_FIND = 'document_find'; public const EVENT_DOCUMENT_CREATE = 'document_create'; public const EVENT_DOCUMENTS_CREATE = 'documents_create'; + public const EVENT_DOCUMENTS_DELETE = 'documents_delete'; public const EVENT_DOCUMENT_READ = 'document_read'; public const EVENT_DOCUMENT_UPDATE = 'document_update'; public const EVENT_DOCUMENTS_UPDATE = 'documents_update'; @@ -4997,6 +4998,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; + while (true) { $affectedDocuments = $this->find($collection->getId(), array_merge( empty($lastDocument) ? [ @@ -5031,9 +5033,6 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $document = $this->silent(fn () => $this->deleteDocumentRelationships($collection, $document)); } - // Fire events - $this->trigger(self::EVENT_DOCUMENT_DELETE, $document); - $this->purgeRelatedDocuments($collection, $document->getId()); $this->purgeCachedDocument($collection->getId(), $document->getId()); } @@ -5045,6 +5044,8 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba } } + $this->trigger(self::EVENT_DOCUMENTS_DELETE, $affectedDocumentIds); + // Mass delete using adapter with query return $this->adapter->deleteDocuments($collection->getId(), $affectedDocumentIds); }); From 51e39ac6a9d8a5d549c088e3acfa0e93b93817ca Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 17 Oct 2024 12:41:00 +0900 Subject: [PATCH 080/103] Add relationship tests, return amount of documents modified --- src/Database/Adapter.php | 11 +++- src/Database/Adapter/MariaDB.php | 18 ++++-- src/Database/Adapter/Mongo.php | 16 +++++- src/Database/Adapter/Postgres.php | 18 ++++-- src/Database/Database.php | 6 ++ tests/e2e/Adapter/Base.php | 95 ++++++++++++++++++++++++++++++- 6 files changed, 149 insertions(+), 15 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index eac26881b..5cafcbbe8 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -601,11 +601,11 @@ abstract public function updateDocument(string $collection, Document $document): * @param Document $update * @param array $documents * - * @return bool + * @return int * * @throws DatabaseException */ - abstract public function updateDocuments(string $collection, Document $update, array $documents): bool; + abstract public function updateDocuments(string $collection, Document $update, array $documents): int; /** * Delete Document @@ -778,6 +778,13 @@ abstract public function getSupportForRelationships(): bool; abstract public function getSupportForUpdateLock(): bool; + /** + * Are batch operations supported? + * + * @return bool + */ + abstract public function getSupportForBatchOperations(): bool; + /** * Is attribute resizing supported? * diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index d33397140..e37130128 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1309,11 +1309,11 @@ public function updateDocument(string $collection, Document $document): Document * @param Document $update * @param array $documents * - * @return bool + * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): bool + public function updateDocuments(string $collection, Document $update, array $documents): int { $attributes = $update->getAttributes(); if (!empty($update->getPermissions())) { @@ -1382,7 +1382,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } $stmt->execute(); - + $affected = $stmt->rowCount(); // Permissions logic if (!empty($update->getPermissions())) { @@ -1553,7 +1553,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } } - return true; + return $affected; } /** @@ -2240,6 +2240,16 @@ public function getSupportForTimeouts(): bool return true; } + /** + * Are batch operations supported? + * + * @return bool + */ + public function getSupportForBatchOperations(): bool + { + return true; + } + /** * Set max execution time * @param int $milliseconds diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 41c64efb9..10010511d 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -826,11 +826,11 @@ public function updateDocument(string $collection, Document $document): Document * @param Document $update * @param array $documents * - * @return bool + * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): bool + public function updateDocuments(string $collection, Document $update, array $documents): int { $name = $this->getNamespace() . '_' . $this->filter($collection); @@ -856,7 +856,7 @@ public function updateDocuments(string $collection, Document $update, array $doc throw new Duplicate($e->getMessage()); } - return true; + return 1; } /** @@ -1689,6 +1689,16 @@ public function getSupportForAttributeResizing(): bool return false; } + /** + * Are batch operations supported? + * + * @return bool + */ + public function getSupportForBatchOperations(): bool + { + return false; + } + /** * Get current attribute count from collection document * diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index b31e2cb2f..25fb92c55 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1232,11 +1232,11 @@ public function updateDocument(string $collection, Document $document): Document * @param Document $update * @param array $documents * - * @return bool + * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): bool + public function updateDocuments(string $collection, Document $update, array $documents): int { $attributes = $update->getAttributes(); if (!empty($update->getPermissions())) { @@ -1305,7 +1305,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } $stmt->execute(); - + $affected = $stmt->rowCount(); // Permissions logic if (!empty($update->getPermissions())) { @@ -1476,7 +1476,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } } - return true; + return $affected; } /** @@ -2212,6 +2212,16 @@ public function getSupportForJSONOverlaps(): bool return false; } + /** + * Are batch operations supported? + * + * @return bool + */ + public function getSupportForBatchOperations(): bool + { + return true; + } + /** * Returns Max Execution Time * @param int $milliseconds diff --git a/src/Database/Database.php b/src/Database/Database.php index 93c629949..22c205789 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3955,7 +3955,9 @@ public function updateDocuments(string $collection, Document $update, array $que foreach ($affectedDocuments as $document) { // Update relationship, TODO: Figure out. if ($this->resolveRelationships) { + $newDocument = array_merge($document->getArrayCopy(), $update->getArrayCopy()); + $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, new Document($newDocument))); } $affectedDocumentIds[] = $document->getId(); @@ -3969,6 +3971,10 @@ public function updateDocuments(string $collection, Document $update, array $que } } + if (empty($totalAffectedDocuments)) { + return; + } + $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); $getResults = fn () => $this->adapter->updateDocuments( diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 2bf54dc88..7d1bc4aad 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15534,6 +15534,11 @@ public function testTransformations(): void public function testUpdateDocuments(): void { + if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + $collection = 'testUpdateDocuments'; self::$authorization->cleanRoles(); self::$authorization->addRole(Role::any()->toString()); @@ -15577,12 +15582,14 @@ public function testUpdateDocuments(): void } // Test Update half of the documents - $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = $this->getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated', ]), [ Query::greaterThanEqual('integer', 5), ]); + $this->assertEquals($affected, 5); + $updatedDocuments = $this->getDatabase()->find($collection, [ Query::greaterThanEqual('integer', 5), ]); @@ -15604,10 +15611,12 @@ public function testUpdateDocuments(): void } // Test Update all documents - $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = $this->getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated all', ])); + $this->assertEquals(5, $affected); + $updatedDocuments = $this->getDatabase()->find($collection); $this->assertEquals(count($updatedDocuments), 10); @@ -15671,6 +15680,11 @@ public function testUpdateDocuments(): void public function testUpdateDocumentsPermissions(): void { + if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + $collection = 'testUpdateDocumentsPerms'; self::$authorization->cleanRoles(); self::$authorization->addRole(Role::any()->toString()); @@ -15782,6 +15796,83 @@ public function testUpdateDocumentsPermissions(): void } } + public function testUpdateDocumentsRelationships(): void + { + if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); + + $this->getDatabase()->createCollection('testUpdateDocumentsRelationships1', attributes: [ + new Document([ + '$id' => ID::custom('string'), + 'type' => Database::VAR_STRING, + 'size' => 767, + 'required' => true, + ]) + ], permissions: [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ]); + + $this->getDatabase()->createCollection('testUpdateDocumentsRelationships2', attributes: [ + new Document([ + '$id' => ID::custom('string'), + 'type' => Database::VAR_STRING, + 'size' => 767, + 'required' => true, + ]) + ], permissions: [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ]); + + $this->getDatabase()->createRelationship( + collection: 'testUpdateDocumentsRelationships1', + relatedCollection: 'testUpdateDocumentsRelationships2', + type: Database::RELATION_ONE_TO_ONE, + twoWay: true, + ); + + $this::$authorization->skip(function () { + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ + '$id' => 'doc1', + 'string' => 'text📝', + ])); + + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ + '$id' => 'doc2', + 'string' => 'text📝', + 'testUpdateDocumentsRelationships1' => 'doc1' + ])); + }); + + $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc2'); + $this->assertNotNull($sisterDocument); + + $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships1', new Document([ + 'string' => 'text📝 updated', + ])); + + $document = $this->getDatabase()->findOne('testUpdateDocumentsRelationships1'); + + $this->assertNotFalse($document); + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + + $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc2'); + $this->assertNotNull($sisterDocument); + + $relationalDocument = $sisterDocument->getAttribute('testUpdateDocumentsRelationships1'); + $this->assertEquals('text📝 updated', $relationalDocument->getAttribute('string')); + } + public function testEvents(): void { self::$authorization->skip(function () { From 619a7a216616b16e34ba36895471d0246ec71c92 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 17 Oct 2024 12:44:26 +0900 Subject: [PATCH 081/103] Run Linter, Address PHPStan --- src/Database/Adapter.php | 2 +- src/Database/Adapter/MariaDB.php | 4 ++-- src/Database/Adapter/Mongo.php | 2 +- src/Database/Adapter/Postgres.php | 4 ++-- tests/e2e/Adapter/Base.php | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 5cafcbbe8..032f95a4f 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -780,7 +780,7 @@ abstract public function getSupportForUpdateLock(): bool; /** * Are batch operations supported? - * + * * @return bool */ abstract public function getSupportForBatchOperations(): bool; diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index e37130128..a258c580d 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1321,7 +1321,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } if (empty($attributes)) { - return true; + return 0; } $name = $this->filter($collection); @@ -2242,7 +2242,7 @@ public function getSupportForTimeouts(): bool /** * Are batch operations supported? - * + * * @return bool */ public function getSupportForBatchOperations(): bool diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 10010511d..37c541f21 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -1691,7 +1691,7 @@ public function getSupportForAttributeResizing(): bool /** * Are batch operations supported? - * + * * @return bool */ public function getSupportForBatchOperations(): bool diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 25fb92c55..07f7671c3 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1244,7 +1244,7 @@ public function updateDocuments(string $collection, Document $update, array $doc } if (empty($attributes)) { - return true; + return 0; } $name = $this->filter($collection); @@ -2214,7 +2214,7 @@ public function getSupportForJSONOverlaps(): bool /** * Are batch operations supported? - * + * * @return bool */ public function getSupportForBatchOperations(): bool diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 7d1bc4aad..36070a0b2 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15868,7 +15868,7 @@ public function testUpdateDocumentsRelationships(): void $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc2'); $this->assertNotNull($sisterDocument); - + $relationalDocument = $sisterDocument->getAttribute('testUpdateDocumentsRelationships1'); $this->assertEquals('text📝 updated', $relationalDocument->getAttribute('string')); } From ce1f15ed36907fa76fb59fb792f0419cb334e483 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 17 Oct 2024 12:50:33 +0900 Subject: [PATCH 082/103] Fix Affected count --- src/Database/Database.php | 10 +++++----- tests/e2e/Adapter/Base.php | 5 +++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 22c205789..ecb9e99cc 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3892,11 +3892,11 @@ public function updateDocument(string $collection, string $id, Document $documen * @param array $queries * @param int $batchSize * - * @return bool + * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): bool + public function updateDocuments(string $collection, Document $update, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -3923,7 +3923,7 @@ public function updateDocuments(string $collection, Document $update, array $que $totalAffectedDocuments = []; $affectedDocumentIds = []; - $this->withTransaction(function () use ($collection, $queries, $batchSize, $totalAffectedDocuments, $affectedDocumentIds, $update) { + $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $totalAffectedDocuments, $affectedDocumentIds, $update) { $lastDocument = null; $documentSecurity = $collection->getAttribute('documentSecurity', false); @@ -3983,12 +3983,12 @@ public function updateDocuments(string $collection, Document $update, array $que $totalAffectedDocuments ); - $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + return $skipAuth ? $this->authorization->skip($getResults) : $getResults(); }); $this->purgeCachedCollection($collection->getId()); - return true; + return $affected; } /** diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 36070a0b2..e9a03c463 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15615,7 +15615,7 @@ public function testUpdateDocuments(): void 'string' => 'text📝 updated all', ])); - $this->assertEquals(5, $affected); + $this->assertEquals(10, $affected); $updatedDocuments = $this->getDatabase()->find($collection); @@ -15725,7 +15725,7 @@ public function testUpdateDocumentsPermissions(): void ])); }); - $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = $this->getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::user('user2')), Permission::create(Role::user('user2')), @@ -15738,6 +15738,7 @@ public function testUpdateDocumentsPermissions(): void return $this->getDatabase()->find($collection); }); + $this->assertEquals(10, $affected); $this->assertCount(11, $documents); $modifiedDocuments = array_filter($documents, function (Document $document) { From 20ea1fadf13a7dbaf34c2e24b787e7f650518f81 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 17 Oct 2024 12:52:22 +0900 Subject: [PATCH 083/103] Fix SQLite because it doesn't support relationships --- tests/e2e/Adapter/Base.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index e9a03c463..f3e65799d 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15799,7 +15799,7 @@ public function testUpdateDocumentsPermissions(): void public function testUpdateDocumentsRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations() || !$this->getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } From 4523393c02fd4a22271391a62971193cbeff99d5 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Thu, 17 Oct 2024 12:53:32 +0900 Subject: [PATCH 084/103] Phpstan --- src/Database/Database.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index ecb9e99cc..0d89522f9 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3903,7 +3903,7 @@ public function updateDocuments(string $collection, Document $update, array $que } if (empty($update->getArrayCopy())) { - return true; + return 0; } $queries = Query::groupByType($queries)['filters']; From 0374d6e9e75527e94de01332d8991a7cbcf3e3e4 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 18 Oct 2024 12:26:25 +0900 Subject: [PATCH 085/103] Address comments --- src/Database/Adapter.php | 6 +- src/Database/Adapter/MariaDB.php | 39 ++- src/Database/Adapter/Mongo.php | 16 +- src/Database/Adapter/Postgres.php | 39 ++- src/Database/Adapter/SQL.php | 12 +- src/Database/Adapter/SQLite.php | 2 +- src/Database/Database.php | 52 ++-- src/Database/Validator/PartialStructure.php | 265 +------------------- src/Database/Validator/Structure.php | 54 ++++ tests/e2e/Adapter/Base.php | 145 +++++++---- 10 files changed, 247 insertions(+), 383 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 032f95a4f..65b3c7f89 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -598,14 +598,14 @@ abstract public function updateDocument(string $collection, Document $document): * Batch update documents * * @param string $collection - * @param Document $update + * @param Document $updates * @param array $documents * * @return int * * @throws DatabaseException */ - abstract public function updateDocuments(string $collection, Document $update, array $documents): int; + abstract public function updateDocuments(string $collection, Document $updates, array $documents): int; /** * Delete Document @@ -634,7 +634,7 @@ abstract public function deleteDocument(string $collection, string $id): bool; * * @return array */ - abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::RELATION_SIDE_PARENT): array; + abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array; /** * Sum an attribute diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index a258c580d..44b009328 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1306,18 +1306,23 @@ public function updateDocument(string $collection, Document $document): Document * Batch update documents * * @param string $collection - * @param Document $update + * @param Document $updates * @param array $documents * * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): int + public function updateDocuments(string $collection, Document $updates, array $documents): int { - $attributes = $update->getAttributes(); - if (!empty($update->getPermissions())) { - $attributes['_permissions'] = json_encode($update->getPermissions()); + $attributes = $updates->getAttributes(); + + if (!empty($updates->getUpdatedAt())) { + $attributes['_updatedAt'] = $updates->getUpdatedAt(); + } + + if (!empty($updates->getPermissions())) { + $attributes['_permissions'] = json_encode($updates->getPermissions()); } if (empty($attributes)) { @@ -1331,10 +1336,10 @@ public function updateDocuments(string $collection, Document $update, array $doc $where = []; $ids = \array_map(fn ($document) => $document->getId(), $documents); - $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ")"; if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "_tenant = :_tenant"; } $sqlWhere = 'WHERE ' . implode(' AND ', $where); @@ -1353,12 +1358,12 @@ public function updateDocuments(string $collection, Document $update, array $doc } $sql = " - UPDATE {$this->getSQLTable($name)} AS table_main + UPDATE {$this->getSQLTable($name)} SET {$columns} {$sqlWhere} "; - $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); + $sql = $this->trigger(Database::EVENT_DOCUMENTS_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); if ($this->sharedTables) { @@ -1385,7 +1390,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $affected = $stmt->rowCount(); // Permissions logic - if (!empty($update->getPermissions())) { + if (!empty($updates->getPermissions())) { $removeQuery = ''; $removeBindValues = []; @@ -1430,7 +1435,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get removed Permissions $removals = []; foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $update->getPermissionsByType($type)); + $diff = array_diff($permissions[$type], $updates->getPermissionsByType($type)); if (!empty($diff)) { $removals[$type] = $diff; } @@ -1475,7 +1480,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get added Permissions $additions = []; foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($update->getPermissionsByType($type), $permissions[$type]); + $diff = \array_diff($updates->getPermissionsByType($type), $permissions[$type]); if (!empty($diff)) { $additions[$type] = $diff; } @@ -2240,16 +2245,6 @@ public function getSupportForTimeouts(): bool return true; } - /** - * Are batch operations supported? - * - * @return bool - */ - public function getSupportForBatchOperations(): bool - { - return true; - } - /** * Set max execution time * @param int $milliseconds diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 37c541f21..1585c295c 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -823,14 +823,14 @@ public function updateDocument(string $collection, Document $document): Document * Batch update documents * * @param string $collection - * @param Document $update + * @param Document $updates * @param array $documents * * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): int + public function updateDocuments(string $collection, Document $updates, array $documents): int { $name = $this->getNamespace() . '_' . $this->filter($collection); @@ -843,8 +843,9 @@ public function updateDocuments(string $collection, Document $update, array $doc $filters['_tenant'] = (string)$this->getTenant(); } - $record = $update->getArrayCopy(); + $record = $updates->getArrayCopy(); $record = $this->replaceChars('$', '_', $record); + $record = $this->timeToMongo($record); $updateQuery = [ '$set' => $record, @@ -1172,8 +1173,13 @@ private function timeToDocument(array $record): array */ private function timeToMongo(array $record): array { - $record['_createdAt'] = $this->toMongoDatetime($record['_createdAt']); - $record['_updatedAt'] = $this->toMongoDatetime($record['_updatedAt']); + if (isset($record['_createdAt'])) { + $record['_createdAt'] = $this->toMongoDatetime($record['_createdAt']); + } + + if (isset($record['_updatedAt'])) { + $record['_updatedAt'] = $this->toMongoDatetime($record['_updatedAt']); + } return $record; } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 07f7671c3..8143bb5b3 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1229,18 +1229,23 @@ public function updateDocument(string $collection, Document $document): Document * Batch update documents * * @param string $collection - * @param Document $update + * @param Document $updates * @param array $documents * * @return int * * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $documents): int + public function updateDocuments(string $collection, Document $updates, array $documents): int { - $attributes = $update->getAttributes(); - if (!empty($update->getPermissions())) { - $attributes['_permissions'] = json_encode($update->getPermissions()); + $attributes = $updates->getAttributes(); + + if (!empty($updates->getUpdatedAt())) { + $attributes['_updatedAt'] = $updates->getUpdatedAt(); + } + + if (!empty($updates->getPermissions())) { + $attributes['_permissions'] = json_encode($updates->getPermissions()); } if (empty($attributes)) { @@ -1254,10 +1259,10 @@ public function updateDocuments(string $collection, Document $update, array $doc $where = []; $ids = \array_map(fn ($document) => $document->getId(), $documents); - $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ")"; if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "_tenant = :_tenant"; } $sqlWhere = 'WHERE ' . implode(' AND ', $where); @@ -1276,12 +1281,12 @@ public function updateDocuments(string $collection, Document $update, array $doc } $sql = " - UPDATE {$this->getSQLTable($name)} AS table_main + UPDATE {$this->getSQLTable($name)} SET {$columns} {$sqlWhere} "; - $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); + $sql = $this->trigger(Database::EVENT_DOCUMENTS_UPDATE, $sql); $stmt = $this->getPDO()->prepare($sql); if ($this->sharedTables) { @@ -1308,7 +1313,7 @@ public function updateDocuments(string $collection, Document $update, array $doc $affected = $stmt->rowCount(); // Permissions logic - if (!empty($update->getPermissions())) { + if (!empty($updates->getPermissions())) { $removeQuery = ''; $removeBindValues = []; @@ -1353,7 +1358,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get removed Permissions $removals = []; foreach (Database::PERMISSIONS as $type) { - $diff = array_diff($permissions[$type], $update->getPermissionsByType($type)); + $diff = array_diff($permissions[$type], $updates->getPermissionsByType($type)); if (!empty($diff)) { $removals[$type] = $diff; } @@ -1398,7 +1403,7 @@ public function updateDocuments(string $collection, Document $update, array $doc // Get added Permissions $additions = []; foreach (Database::PERMISSIONS as $type) { - $diff = \array_diff($update->getPermissionsByType($type), $permissions[$type]); + $diff = \array_diff($updates->getPermissionsByType($type), $permissions[$type]); if (!empty($diff)) { $additions[$type] = $diff; } @@ -2212,16 +2217,6 @@ public function getSupportForJSONOverlaps(): bool return false; } - /** - * Are batch operations supported? - * - * @return bool - */ - public function getSupportForBatchOperations(): bool - { - return true; - } - /** * Returns Max Execution Time * @param int $milliseconds diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index 2049943cb..98efafa79 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -361,6 +361,16 @@ public function getSupportForAttributeResizing(): bool return true; } + /** + * Are batch operations supported? + * + * @return bool + */ + public function getSupportForBatchOperations(): bool + { + return true; + } + /** * Get current attribute count from collection document * @@ -968,7 +978,7 @@ protected function getSQLIndexType(string $type): string * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = 'read'): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = Database::PERMISSION_READ): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 1ae62ac1c..69e9d51ad 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -963,7 +963,7 @@ protected function getSQLIndex(string $collection, string $id, string $type, arr * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = 'read'): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = Database::PERMISSION_READ): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); return "table_main._uid IN ( diff --git a/src/Database/Database.php b/src/Database/Database.php index 0d89522f9..58e7c6f44 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3885,7 +3885,9 @@ public function updateDocument(string $collection, string $id, Document $documen } /** - * Batch update documents + * Update documents + * + * Updates all documents which match the given query. * * @param string $collection * @param Document $update @@ -3894,6 +3896,7 @@ public function updateDocument(string $collection, string $id, Document $documen * * @return int * + * @throws AuthorizationException * @throws DatabaseException */ public function updateDocuments(string $collection, Document $update, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int @@ -3902,7 +3905,7 @@ public function updateDocuments(string $collection, Document $update, array $que throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - if (empty($update->getArrayCopy())) { + if ($update->isEmpty()) { return 0; } @@ -3911,8 +3914,14 @@ public function updateDocuments(string $collection, Document $update, array $que unset($update['$id']); unset($update['$createdAt']); - unset($update['$updatedAt']); - unset($update['_tenant']); + unset($update['$tenant']); + + if (!$this->preserveDates) { + unset($update['$updatedAt']); + $update['$updatedAt'] = DateTime::now(); + } + + $update = $this->encode($collection, $update); // Check new document structure $validator = new PartialStructure($collection); @@ -3920,11 +3929,10 @@ public function updateDocuments(string $collection, Document $update, array $que throw new StructureException($validator->getDescription()); } - $totalAffectedDocuments = []; - $affectedDocumentIds = []; - - $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $totalAffectedDocuments, $affectedDocumentIds, $update) { + $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $update) { $lastDocument = null; + $totalModified = 0; + $affectedDocumentIds = []; $documentSecurity = $collection->getAttribute('documentSecurity', false); @@ -3953,7 +3961,6 @@ public function updateDocuments(string $collection, Document $update, array $que } foreach ($affectedDocuments as $document) { - // Update relationship, TODO: Figure out. if ($this->resolveRelationships) { $newDocument = array_merge($document->getArrayCopy(), $update->getArrayCopy()); @@ -3964,6 +3971,16 @@ public function updateDocuments(string $collection, Document $update, array $que $totalAffectedDocuments[] = $document; } + $getResults = fn () => $this->adapter->updateDocuments( + $collection->getId(), + $update, + $affectedDocuments + ); + + $result = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + + $totalModified += $result; + if (count($affectedDocuments) < $batchSize) { break; } else { @@ -3971,23 +3988,16 @@ public function updateDocuments(string $collection, Document $update, array $que } } - if (empty($totalAffectedDocuments)) { - return; - } - $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); - $getResults = fn () => $this->adapter->updateDocuments( - $collection->getId(), - $update, - $totalAffectedDocuments - ); + foreach ($affectedDocumentIds as $id) { + $this->purgeRelatedDocuments($collection, $id); + $this->purgeCachedDocument($collection->getId(), $id); + } - return $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + return $result ?? 0; }); - $this->purgeCachedCollection($collection->getId()); - return $affected; } diff --git a/src/Database/Validator/PartialStructure.php b/src/Database/Validator/PartialStructure.php index eb8b56928..69d4703ca 100644 --- a/src/Database/Validator/PartialStructure.php +++ b/src/Database/Validator/PartialStructure.php @@ -2,146 +2,11 @@ namespace Utopia\Database\Validator; -use Closure; -use Exception; use Utopia\Database\Database; use Utopia\Database\Document; -use Utopia\Database\Exception as DatabaseException; -use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Http\Validator; -use Utopia\Http\Validator\Boolean; -use Utopia\Http\Validator\FloatValidator; -use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Range; -use Utopia\Http\Validator\Text; -class PartialStructure extends Validator +class PartialStructure extends Structure { - /** - * @var Document - */ - protected Document $collection; - - /** - * @var array> - */ - protected array $attributes = [ - [ - '$id' => '$permissions', - 'type' => Database::VAR_STRING, - 'size' => 67000, // medium text - 'required' => false, - 'signed' => true, - 'array' => true, - 'filters' => [], - ] - ]; - - /** - * @var array - */ - protected static array $formats = []; - - /** - * @var string - */ - protected string $message = 'General Error'; - - /** - * Structure constructor. - * - */ - public function __construct(Document $collection) - { - $this->collection = $collection; - } - - /** - * Remove a Validator - * - * @return array - */ - public static function getFormats(): array - { - return self::$formats; - } - - /** - * Add a new Validator - * Stores a callback and required params to create Validator - * - * @param string $name - * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Http\Validator - * @param string $type Primitive data type for validation - */ - public static function addFormat(string $name, Closure $callback, string $type): void - { - self::$formats[$name] = [ - 'callback' => $callback, - 'type' => $type, - ]; - } - - /** - * Check if validator has been added - * - * @param string $name - * - * @return bool - */ - public static function hasFormat(string $name, string $type): bool - { - if (isset(self::$formats[$name]) && self::$formats[$name]['type'] === $type) { - return true; - } - - return false; - } - - /** - * Get a Format array to create Validator - * - * @param string $name - * @param string $type - * - * @return array{callback: callable, type: string} - * @throws Exception - */ - public static function getFormat(string $name, string $type): array - { - if (isset(self::$formats[$name])) { - if (self::$formats[$name]['type'] !== $type) { - throw new DatabaseException('Format "'.$name.'" not available for attribute type "'.$type.'"'); - } - - return self::$formats[$name]; - } - - throw new DatabaseException('Unknown format validator "'.$name.'"'); - } - - /** - * Remove a Validator - * - * @param string $name - */ - public static function removeFormat(string $name): void - { - unset(self::$formats[$name]); - } - - /** - * Get Description. - * - * Returns validator description - * - * @return string - */ - public function getDescription(): string - { - return 'Invalid document structure: '.$this->message; - } - /** * Is valid. * @@ -169,133 +34,19 @@ public function isValid($document): bool $attributes = \array_merge($this->attributes, $this->collection->getAttribute('attributes', [])); - $keys = []; foreach ($attributes as $attribute) { - $keys[$attribute['$id']] = $attribute; + $name = $attribute['$id'] ?? ''; + $keys[$name] = $attribute; } - foreach ($structure as $key => $value) { - if (!array_key_exists($key, $keys)) { // Check no unknown attributes are set - $this->message = 'Unknown attribute: "'.$key.'"'; - return false; - } - - $attribute = $keys[$key] ?? []; - $type = $attribute['type'] ?? ''; - $array = $attribute['array'] ?? false; - $format = $attribute['format'] ?? ''; - $required = $attribute['required'] ?? false; - $size = $attribute['size'] ?? 0; - $signed = $attribute['signed'] ?? true; - - if ($required === false && is_null($value)) { // Allow null value to optional params - continue; - } - - if ($type === Database::VAR_RELATIONSHIP) { - continue; - } - - $validators = []; - - switch ($type) { - case Database::VAR_STRING: - $validators[] = new Text($size, min: 0); - break; - - case Database::VAR_INTEGER: - // We need both Integer and Range because Range implicitly casts non-numeric values - $validators[] = new Integer(); - $max = $size >= 8 ? Database::BIG_INT_MAX : Database::INT_MAX; - $min = $signed ? -$max : 0; - $validators[] = new Range($min, $max, Database::VAR_INTEGER); - break; - - case Database::VAR_FLOAT: - // We need both Float and Range because Range implicitly casts non-numeric values - $validators[] = new FloatValidator(); - $min = $signed ? -Database::DOUBLE_MAX : 0; - $validators[] = new Range($min, Database::DOUBLE_MAX, Database::VAR_FLOAT); - break; - - case Database::VAR_BOOLEAN: - $validators[] = new Boolean(); - break; - - case Database::VAR_DATETIME: - $validators[] = new DatetimeValidator(); - break; - - default: - $this->message = 'Unknown attribute type "'.$type.'"'; - return false; - } - - /** Error message label, either 'format' or 'type' */ - $label = ($format) ? 'format' : 'type'; - - if ($format) { - // Format encoded as json string containing format name and relevant format options - $format = self::getFormat($format, $type); - $validators[] = $format['callback']($attribute); - } - - if ($array) { // Validate attribute type for arrays - format for arrays handled separately - if (!$required && ((is_array($value) && empty($value)) || is_null($value))) { // Allow both null and [] for optional arrays - continue; - } - - if (!\is_array($value) || !\array_is_list($value)) { - $this->message = 'Attribute "'.$key.'" must be an array'; - return false; - } - - foreach ($value as $x => $child) { - if (!$required && is_null($child)) { // Allow null value to optional params - continue; - } + if (!$this->checkForUnknownAttributes($structure, $keys)) { + return false; + } - foreach ($validators as $validator) { - if (!$validator->isValid($child)) { - $this->message = 'Attribute "'.$key.'[\''.$x.'\']" has invalid '.$label.'. '.$validator->getDescription(); - return false; - } - } - } - } else { - foreach ($validators as $validator) { - if (!$validator->isValid($value)) { - $this->message = 'Attribute "'.$key.'" has invalid '.$label.'. '.$validator->getDescription(); - return false; - } - } - } + if (!$this->checkForInvalidAttributeValues($structure, $keys)) { + return false; } return true; } - - /** - * Is array - * - * Function will return true if object is array. - * - * @return bool - */ - public function isArray(): bool - { - return false; - } - - /** - * Get Type - * - * Returns validator type. - * - * @return string - */ - public function getType(): string - { - return self::TYPE_ARRAY; - } } diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 4820009f7..20388a94c 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -227,6 +227,32 @@ public function isValid($document): bool $structure = $document->getArrayCopy(); $attributes = \array_merge($this->attributes, $this->collection->getAttribute('attributes', [])); + if (!$this->checkForAllRequiredValues($structure, $attributes, $keys)) { + return false; + } + + if (!$this->checkForUnknownAttributes($structure, $keys)) { + return false; + } + + if (!$this->checkForInvalidAttributeValues($structure, $keys)) { + return false; + } + + return true; + } + + /** + * Check for all required values + * + * @param array $structure + * @param array $attributes + * @param array $keys + * + * @return bool + */ + protected function checkForAllRequiredValues(array $structure, array $attributes, array &$keys): bool + { foreach ($attributes as $key => $attribute) { // Check all required attributes are set $name = $attribute['$id'] ?? ''; $required = $attribute['required'] ?? false; @@ -239,12 +265,40 @@ public function isValid($document): bool } } + return true; + } + + /** + * Check for Unknown Attributes + * + * @param array $structure + * @param array $keys + * + * @return bool + */ + protected function checkForUnknownAttributes(array $structure, array $keys): bool + { foreach ($structure as $key => $value) { if (!array_key_exists($key, $keys)) { // Check no unknown attributes are set $this->message = 'Unknown attribute: "'.$key.'"'; return false; } + } + return true; + } + + /** + * Check for invalid attribute values + * + * @param array $structure + * @param array $keys + * + * @return bool + */ + protected function checkForInvalidAttributeValues(array $structure, array $keys): bool + { + foreach ($structure as $key => $value) { $attribute = $keys[$key] ?? []; $type = $attribute['type'] ?? ''; $array = $attribute['array'] ?? false; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index f3e65799d..ece988538 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -760,10 +760,18 @@ public function testPreserveDatesUpdate(): void $doc1 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc1'); $this->assertEquals($newDate, $doc1->getAttribute('$updatedAt')); - $doc2->setAttribute('$updatedAt', $newDate); - $doc3->setAttribute('$updatedAt', $newDate); - $this->getDatabase()->updateDocument('preserve_update_dates', 'doc2', $doc2); - $this->getDatabase()->updateDocument('preserve_update_dates', 'doc3', $doc3); + $this->getDatabase()->updateDocuments( + 'preserve_update_dates', + new Document([ + '$updatedAt' => $newDate + ]), + [ + Query::equal('$id', [ + $doc2->getId(), + $doc3->getId() + ]) + ] + ); $doc2 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc2'); $doc3 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc3'); @@ -15534,7 +15542,7 @@ public function testTransformations(): void public function testUpdateDocuments(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } @@ -15543,7 +15551,7 @@ public function testUpdateDocuments(): void self::$authorization->cleanRoles(); self::$authorization->addRole(Role::any()->toString()); - $this->getDatabase()->createCollection($collection, attributes: [ + static::getDatabase()->createCollection($collection, attributes: [ new Document([ '$id' => ID::custom('string'), 'type' => Database::VAR_STRING, @@ -15574,7 +15582,7 @@ public function testUpdateDocuments(): void ], documentSecurity: false); for ($i = 0; $i < 10; $i++) { - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, 'string' => 'text📝 ' . $i, 'integer' => $i @@ -15582,7 +15590,7 @@ public function testUpdateDocuments(): void } // Test Update half of the documents - $affected = $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated', ]), [ Query::greaterThanEqual('integer', 5), @@ -15590,7 +15598,7 @@ public function testUpdateDocuments(): void $this->assertEquals($affected, 5); - $updatedDocuments = $this->getDatabase()->find($collection, [ + $updatedDocuments = static::getDatabase()->find($collection, [ Query::greaterThanEqual('integer', 5), ]); @@ -15600,7 +15608,7 @@ public function testUpdateDocuments(): void $this->assertEquals('text📝 updated', $document->getAttribute('string')); } - $controlDocuments = $this->getDatabase()->find($collection, [ + $controlDocuments = static::getDatabase()->find($collection, [ Query::lessThan('integer', 5), ]); @@ -15611,13 +15619,13 @@ public function testUpdateDocuments(): void } // Test Update all documents - $affected = $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated all', ])); $this->assertEquals(10, $affected); - $updatedDocuments = $this->getDatabase()->find($collection); + $updatedDocuments = static::getDatabase()->find($collection); $this->assertEquals(count($updatedDocuments), 10); @@ -15626,7 +15634,7 @@ public function testUpdateDocuments(): void } // Check collection level permissions - $this->getDatabase()->updateCollection($collection, permissions: [ + static::getDatabase()->updateCollection($collection, permissions: [ Permission::read(Role::user('asd')), Permission::create(Role::user('asd')), Permission::update(Role::user('asd')), @@ -15634,7 +15642,7 @@ public function testUpdateDocuments(): void ], documentSecurity: false); try { - $this->getDatabase()->updateDocuments($collection, new Document([ + static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated all', ])); $this->fail('Failed to throw exception'); @@ -15643,10 +15651,10 @@ public function testUpdateDocuments(): void } // Check document level permissions - $this->getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); + static::getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); - $this::$authorization->skip(function () use ($collection) { - $this->getDatabase()->updateDocument($collection, 'doc0', new Document([ + static::$authorization->skip(function () use ($collection) { + static::getDatabase()->updateDocument($collection, 'doc0', new Document([ 'string' => 'text📝 updated all', '$permissions' => [ Permission::read(Role::user('asd')), @@ -15657,39 +15665,51 @@ public function testUpdateDocuments(): void ])); }); - $this::$authorization->addRole(Role::user('asd')->toString()); + static::$authorization->addRole(Role::user('asd')->toString()); - $this->getDatabase()->updateDocuments($collection, new Document([ + static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'permission text', ])); - self::$authorization->skip(function () use ($collection) { - $documents = $this->getDatabase()->find($collection, [ - Query::equal('string', ['permission text']), - ]); + $documents = static::getDatabase()->find($collection, [ + Query::equal('string', ['permission text']), + ]); - $this->assertCount(1, $documents); + $this->assertCount(1, $documents); - $unmodifiedDocuments = $this->getDatabase()->find($collection, [ + self::$authorization->skip(function () use ($collection) { + $unmodifiedDocuments = static::getDatabase()->find($collection, [ Query::equal('string', ['text📝 updated all']), ]); $this->assertCount(9, $unmodifiedDocuments); }); + + // Test we can update more documents than batchSize + static::getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'batchSize Test' + ]), batchSize: 2); + + $documents = static::getDatabase()->find($collection); + + foreach ($documents as $document) { + $this->assertEquals('batchSize Test', $document->getAttribute('string')); + } + + self::$authorization->cleanRoles(); + self::$authorization->addRole(Role::any()->toString()); } public function testUpdateDocumentsPermissions(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations()) { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } $collection = 'testUpdateDocumentsPerms'; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); - $this->getDatabase()->createCollection($collection, attributes: [ + static::getDatabase()->createCollection($collection, attributes: [ new Document([ '$id' => ID::custom('string'), 'type' => Database::VAR_STRING, @@ -15699,9 +15719,9 @@ public function testUpdateDocumentsPermissions(): void ], permissions: [], documentSecurity: true); // Test we can bulk update permissions we have access to - $this::$authorization->skip(function () use ($collection) { + static::$authorization->skip(function () use ($collection) { for ($i = 0; $i < 10; $i++) { - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, 'string' => 'text📝 ' . $i, '$permissions' => [ @@ -15713,7 +15733,7 @@ public function testUpdateDocumentsPermissions(): void ])); } - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, 'string' => 'text📝 ' . $i, '$permissions' => [ @@ -15725,7 +15745,7 @@ public function testUpdateDocumentsPermissions(): void ])); }); - $affected = $this->getDatabase()->updateDocuments($collection, new Document([ + $affected = static::getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::user('user2')), Permission::create(Role::user('user2')), @@ -15734,8 +15754,8 @@ public function testUpdateDocumentsPermissions(): void ], ])); - $documents = $this::$authorization->skip(function () use ($collection) { - return $this->getDatabase()->find($collection); + $documents = static::$authorization->skip(function () use ($collection) { + return static::getDatabase()->find($collection); }); $this->assertEquals(10, $affected); @@ -15763,10 +15783,10 @@ public function testUpdateDocumentsPermissions(): void $this->assertCount(1, $unmodifiedDocuments); - $this::$authorization->addRole(Role::user('user2')->toString()); + static::$authorization->addRole(Role::user('user2')->toString()); // Test Bulk permission update with data - $this->getDatabase()->updateDocuments($collection, new Document([ + static::getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::user('user3')), Permission::create(Role::user('user3')), @@ -15776,7 +15796,7 @@ public function testUpdateDocumentsPermissions(): void 'string' => 'text📝 updated', ])); - $documents = $this::$authorization + $documents = static::$authorization ->skip(function () use ($collection) { return $this->getDatabase()->find($collection); }); @@ -15842,20 +15862,18 @@ public function testUpdateDocumentsRelationships(): void twoWay: true, ); - $this::$authorization->skip(function () { - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ - '$id' => 'doc1', - 'string' => 'text📝', - ])); + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ + '$id' => 'doc1', + 'string' => 'text📝', + ])); - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ - '$id' => 'doc2', - 'string' => 'text📝', - 'testUpdateDocumentsRelationships1' => 'doc1' - ])); - }); + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ + '$id' => 'doc1', + 'string' => 'text📝', + 'testUpdateDocumentsRelationships1' => 'doc1' + ])); - $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc2'); + $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); $this->assertNotNull($sisterDocument); $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships1', new Document([ @@ -15867,11 +15885,36 @@ public function testUpdateDocumentsRelationships(): void $this->assertNotFalse($document); $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc2'); + $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); $this->assertNotNull($sisterDocument); $relationalDocument = $sisterDocument->getAttribute('testUpdateDocumentsRelationships1'); $this->assertEquals('text📝 updated', $relationalDocument->getAttribute('string')); + + // Check relationship value updating between each other. + for ($i = 2; $i < 11; $i++) { + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝', + ])); + + $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ + '$id' => 'doc' . $i, + 'string' => 'text📝', + 'testUpdateDocumentsRelationships1' => 'doc' . $i + ])); + } + + $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ + 'testUpdateDocumentsRelationships1' => 'doc1' + ])); + + $documents = $this->getDatabase()->find('testUpdateDocumentsRelationships2'); + + foreach ($documents as $document) { + var_dump($document->getAttribute('testUpdateDocumentsRelationships1')); + // $this->assertEquals('doc1', $document->getAttribute('testUpdateDocumentsRelationships1')->getId()); + } } public function testEvents(): void From a71a7c9b54a7bad279c210821ba8e5ab00f7fccf Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 18 Oct 2024 14:09:25 +0900 Subject: [PATCH 086/103] Get relationship tests working --- src/Database/Database.php | 21 +++++++++------------ tests/e2e/Adapter/Base.php | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 58e7c6f44..b0d33f049 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3944,17 +3944,15 @@ public function updateDocuments(string $collection, Document $update, array $que // Resolve and update relationships while (true) { - $affectedDocuments = $this->skipRelationships(function () use ($collection, $queries, $batchSize, $lastDocument) { - return $this->find($collection->getId(), array_merge( - empty($lastDocument) ? [ - Query::limit($batchSize), - ] : [ - Query::limit($batchSize), - Query::cursorAfter($lastDocument), - ], - $queries, - ), forPermission: Database::PERMISSION_UPDATE); - }); + $affectedDocuments = $this->find($collection->getId(), array_merge( + empty($lastDocument) ? [ + Query::limit($batchSize), + ] : [ + Query::limit($batchSize), + Query::cursorAfter($lastDocument), + ], + $queries, + ), forPermission: Database::PERMISSION_UPDATE); if (empty($affectedDocuments)) { break; @@ -3968,7 +3966,6 @@ public function updateDocuments(string $collection, Document $update, array $que } $affectedDocumentIds[] = $document->getId(); - $totalAffectedDocuments[] = $document; } $getResults = fn () => $this->adapter->updateDocuments( diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index ece988538..01ed9e077 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15892,6 +15892,15 @@ public function testUpdateDocumentsRelationships(): void $this->assertEquals('text📝 updated', $relationalDocument->getAttribute('string')); // Check relationship value updating between each other. + $this->getDatabase()->deleteRelationship('testUpdateDocumentsRelationships1', 'testUpdateDocumentsRelationships2'); + + $this->getDatabase()->createRelationship( + collection: 'testUpdateDocumentsRelationships1', + relatedCollection: 'testUpdateDocumentsRelationships2', + type: Database::RELATION_ONE_TO_MANY, + twoWay: true, + ); + for ($i = 2; $i < 11; $i++) { $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ '$id' => 'doc' . $i, @@ -15905,6 +15914,10 @@ public function testUpdateDocumentsRelationships(): void ])); } + $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ + 'testUpdateDocumentsRelationships1' => null + ])); + $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ 'testUpdateDocumentsRelationships1' => 'doc1' ])); @@ -15912,8 +15925,7 @@ public function testUpdateDocumentsRelationships(): void $documents = $this->getDatabase()->find('testUpdateDocumentsRelationships2'); foreach ($documents as $document) { - var_dump($document->getAttribute('testUpdateDocumentsRelationships1')); - // $this->assertEquals('doc1', $document->getAttribute('testUpdateDocumentsRelationships1')->getId()); + $this->assertEquals('doc1', $document->getAttribute('testUpdateDocumentsRelationships1')->getId()); } } From d34b44df06420a5594b246534c5ceb8b526a710e Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 18 Oct 2024 14:39:24 +0900 Subject: [PATCH 087/103] Address comments --- src/Database/Adapter.php | 3 ++- src/Database/Adapter/MariaDB.php | 13 +++++++------ src/Database/Adapter/Mongo.php | 7 ++++--- src/Database/Adapter/Postgres.php | 9 +++++---- src/Database/Adapter/SQL.php | 4 ++-- src/Database/Adapter/SQLite.php | 4 ++-- src/Database/Database.php | 31 +++++++++++++++---------------- tests/e2e/Adapter/Base.php | 15 ++++++++------- 8 files changed, 45 insertions(+), 41 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 349193da1..4e614ee27 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -640,10 +640,11 @@ abstract public function deleteDocuments(string $collection, array $ids): bool; * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array */ - abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array; + abstract public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array; /** * Sum an attribute diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 4788c67fc..fb7c5afe3 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1654,11 +1654,11 @@ public function deleteDocuments(string $collection, array $ids): bool $where[] = "_tenant = :_tenant"; } - $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ")"; $sql = "DELETE FROM {$this->getSQLTable($name)} WHERE " . \implode(' AND ', $where); - $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + $sql = $this->trigger(Database::EVENT_DOCUMENTS_DELETE, $sql); $stmt = $this->getPDO()->prepare($sql); @@ -1672,7 +1672,7 @@ public function deleteDocuments(string $collection, array $ids): bool $sql = " DELETE FROM {$this->getSQLTable($name . '_perms')} - WHERE _document IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ") + WHERE _document IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ") "; if ($this->sharedTables) { @@ -1705,7 +1705,7 @@ public function deleteDocuments(string $collection, array $ids): bool return true; } - /** + /** * Find Documents * * @param string $collection @@ -1716,11 +1716,12 @@ public function deleteDocuments(string $collection, array $ids): bool * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * @return array * @throws DatabaseException * @throws TimeoutException */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); $roles = $this->authorization->getRoles(); @@ -1810,7 +1811,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles); + $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } if ($this->sharedTables) { diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 7841c51b0..924315275 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -966,7 +966,7 @@ public function updateAttribute(string $collection, string $id, string $type, in return true; } - /** + /** * Find Documents * * Find data sets using chosen queries @@ -979,12 +979,13 @@ public function updateAttribute(string $collection, string $id, string $type, in * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array * @throws Exception * @throws Timeout */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->getNamespace() . '_' . $this->filter($collection); $queries = array_map(fn ($query) => clone $query, $queries); @@ -998,7 +999,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, // permissions if ($this->authorization->getStatus()) { // skip if authorization is disabled $roles = \implode('|', $this->authorization->getRoles()); - $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; + $filters['_permissions']['$in'] = [new Regex("{$forPermission}\(\".*(?:{$roles}).*\"\)", 'i')]; } $options = []; diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 437c44914..0bfffd3d5 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1579,11 +1579,11 @@ public function deleteDocuments(string $collection, array $ids): bool $where[] = "_tenant = :_tenant"; } - $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($id) => ":_id_{$id}", \array_keys($ids))) . ")"; + $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ")"; $sql = "DELETE FROM {$this->getSQLTable($name)} WHERE " . \implode(' AND ', $where); - $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); + $sql = $this->trigger(Database::EVENT_DOCUMENTS_DELETE, $sql); $stmt = $this->getPDO()->prepare($sql); @@ -1643,13 +1643,14 @@ public function deleteDocuments(string $collection, array $ids): bool * @param array $orderTypes * @param array $cursor * @param string $cursorDirection + * @param string $forPermission * * @return array * @throws Exception * @throws PDOException * @throws Timeout */ - public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER): array + public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); $roles = $this->authorization->getRoles(); @@ -1737,7 +1738,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles); + $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index e73515a57..58fdbc52b 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -968,7 +968,7 @@ protected function getSQLIndexType(string $type): string * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = Database::PERMISSION_READ): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); @@ -981,7 +981,7 @@ protected function getSQLPermissionsCondition(string $collection, array $roles): SELECT _document FROM {$this->getSQLTable($collection . '_perms')} WHERE _permission IN (" . implode(', ', $roles) . ") - AND _type = 'read' + AND _type = '{$type}' {$tenantQuery} )"; } diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 193f9b19c..74984a260 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -1175,14 +1175,14 @@ protected function getSQLIndex(string $collection, string $id, string $type, arr * @return string * @throws Exception */ - protected function getSQLPermissionsCondition(string $collection, array $roles): string + protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = Database::PERMISSION_READ): string { $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); return "table_main._uid IN ( SELECT distinct(_document) FROM `{$this->getNamespace()}_{$collection}_perms` WHERE _permission IN (" . implode(', ', $roles) . ") - AND _type = 'read' + AND _type = '{$type}' )"; } diff --git a/src/Database/Database.php b/src/Database/Database.php index 22d056d63..2c5c6f7db 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -137,6 +137,7 @@ class Database public const EVENT_INDEX_DELETE = 'index_delete'; public const INSERT_BATCH_SIZE = 100; + public const DELETE_BATCH_SIZE = 100; protected Adapter $adapter; @@ -4986,7 +4987,7 @@ private function deleteCascade(Document $collection, Document $relatedCollection * @throws DatabaseException * @throws RestrictedException */ - public function deleteDocuments(string $collection, array $queries = [], int $batchSize = 100): bool + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): bool { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -4998,6 +4999,13 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; + + $documentSecurity = $collection->getAttribute('documentSecurity', false); + $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, $collection->getDelete())); + + if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { + throw new AuthorizationException($this->authorization->getDescription()); + } while (true) { $affectedDocuments = $this->find($collection->getId(), array_merge( @@ -5008,7 +5016,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba Query::cursorAfter($lastDocument), ], $queries, - )); + ), forPermission: Database::PERMISSION_DELETE); if (empty($affectedDocuments)) { break; @@ -5017,17 +5025,6 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); foreach ($affectedDocuments as $document) { - if ($collection->getId() !== self::METADATA) { - $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ - ...$collection->getDelete(), - ...($documentSecurity ? $document->getDelete() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); - } - } - // Delete Relationships if ($this->resolveRelationships) { $document = $this->silent(fn () => $this->deleteDocumentRelationships($collection, $document)); @@ -5097,13 +5094,14 @@ public function purgeCachedDocument(string $collectionId, string $id): bool * * @param string $collection * @param array $queries + * @param string $forPermission * * @return array * @throws DatabaseException * @throws QueryException * @throws TimeoutException */ - public function find(string $collection, array $queries = []): array + public function find(string $collection, array $queries = [], string $forPermission = Database::PERMISSION_READ): array { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -5127,7 +5125,7 @@ public function find(string $collection, array $queries = []): array $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + $skipAuth = $this->authorization->isValid(new Input($forPermission, $collection->getPermissionsByType($forPermission))); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { throw new AuthorizationException($this->authorization->getDescription()); @@ -5214,7 +5212,8 @@ public function find(string $collection, array $queries = []): array $orderAttributes, $orderTypes, $cursor, - $cursorDirection ?? Database::CURSOR_AFTER + $cursorDirection ?? Database::CURSOR_AFTER, + $forPermission ); $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 82694ec7a..68d024a64 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15617,18 +15617,19 @@ public function testDeleteBulkDocuments(): void static::getDatabase()->deleteDocuments('bulk_delete'); $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); - // TEST (FAIL): Bulk delete all documents with invalid document permissions - // Authorization::setRole(Role::any()->toString()); + // TEST: Make sure we can't delete documents we don't have permissions for static::getDatabase()->updateCollection('bulk_delete', [ Permission::create(Role::any()), ], true); $this->propegateBulkDocuments(true); - try { - static::getDatabase()->deleteDocuments('bulk_delete'); - $this->fail('Bulk deleted documents with invalid document permission'); - } catch (\Utopia\Database\Exception\Authorization) { - } + static::getDatabase()->deleteDocuments('bulk_delete'); + + $documents = static::$authorization->skip(function () { + return static::getDatabase()->find('bulk_delete'); + }); + + $this->assertCount(10, $documents); static::getDatabase()->updateCollection('bulk_delete', [ Permission::create(Role::any()), From afd0d9c5e6a0fa8e2715161f98ac7e5b13f72a75 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 18 Oct 2024 14:42:16 +0900 Subject: [PATCH 088/103] Run Linter --- src/Database/Adapter/MariaDB.php | 2 +- src/Database/Adapter/Mongo.php | 2 +- src/Database/Database.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index fb7c5afe3..d7067e600 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1705,7 +1705,7 @@ public function deleteDocuments(string $collection, array $ids): bool return true; } - /** + /** * Find Documents * * @param string $collection diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 924315275..e2882241c 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -966,7 +966,7 @@ public function updateAttribute(string $collection, string $id, string $type, in return true; } - /** + /** * Find Documents * * Find data sets using chosen queries diff --git a/src/Database/Database.php b/src/Database/Database.php index 2c5c6f7db..119d75c75 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4999,7 +4999,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { $lastDocument = null; - + $documentSecurity = $collection->getAttribute('documentSecurity', false); $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, $collection->getDelete())); From 6e2b974639e32115eed3760f853cb2dcb92d0065 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 18 Oct 2024 16:19:14 +0900 Subject: [PATCH 089/103] Address comments, work on fixes for permissions --- src/Database/Adapter.php | 6 ++++-- src/Database/Adapter/MariaDB.php | 14 +++++++++++++- src/Database/Adapter/Mongo.php | 4 +++- src/Database/Adapter/Postgres.php | 4 +++- src/Database/Adapter/SQL.php | 4 ++++ src/Database/Database.php | 29 ++++++++++++++--------------- tests/e2e/Adapter/Base.php | 19 +++++++++++++++++-- 7 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 65b3c7f89..9b4dd9aea 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -593,9 +593,11 @@ abstract public function createDocuments(string $collection, array $documents, i * @return Document */ abstract public function updateDocument(string $collection, Document $document): Document; - + /** - * Batch update documents + * Update documents + * + * Updates all documents which match the given query. * * @param string $collection * @param Document $updates diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 44b009328..88129ab95 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1303,7 +1303,9 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Batch update documents + * Update documents + * + * Updates all documents which match the given query. * * @param string $collection * @param Document $updates @@ -1522,9 +1524,19 @@ public function updateDocuments(string $collection, Document $updates, array $do WHERE ({$removeQuery}) "); + $asd = " + DELETE + FROM {$this->getSQLTable($name . '_perms')} + WHERE ({$removeQuery}) + "; + foreach ($removeBindValues as $key => $value) { + $asd = str_replace(":{$key}", "'{$value}'", $asd); $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); } + + var_dump($asd); + if ($this->sharedTables) { $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 1585c295c..c0f21c1da 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -820,7 +820,9 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Batch update documents + * Update documents + * + * Updates all documents which match the given query. * * @param string $collection * @param Document $updates diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 8143bb5b3..361abaa5c 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1226,7 +1226,9 @@ public function updateDocument(string $collection, Document $document): Document } /** - * Batch update documents + * Update documents + * + * Updates all documents which match the given query. * * @param string $collection * @param Document $updates diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index 98efafa79..b06492f3f 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -980,6 +980,10 @@ protected function getSQLIndexType(string $type): string */ protected function getSQLPermissionsCondition(string $collection, array $roles, string $type = Database::PERMISSION_READ): string { + if (!in_array($type, Database::PERMISSIONS)) { + throw new DatabaseException('Unknown permission type: ' . $type); + } + $roles = array_map(fn (string $role) => $this->getPDO()->quote($role), $roles); $tenantQuery = ''; diff --git a/src/Database/Database.php b/src/Database/Database.php index b0d33f049..fb6a74bf0 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3890,46 +3890,45 @@ public function updateDocument(string $collection, string $id, Document $documen * Updates all documents which match the given query. * * @param string $collection - * @param Document $update + * @param Document $updates * @param array $queries * @param int $batchSize * * @return int * - * @throws AuthorizationException + * @throws AuthorizationExceptions * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $update, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int + public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - if ($update->isEmpty()) { + if ($updates->isEmpty()) { return 0; } $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); - unset($update['$id']); - unset($update['$createdAt']); - unset($update['$tenant']); + unset($updates['$id']); + unset($updates['$createdAt']); + unset($updates['$tenant']); if (!$this->preserveDates) { - unset($update['$updatedAt']); - $update['$updatedAt'] = DateTime::now(); + $updates['$updatedAt'] = DateTime::now(); } - $update = $this->encode($collection, $update); + $updates = $this->encode($collection, $updates); // Check new document structure $validator = new PartialStructure($collection); - if (!$validator->isValid($update)) { + if (!$validator->isValid($updates)) { throw new StructureException($validator->getDescription()); } - $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $update) { + $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $updates) { $lastDocument = null; $totalModified = 0; $affectedDocumentIds = []; @@ -3960,7 +3959,7 @@ public function updateDocuments(string $collection, Document $update, array $que foreach ($affectedDocuments as $document) { if ($this->resolveRelationships) { - $newDocument = array_merge($document->getArrayCopy(), $update->getArrayCopy()); + $newDocument = array_merge($document->getArrayCopy(), $updates->getArrayCopy()); $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, new Document($newDocument))); } @@ -3970,7 +3969,7 @@ public function updateDocuments(string $collection, Document $update, array $que $getResults = fn () => $this->adapter->updateDocuments( $collection->getId(), - $update, + $updates, $affectedDocuments ); @@ -3992,7 +3991,7 @@ public function updateDocuments(string $collection, Document $update, array $que $this->purgeCachedDocument($collection->getId(), $id); } - return $result ?? 0; + return $totalModified ?? 0; }); return $affected; diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 01ed9e077..8391487f9 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15685,13 +15685,26 @@ public function testUpdateDocuments(): void $this->assertCount(9, $unmodifiedDocuments); }); + static::$authorization->skip(function () use ($collection) { + static::getDatabase()->updateDocuments($collection, new Document([ + '$permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + ])); + }); + // Test we can update more documents than batchSize - static::getDatabase()->updateDocuments($collection, new Document([ + $affected = static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'batchSize Test' ]), batchSize: 2); $documents = static::getDatabase()->find($collection); + $this->assertEquals(10, $affected); + foreach ($documents as $document) { $this->assertEquals('batchSize Test', $document->getAttribute('string')); } @@ -15786,7 +15799,7 @@ public function testUpdateDocumentsPermissions(): void static::$authorization->addRole(Role::user('user2')->toString()); // Test Bulk permission update with data - static::getDatabase()->updateDocuments($collection, new Document([ + $affected = static::getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::user('user3')), Permission::create(Role::user('user3')), @@ -15796,6 +15809,8 @@ public function testUpdateDocumentsPermissions(): void 'string' => 'text📝 updated', ])); + $this->assertEquals(10, $affected); + $documents = static::$authorization ->skip(function () use ($collection) { return $this->getDatabase()->find($collection); From 9e603ec12d3d2b144bce77f726ade184f0db8c12 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Fri, 18 Oct 2024 20:34:35 +1300 Subject: [PATCH 090/103] Fix permissions removal query --- src/Database/Adapter/MariaDB.php | 4 ---- src/Database/Validator/PartialStructure.php | 2 -- 2 files changed, 6 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 88129ab95..259cd8e9b 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1473,10 +1473,6 @@ public function updateDocuments(string $collection, Document $updates, array $do $removeQuery .= ' OR '; } } - - if ($index !== \array_key_last($documents)) { - $removeQuery .= ' OR '; - } } // Get added Permissions diff --git a/src/Database/Validator/PartialStructure.php b/src/Database/Validator/PartialStructure.php index 69d4703ca..1f52a451c 100644 --- a/src/Database/Validator/PartialStructure.php +++ b/src/Database/Validator/PartialStructure.php @@ -30,8 +30,6 @@ public function isValid($document): bool $keys = []; $structure = $document->getArrayCopy(); - $attributes = $this->collection->getAttribute('attributes', []); - $attributes = \array_merge($this->attributes, $this->collection->getAttribute('attributes', [])); foreach ($attributes as $attribute) { From 935c9377b83c996870e654d5179848828b6365ee Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Fri, 18 Oct 2024 20:40:00 +1300 Subject: [PATCH 091/103] Remove debug --- src/Database/Adapter/MariaDB.php | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 40f0a687a..789e6323f 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1522,19 +1522,10 @@ public function updateDocuments(string $collection, Document $updates, array $do WHERE ({$removeQuery}) "); - $asd = " - DELETE - FROM {$this->getSQLTable($name . '_perms')} - WHERE ({$removeQuery}) - "; - foreach ($removeBindValues as $key => $value) { - $asd = str_replace(":{$key}", "'{$value}'", $asd); $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); } - var_dump($asd); - if ($this->sharedTables) { $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); } From 36758c8a9bf459ccc528b819ae2933d574fa7549 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Fri, 18 Oct 2024 21:20:17 +1300 Subject: [PATCH 092/103] Revert "Fix permissions removal query" This reverts commit 9e603ec12d3d2b144bce77f726ade184f0db8c12. --- composer.json | 2 +- src/Database/Adapter/MariaDB.php | 4 ++++ src/Database/Database.php | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index f8f5bf8e9..de12d86f6 100755 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ ], "lint": "./vendor/bin/pint --test", "format": "./vendor/bin/pint", - "check": "./vendor/bin/phpstan analyse --level 7 src tests --memory-limit 512M", + "check": "./vendor/bin/phpstan analyse --level 7 src tests --memory-limit 2G", "coverage": "./vendor/bin/coverage-check ./tmp/clover.xml 90" }, "require": { diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 789e6323f..b21a7c3e0 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1475,6 +1475,10 @@ public function updateDocuments(string $collection, Document $updates, array $do $removeQuery .= ' OR '; } } + + if ($index !== \array_key_last($documents)) { + $removeQuery .= ' OR '; + } } // Get added Permissions diff --git a/src/Database/Database.php b/src/Database/Database.php index 74e939bf8..5b8093206 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -3897,7 +3897,7 @@ public function updateDocument(string $collection, string $id, Document $documen * * @return int * - * @throws AuthorizationExceptions + * @throws AuthorizationException * @throws DatabaseException */ public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int @@ -3992,7 +3992,7 @@ public function updateDocuments(string $collection, Document $updates, array $qu $this->purgeCachedDocument($collection->getId(), $id); } - return $totalModified ?? 0; + return $totalModified; }); return $affected; From a65da29e4f051288c0a6af52cd87485cf7c6f749 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 28 Oct 2024 11:58:21 +0900 Subject: [PATCH 093/103] Fix mongoDB attempting to delete an empty array of documents --- src/Database/Adapter/Mongo.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index e2882241c..374e6fcbd 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -920,6 +920,10 @@ public function deleteDocuments(string $collection, array $ids): bool { $name = $this->getNamespace() . '_' . $this->filter($collection); + if (empty($ids)) { + return true; + } + $filters = $this->buildFilters([new Query(Query::TYPE_EQUAL, '_uid', $ids)]); if ($this->sharedTables) { From b3cab3bac046c2b24c6254d517570fe4fa899f84 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Mon, 28 Oct 2024 13:55:08 +0900 Subject: [PATCH 094/103] Move empty affected document check to database.php --- src/Database/Adapter/MariaDB.php | 4 ---- src/Database/Adapter/Mongo.php | 4 ---- src/Database/Adapter/Postgres.php | 4 ---- src/Database/Database.php | 4 ++++ 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index d7067e600..3103d3b90 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1642,10 +1642,6 @@ public function deleteDocument(string $collection, string $id): bool */ public function deleteDocuments(string $collection, array $ids): bool { - if (empty($ids)) { - return true; - } - try { $name = $this->filter($collection); $where = []; diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 374e6fcbd..e2882241c 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -920,10 +920,6 @@ public function deleteDocuments(string $collection, array $ids): bool { $name = $this->getNamespace() . '_' . $this->filter($collection); - if (empty($ids)) { - return true; - } - $filters = $this->buildFilters([new Query(Query::TYPE_EQUAL, '_uid', $ids)]); if ($this->sharedTables) { diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 0bfffd3d5..068e80b8b 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1567,10 +1567,6 @@ public function deleteDocument(string $collection, string $id): bool */ public function deleteDocuments(string $collection, array $ids): bool { - if (empty($ids)) { - return true; - } - try { $name = $this->filter($collection); $where = []; diff --git a/src/Database/Database.php b/src/Database/Database.php index 119d75c75..4f87d8403 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -5041,6 +5041,10 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba } } + if (empty($affectedDocumentIds)) { + return false; + } + $this->trigger(self::EVENT_DOCUMENTS_DELETE, $affectedDocumentIds); // Mass delete using adapter with query From adacd1457e8297d9cf501ff3d9ced6d6ee57774d Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 1 Nov 2024 16:00:10 +0900 Subject: [PATCH 095/103] Fix removing permissions SQL --- src/Database/Adapter/MariaDB.php | 26 ++++++++++---------------- src/Database/Adapter/Postgres.php | 16 +++++----------- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index b21a7c3e0..f3359b5f8 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1395,7 +1395,7 @@ public function updateDocuments(string $collection, Document $updates, array $do // Permissions logic if (!empty($updates->getPermissions())) { - $removeQuery = ''; + $removeQueries = []; $removeBindValues = []; $addQuery = ''; @@ -1457,11 +1457,11 @@ public function updateDocuments(string $collection, Document $updates, array $do $tenantQuery = ' AND _tenant = :_tenant'; } - $removeQuery .= "( - _document = :uid_{$index} - {$tenantQuery} - AND _type = '{$type}' - AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { + $removeQueries[] = "( + _document = :uid_{$index} + {$tenantQuery} + AND _type = '{$type}' + AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; $removeBindKeys[] = ':' . $bindKey; $removeBindValues[$bindKey] = $permissionsToRemove[$i]; @@ -1469,15 +1469,7 @@ public function updateDocuments(string $collection, Document $updates, array $do return ':' . $bindKey; }, \array_keys($permissionsToRemove))) . ") - )"; - - if ($type !== \array_key_last($removals)) { - $removeQuery .= ' OR '; - } - } - - if ($index !== \array_key_last($documents)) { - $removeQuery .= ' OR '; + )"; } } @@ -1519,7 +1511,9 @@ public function updateDocuments(string $collection, Document $updates, array $do } } - if (!empty($removeQuery)) { + if (!empty($removeQueries)) { + $removeQuery = \implode(' OR ', $removeQueries); + $stmtRemovePermissions = $this->getPDO()->prepare(" DELETE FROM {$this->getSQLTable($name . '_perms')} diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 0b6413553..a2154bbfd 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1318,7 +1318,7 @@ public function updateDocuments(string $collection, Document $updates, array $do // Permissions logic if (!empty($updates->getPermissions())) { - $removeQuery = ''; + $removeQueries = []; $removeBindValues = []; $addQuery = ''; @@ -1380,7 +1380,7 @@ public function updateDocuments(string $collection, Document $updates, array $do $tenantQuery = ' AND _tenant = :_tenant'; } - $removeQuery .= "( + $removeQueries[] = "( _document = :uid_{$index} {$tenantQuery} AND _type = '{$type}' @@ -1393,14 +1393,6 @@ public function updateDocuments(string $collection, Document $updates, array $do }, \array_keys($permissionsToRemove))) . ") )"; - - if ($type !== \array_key_last($removals)) { - $removeQuery .= ' OR '; - } - } - - if ($index !== \array_key_last($documents)) { - $removeQuery .= ' OR '; } } @@ -1442,7 +1434,9 @@ public function updateDocuments(string $collection, Document $updates, array $do } } - if (!empty($removeQuery)) { + if (!empty($removeQueries)) { + $removeQuery = \implode(' OR ', $removeQueries); + $stmtRemovePermissions = $this->getPDO()->prepare(" DELETE FROM {$this->getSQLTable($name . '_perms')} From a1a5f536d5acc8309c0893188487b41d96864157 Mon Sep 17 00:00:00 2001 From: Bradley Schofield Date: Fri, 1 Nov 2024 16:20:39 +0900 Subject: [PATCH 096/103] Address comments --- src/Database/Adapter.php | 4 ++-- src/Database/Adapter/MariaDB.php | 6 +++--- src/Database/Adapter/Mongo.php | 8 ++++---- src/Database/Adapter/Postgres.php | 6 +++--- src/Database/Database.php | 6 +++--- tests/e2e/Adapter/Base.php | 13 +++++++++---- 6 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index 4e614ee27..8807570ff 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -623,9 +623,9 @@ abstract public function deleteDocument(string $collection, string $id): bool; * @param string $collection * @param array $ids * - * @return bool + * @return int */ - abstract public function deleteDocuments(string $collection, array $ids): bool; + abstract public function deleteDocuments(string $collection, array $ids): int; /** * Find Documents diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 3103d3b90..7616f8b8c 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -1638,9 +1638,9 @@ public function deleteDocument(string $collection, string $id): bool * @param string $collection * @param array $ids * - * @return bool + * @return int */ - public function deleteDocuments(string $collection, array $ids): bool + public function deleteDocuments(string $collection, array $ids): int { try { $name = $this->filter($collection); @@ -1698,7 +1698,7 @@ public function deleteDocuments(string $collection, array $ids): bool throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return true; + return $stmt->rowCount(); } /** diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index e2882241c..c88f6d2f6 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -914,9 +914,9 @@ public function deleteDocument(string $collection, string $id): bool * @param string $collection * @param array $ids * - * @return bool + * @return int */ - public function deleteDocuments(string $collection, array $ids): bool + public function deleteDocuments(string $collection, array $ids): int { $name = $this->getNamespace() . '_' . $this->filter($collection); @@ -932,7 +932,7 @@ public function deleteDocuments(string $collection, array $ids): bool $options = []; try { - $res = $this->client->delete( + $count = $this->client->delete( collection: $name, filters: $filters, options: $options, @@ -942,7 +942,7 @@ public function deleteDocuments(string $collection, array $ids): bool $this->processException($e); } - return true; + return $count ?? 0; } /** diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 068e80b8b..7b0e33868 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -1563,9 +1563,9 @@ public function deleteDocument(string $collection, string $id): bool * @param string $collection * @param array $ids * - * @return bool + * @return int */ - public function deleteDocuments(string $collection, array $ids): bool + public function deleteDocuments(string $collection, array $ids): int { try { $name = $this->filter($collection); @@ -1623,7 +1623,7 @@ public function deleteDocuments(string $collection, array $ids): bool throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - return true; + return $stmt->rowCount(); } /** diff --git a/src/Database/Database.php b/src/Database/Database.php index 4f87d8403..508c56b3f 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4981,13 +4981,13 @@ private function deleteCascade(Document $collection, Document $relatedCollection * @param array $queries * @param int $batchSize * - * @return bool + * @return int * * @throws AuthorizationException * @throws DatabaseException * @throws RestrictedException */ - public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): bool + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -5042,7 +5042,7 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba } if (empty($affectedDocumentIds)) { - return false; + return 0; } $this->trigger(self::EVENT_DOCUMENTS_DELETE, $affectedDocumentIds); diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 68d024a64..94f610dab 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -15586,7 +15586,8 @@ public function testDeleteBulkDocuments(): void $this->assertCount(10, $docs); // TEST: Bulk Delete All Documents - static::getDatabase()->deleteDocuments('bulk_delete'); + $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); + $this->assertEquals(10, $deleted); $docs = static::getDatabase()->find('bulk_delete'); $this->assertCount(0, $docs); @@ -15594,9 +15595,10 @@ public function testDeleteBulkDocuments(): void // TEST: Bulk delete documents with queries. $this->propegateBulkDocuments(); - static::getDatabase()->deleteDocuments('bulk_delete', [ + $deleted = static::getDatabase()->deleteDocuments('bulk_delete', [ Query::greaterThanEqual('integer', 5) ]); + $this->assertEquals(5, $deleted); $docs = static::getDatabase()->find('bulk_delete'); $this->assertCount(5, $docs); @@ -15614,7 +15616,9 @@ public function testDeleteBulkDocuments(): void Permission::read(Role::any()), Permission::delete(Role::any()) ], false); - static::getDatabase()->deleteDocuments('bulk_delete'); + $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); + + $this->assertEquals(5, $deleted); $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); // TEST: Make sure we can't delete documents we don't have permissions for @@ -15623,7 +15627,8 @@ public function testDeleteBulkDocuments(): void ], true); $this->propegateBulkDocuments(true); - static::getDatabase()->deleteDocuments('bulk_delete'); + $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); + $this->assertEquals(0, $deleted); $documents = static::$authorization->skip(function () { return static::getDatabase()->find('bulk_delete'); From af2d2f46727fd426fea2b3cdd1effde62138c4aa Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:05:42 +1300 Subject: [PATCH 097/103] Revert "Merge pull request #376 from utopia-php/feat-framework-v2" --- README.md | 2 +- bin/tasks/index.php | 2 +- bin/tasks/load.php | 19 +- bin/tasks/query.php | 24 +- composer.json | 4 +- composer.lock | 2174 ++++++++-- src/Database/Adapter.php | 32 +- src/Database/Adapter/MariaDB.php | 31 +- src/Database/Adapter/Mongo.php | 19 +- src/Database/Adapter/Postgres.php | 25 +- src/Database/Adapter/SQL.php | 6 +- src/Database/Adapter/SQLite.php | 8 +- src/Database/Database.php | 140 +- src/Database/Exception.php | 2 +- src/Database/Query.php | 4 +- src/Database/Validator/Authorization.php | 147 +- .../Validator/Authorization/Input.php | 49 - src/Database/Validator/Datetime.php | 20 +- src/Database/Validator/Index.php | 16 +- src/Database/Validator/Key.php | 2 +- src/Database/Validator/Queries.php | 6 +- src/Database/Validator/Query/Base.php | 2 +- src/Database/Validator/Query/Filter.php | 26 +- src/Database/Validator/Query/Limit.php | 4 +- src/Database/Validator/Query/Offset.php | 4 +- src/Database/Validator/Roles.php | 2 +- src/Database/Validator/Structure.php | 16 +- tests/e2e/Adapter/Base.php | 3578 +++++++++-------- tests/e2e/Adapter/MariaDBTest.php | 8 +- tests/e2e/Adapter/MongoDBTest.php | 16 +- tests/e2e/Adapter/MySQLTest.php | 8 +- tests/e2e/Adapter/PostgresTest.php | 8 +- tests/e2e/Adapter/SQLiteTest.php | 8 +- .../e2e/Adapter/SharedTables/MariaDBTest.php | 3 +- .../e2e/Adapter/SharedTables/MongoDBTest.php | 3 +- tests/e2e/Adapter/SharedTables/MySQLTest.php | 3 +- .../e2e/Adapter/SharedTables/PostgresTest.php | 3 +- tests/e2e/Adapter/SharedTables/SQLiteTest.php | 3 +- tests/unit/Format.php | 5 +- tests/unit/Validator/AuthorizationTest.php | 94 +- tests/unit/Validator/DateTimeTest.php | 2 +- 41 files changed, 4047 insertions(+), 2481 deletions(-) delete mode 100644 src/Database/Validator/Authorization/Input.php diff --git a/README.md b/README.md index cccfa1afa..1adf58143 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ A list of the utopia/php concepts and their relevant equivalent using the differ - **Document** - A simple JSON object that will be stored in one of the utopia/database collections. For SQL-based adapters, this will be equivalent to a row. For a No-SQL adapter, this will equivalent to a native document. - **Attribute** - A simple document attribute. For SQL-based adapters, this will be equivalent to a column. For a No-SQL adapter, this will equivalent to a native document field. - **Index** - A simple collection index used to improve the performance of your database queries. -- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `$authorization->addRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. +- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `Authorization::setRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. ### Filters diff --git a/bin/tasks/index.php b/bin/tasks/index.php index c1505cc26..5b43b5920 100644 --- a/bin/tasks/index.php +++ b/bin/tasks/index.php @@ -13,8 +13,8 @@ use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; -use Utopia\Http\Validator\Text; use Utopia\Mongo\Client; +use Utopia\Validator\Text; /** * @Example diff --git a/bin/tasks/load.php b/bin/tasks/load.php index e48a4cc55..31deb39dc 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -21,11 +21,9 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Text; use Utopia\Mongo\Client; - -$authorization = new Authorization(); +use Utopia\Validator\Numeric; +use Utopia\Validator\Text; /** * @Example @@ -63,7 +61,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // reclaim resources $database = null; @@ -123,7 +121,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // reclaim resources $database = null; @@ -185,7 +183,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // Fill DB $faker = Factory::create(); @@ -228,13 +226,14 @@ }); -$createSchema = function (Database $database) use ($authorization): void { +function createSchema(Database $database): void +{ if ($database->exists($database->getDatabase())) { $database->delete($database->getDatabase()); } $database->create(); - $authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); $database->createCollection('articles', permissions: [ Permission::create(Role::any()), @@ -248,7 +247,7 @@ $database->createAttribute('articles', 'views', Database::VAR_INTEGER, 0, true); $database->createAttribute('articles', 'tags', Database::VAR_STRING, 0, true, array: true); $database->createIndex('articles', 'text', Database::INDEX_FULLTEXT, ['text']); -}; +} function createDocument($database, Generator $faker): void { diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 28dc0c431..ed84fd00c 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -14,9 +14,10 @@ use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Text; +use Utopia\Database\Validator\Authorization; use Utopia\Mongo\Client; +use Utopia\Validator\Numeric; +use Utopia\Validator\Text; /** * @Example @@ -83,35 +84,35 @@ $report = []; - $count = $setRoles($faker, 1); + $count = setRoles($faker, 1); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 100); + $count = setRoles($faker, 100); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 400); + $count = setRoles($faker, 400); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 500); + $count = setRoles($faker, 500); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 1000); + $count = setRoles($faker, 1000); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, @@ -135,12 +136,13 @@ Console::error($error->getMessage()); }); -$setRoles = function ($faker, $count) use ($authorization): int { +function setRoles($faker, $count): int +{ for ($i = 0; $i < $count; $i++) { - $authorization->addRole($faker->numerify('user####')); + Authorization::setRole($faker->numerify('user####')); } - return \count($authorization->getRoles()); -}; + return \count(Authorization::getRoles()); +} function runQueries(Database $database, int $limit): array { diff --git a/composer.json b/composer.json index de12d86f6..a99e03468 100755 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ "ext-pdo": "*", "ext-mbstring": "*", "php": ">=8.0", - "utopia-php/framework": "1.0.*", + "utopia-php/framework": "0.33.*", "utopia-php/cache": "0.10.*", "utopia-php/mongo": "0.3.*" }, @@ -45,7 +45,7 @@ "phpunit/phpunit": "9.6.*", "pcov/clobber": "2.0.*", "swoole/ide-helper": "5.1.3", - "utopia-php/cli": "0.19.*", + "utopia-php/cli": "0.14.*", "laravel/pint": "1.17.*", "phpstan/phpstan": "1.11.*", "rregeer/phpunit-coverage-check": "0.3.*" diff --git a/composer.lock b/composer.lock index 2ad152cc9..2021f0b9e 100644 --- a/composer.lock +++ b/composer.lock @@ -4,32 +4,217 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "62684826df21956b2d48dc2c42cc3e07", + "content-hash": "8a6537ec5c4f47cd0b6c34e9ceda042b", "packages": [ + { + "name": "brick/math", + "version": "0.12.1", + "source": { + "type": "git", + "url": "https://github.com/brick/math.git", + "reference": "f510c0a40911935b77b86859eb5223d58d660df1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brick/math/zipball/f510c0a40911935b77b86859eb5223d58d660df1", + "reference": "f510c0a40911935b77b86859eb5223d58d660df1", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^10.1", + "vimeo/psalm": "5.16.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Arbitrary-precision arithmetic library", + "keywords": [ + "Arbitrary-precision", + "BigInteger", + "BigRational", + "arithmetic", + "bigdecimal", + "bignum", + "bignumber", + "brick", + "decimal", + "integer", + "math", + "mathematics", + "rational" + ], + "support": { + "issues": "https://github.com/brick/math/issues", + "source": "https://github.com/brick/math/tree/0.12.1" + }, + "funding": [ + { + "url": "https://github.com/BenMorel", + "type": "github" + } + ], + "time": "2023-11-29T23:19:16+00:00" + }, + { + "name": "composer/semver", + "version": "3.4.3", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", + "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.3" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-09-19T14:15:21+00:00" + }, + { + "name": "google/protobuf", + "version": "v4.29.3", + "source": { + "type": "git", + "url": "https://github.com/protocolbuffers/protobuf-php.git", + "reference": "ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7", + "reference": "ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7", + "shasum": "" + }, + "require": { + "php": ">=7.0.0" + }, + "require-dev": { + "phpunit/phpunit": ">=5.0.0" + }, + "suggest": { + "ext-bcmath": "Need to support JSON deserialization" + }, + "type": "library", + "autoload": { + "psr-4": { + "Google\\Protobuf\\": "src/Google/Protobuf", + "GPBMetadata\\Google\\Protobuf\\": "src/GPBMetadata/Google/Protobuf" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "proto library for PHP", + "homepage": "https://developers.google.com/protocol-buffers/", + "keywords": [ + "proto" + ], + "support": { + "source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.29.3" + }, + "time": "2025-01-08T21:00:13+00:00" + }, { "name": "jean85/pretty-package-versions", - "version": "2.0.6", + "version": "2.1.0", "source": { "type": "git", "url": "https://github.com/Jean85/pretty-package-versions.git", - "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4" + "reference": "3c4e5f62ba8d7de1734312e4fff32f67a8daaf10" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/f9fdd29ad8e6d024f52678b570e5593759b550b4", - "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4", + "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/3c4e5f62ba8d7de1734312e4fff32f67a8daaf10", + "reference": "3c4e5f62ba8d7de1734312e4fff32f67a8daaf10", "shasum": "" }, "require": { - "composer-runtime-api": "^2.0.0", - "php": "^7.1|^8.0" + "composer-runtime-api": "^2.1.0", + "php": "^7.4|^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.2", "jean85/composer-provided-replaced-stub-package": "^1.0", "phpstan/phpstan": "^1.4", - "phpunit/phpunit": "^7.5|^8.5|^9.4", - "vimeo/psalm": "^4.3" + "phpunit/phpunit": "^7.5|^8.5|^9.6", + "vimeo/psalm": "^4.3 || ^5.0" }, "type": "library", "extra": { @@ -61,9 +246,9 @@ ], "support": { "issues": "https://github.com/Jean85/pretty-package-versions/issues", - "source": "https://github.com/Jean85/pretty-package-versions/tree/2.0.6" + "source": "https://github.com/Jean85/pretty-package-versions/tree/2.1.0" }, - "time": "2024-03-08T09:58:59+00:00" + "time": "2024-11-18T16:19:46+00:00" }, { "name": "mongodb/mongodb", @@ -100,73 +285,1624 @@ }, "autoload": { "files": [ - "src/functions.php" + "src/functions.php" + ], + "psr-4": { + "MongoDB\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Andreas Braun", + "email": "andreas.braun@mongodb.com" + }, + { + "name": "Jeremy Mikola", + "email": "jmikola@gmail.com" + } + ], + "description": "MongoDB driver library", + "homepage": "https://jira.mongodb.org/browse/PHPLIB", + "keywords": [ + "database", + "driver", + "mongodb", + "persistence" + ], + "support": { + "issues": "https://github.com/mongodb/mongo-php-library/issues", + "source": "https://github.com/mongodb/mongo-php-library/tree/1.10.0" + }, + "time": "2021-10-20T22:22:37+00:00" + }, + { + "name": "nyholm/psr7", + "version": "1.8.2", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7.git", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7/zipball/a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0", + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "http-interop/http-factory-tests": "^0.9", + "php-http/message-factory": "^1.0", + "php-http/psr7-integration-tests": "^1.0", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.4", + "symfony/error-handler": "^4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Nyholm\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "A fast PHP7 implementation of PSR-7", + "homepage": "https://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7/issues", + "source": "https://github.com/Nyholm/psr7/tree/1.8.2" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2024-09-09T07:06:30+00:00" + }, + { + "name": "nyholm/psr7-server", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7-server.git", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7-server/zipball/4335801d851f554ca43fa6e7d2602141538854dc", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "require-dev": { + "nyholm/nsa": "^1.1", + "nyholm/psr7": "^1.3", + "phpunit/phpunit": "^7.0 || ^8.5 || ^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Nyholm\\Psr7Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "Helper classes to handle PSR-7 server requests", + "homepage": "http://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7-server/issues", + "source": "https://github.com/Nyholm/psr7-server/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2023-11-08T09:30:43+00:00" + }, + { + "name": "open-telemetry/api", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/api.git", + "reference": "351a30baa79699de3de3a814c8ccc7b52ccdfb1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/351a30baa79699de3de3a814c8ccc7b52ccdfb1d", + "reference": "351a30baa79699de3de3a814c8ccc7b52ccdfb1d", + "shasum": "" + }, + "require": { + "open-telemetry/context": "^1.0", + "php": "^8.1", + "psr/log": "^1.1|^2.0|^3.0", + "symfony/polyfill-php82": "^1.26" + }, + "conflict": { + "open-telemetry/sdk": "<=1.0.8" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.1.x-dev" + } + }, + "autoload": { + "files": [ + "Trace/functions.php" + ], + "psr-4": { + "OpenTelemetry\\API\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "API for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "api", + "apm", + "logging", + "opentelemetry", + "otel", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:34+00:00" + }, + { + "name": "open-telemetry/context", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/context.git", + "reference": "0cba875ea1953435f78aec7f1d75afa87bdbf7f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/0cba875ea1953435f78aec7f1d75afa87bdbf7f3", + "reference": "0cba875ea1953435f78aec7f1d75afa87bdbf7f3", + "shasum": "" + }, + "require": { + "php": "^8.1", + "symfony/polyfill-php82": "^1.26" + }, + "suggest": { + "ext-ffi": "To allow context switching in Fibers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "fiber/initialize_fiber_handler.php" + ], + "psr-4": { + "OpenTelemetry\\Context\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Context implementation for OpenTelemetry PHP.", + "keywords": [ + "Context", + "opentelemetry", + "otel" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-08-21T00:29:20+00:00" + }, + { + "name": "open-telemetry/exporter-otlp", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/exporter-otlp.git", + "reference": "243d9657c44a06f740cf384f486afe954c2b725f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/exporter-otlp/zipball/243d9657c44a06f740cf384f486afe954c2b725f", + "reference": "243d9657c44a06f740cf384f486afe954c2b725f", + "shasum": "" + }, + "require": { + "open-telemetry/api": "^1.0", + "open-telemetry/gen-otlp-protobuf": "^1.1", + "open-telemetry/sdk": "^1.0", + "php": "^8.1", + "php-http/discovery": "^1.14" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "_register.php" + ], + "psr-4": { + "OpenTelemetry\\Contrib\\Otlp\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "OTLP exporter for OpenTelemetry.", + "keywords": [ + "Metrics", + "exporter", + "gRPC", + "http", + "opentelemetry", + "otel", + "otlp", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:03+00:00" + }, + { + "name": "open-telemetry/gen-otlp-protobuf", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/gen-otlp-protobuf.git", + "reference": "66c3b98e998a726691c92e6405a82e6e7b8b169d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/gen-otlp-protobuf/zipball/66c3b98e998a726691c92e6405a82e6e7b8b169d", + "reference": "66c3b98e998a726691c92e6405a82e6e7b8b169d", + "shasum": "" + }, + "require": { + "google/protobuf": "^3.22 || ^4.0", + "php": "^8.0" + }, + "suggest": { + "ext-protobuf": "For better performance, when dealing with the protobuf format" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Opentelemetry\\Proto\\": "Opentelemetry/Proto/", + "GPBMetadata\\Opentelemetry\\": "GPBMetadata/Opentelemetry/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "PHP protobuf files for communication with OpenTelemetry OTLP collectors/servers.", + "keywords": [ + "Metrics", + "apm", + "gRPC", + "logging", + "opentelemetry", + "otel", + "otlp", + "protobuf", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-10-30T11:49:49+00:00" + }, + { + "name": "open-telemetry/sdk", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sdk.git", + "reference": "9a1c3b866239dbff291e5cc555bb7793eab08127" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/9a1c3b866239dbff291e5cc555bb7793eab08127", + "reference": "9a1c3b866239dbff291e5cc555bb7793eab08127", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nyholm/psr7-server": "^1.1", + "open-telemetry/api": "~1.0 || ~1.1", + "open-telemetry/context": "^1.0", + "open-telemetry/sem-conv": "^1.0", + "php": "^8.1", + "php-http/discovery": "^1.14", + "psr/http-client": "^1.0", + "psr/http-client-implementation": "^1.0", + "psr/http-factory-implementation": "^1.0", + "psr/http-message": "^1.0.1|^2.0", + "psr/log": "^1.1|^2.0|^3.0", + "ramsey/uuid": "^3.0 || ^4.0", + "symfony/polyfill-mbstring": "^1.23", + "symfony/polyfill-php82": "^1.26", + "tbachert/spi": "^1.0.1" + }, + "suggest": { + "ext-gmp": "To support unlimited number of synchronous metric readers", + "ext-mbstring": "To increase performance of string operations", + "open-telemetry/sdk-configuration": "File-based OpenTelemetry SDK configuration" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "Common/Util/functions.php", + "Logs/Exporter/_register.php", + "Metrics/MetricExporter/_register.php", + "Propagation/_register.php", + "Trace/SpanExporter/_register.php", + "Common/Dev/Compatibility/_load.php", + "_autoload.php" + ], + "psr-4": { + "OpenTelemetry\\SDK\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "SDK for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "sdk", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:34+00:00" + }, + { + "name": "open-telemetry/sem-conv", + "version": "1.27.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sem-conv.git", + "reference": "1dba705fea74bc0718d04be26090e3697e56f4e6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sem-conv/zipball/1dba705fea74bc0718d04be26090e3697e56f4e6", + "reference": "1dba705fea74bc0718d04be26090e3697e56f4e6", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "OpenTelemetry\\SemConv\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Semantic conventions for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "semantic conventions", + "semconv", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-08-28T09:20:31+00:00" + }, + { + "name": "php-http/discovery", + "version": "1.20.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/discovery.git", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/discovery/zipball/82fe4c73ef3363caed49ff8dd1539ba06044910d", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0|^2.0", + "php": "^7.1 || ^8.0" + }, + "conflict": { + "nyholm/psr7": "<1.0", + "zendframework/zend-diactoros": "*" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "*", + "psr/http-factory-implementation": "*", + "psr/http-message-implementation": "*" + }, + "require-dev": { + "composer/composer": "^1.0.2|^2.0", + "graham-campbell/phpspec-skip-example-extension": "^5.0", + "php-http/httplug": "^1.0 || ^2.0", + "php-http/message-factory": "^1.0", + "phpspec/phpspec": "^5.1 || ^6.1 || ^7.3", + "sebastian/comparator": "^3.0.5 || ^4.0.8", + "symfony/phpunit-bridge": "^6.4.4 || ^7.0.1" + }, + "type": "composer-plugin", + "extra": { + "class": "Http\\Discovery\\Composer\\Plugin", + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Http\\Discovery\\": "src/" + }, + "exclude-from-classmap": [ + "src/Composer/Plugin.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations", + "homepage": "http://php-http.org", + "keywords": [ + "adapter", + "client", + "discovery", + "factory", + "http", + "message", + "psr17", + "psr7" + ], + "support": { + "issues": "https://github.com/php-http/discovery/issues", + "source": "https://github.com/php-http/discovery/tree/1.20.0" + }, + "time": "2024-10-02T11:20:13+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "ramsey/collection", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/collection.git", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/collection/zipball/a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "captainhook/plugin-composer": "^5.3", + "ergebnis/composer-normalize": "^2.28.3", + "fakerphp/faker": "^1.21", + "hamcrest/hamcrest-php": "^2.0", + "jangregor/phpstan-prophecy": "^1.0", + "mockery/mockery": "^1.5", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcsstandards/phpcsutils": "^1.0.0-rc1", + "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.2", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5", + "psalm/plugin-mockery": "^1.1", + "psalm/plugin-phpunit": "^0.18.4", + "ramsey/coding-standard": "^2.0.3", + "ramsey/conventional-commits": "^1.3", + "vimeo/psalm": "^5.4" + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "description": "A PHP library for representing and manipulating collections.", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "support": { + "issues": "https://github.com/ramsey/collection/issues", + "source": "https://github.com/ramsey/collection/tree/2.0.0" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/collection", + "type": "tidelift" + } + ], + "time": "2022-12-31T21:50:55+00:00" + }, + { + "name": "ramsey/uuid", + "version": "4.7.6", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "91039bc1faa45ba123c4328958e620d382ec7088" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/91039bc1faa45ba123c4328958e620d382ec7088", + "reference": "91039bc1faa45ba123c4328958e620d382ec7088", + "shasum": "" + }, + "require": { + "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12", + "ext-json": "*", + "php": "^8.0", + "ramsey/collection": "^1.2 || ^2.0" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "require-dev": { + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.8", + "ergebnis/composer-normalize": "^2.15", + "mockery/mockery": "^1.3", + "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", + "php-mock/php-mock-mockery": "^1.3", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^8.5 || ^9", + "ramsey/composer-repl": "^1.4", + "slevomat/coding-standard": "^8.4", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.9" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Ramsey\\Uuid\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "support": { + "issues": "https://github.com/ramsey/uuid/issues", + "source": "https://github.com/ramsey/uuid/tree/4.7.6" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/uuid", + "type": "tidelift" + } + ], + "time": "2024-04-27T21:32:50+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.5.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", + "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:20:29+00:00" + }, + { + "name": "symfony/http-client", + "version": "v7.2.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client.git", + "reference": "339ba21476eb184290361542f732ad12c97591ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client/zipball/339ba21476eb184290361542f732ad12c97591ec", + "reference": "339ba21476eb184290361542f732ad12c97591ec", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/http-client-contracts": "~3.4.4|^3.5.2", + "symfony/service-contracts": "^2.5|^3" + }, + "conflict": { + "amphp/amp": "<2.5", + "php-http/discovery": "<1.15", + "symfony/http-foundation": "<6.4" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "1.0", + "symfony/http-client-implementation": "3.0" + }, + "require-dev": { + "amphp/http-client": "^4.2.1|^5.0", + "amphp/http-tunnel": "^1.0|^2.0", + "amphp/socket": "^1.1", + "guzzlehttp/promises": "^1.4|^2.0", + "nyholm/psr7": "^1.0", + "php-http/httplug": "^1.0|^2.0", + "psr/http-client": "^1.0", + "symfony/amphp-http-client-meta": "^1.0|^2.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/rate-limiter": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously", + "homepage": "https://symfony.com", + "keywords": [ + "http" + ], + "support": { + "source": "https://github.com/symfony/http-client/tree/v7.2.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-30T18:35:15+00:00" + }, + { + "name": "symfony/http-client-contracts", + "version": "v3.5.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/ee8d807ab20fcb51267fdace50fbe3494c31e645", + "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v3.5.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-07T08:49:48+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/85181ba99b2345b0ef10ce42ecac37612d9fd341", + "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-php82", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php82.git", + "reference": "5d2ed36f7734637dacc025f179698031951b1692" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/5d2ed36f7734637dacc025f179698031951b1692", + "reference": "5d2ed36f7734637dacc025f179698031951b1692", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" ], "psr-4": { - "MongoDB\\": "src/" - } + "Symfony\\Polyfill\\Php82\\": "" + }, + "classmap": [ + "Resources/stubs" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "Apache-2.0" + "MIT" ], "authors": [ { - "name": "Andreas Braun", - "email": "andreas.braun@mongodb.com" + "name": "Nicolas Grekas", + "email": "p@tchwork.com" }, { - "name": "Jeremy Mikola", - "email": "jmikola@gmail.com" + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" } ], - "description": "MongoDB driver library", - "homepage": "https://jira.mongodb.org/browse/PHPLIB", + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "homepage": "https://symfony.com", "keywords": [ - "database", - "driver", - "mongodb", - "persistence" + "compatibility", + "polyfill", + "portable", + "shim" ], "support": { - "issues": "https://github.com/mongodb/mongo-php-library/issues", - "source": "https://github.com/mongodb/mongo-php-library/tree/1.10.0" + "source": "https://github.com/symfony/polyfill-php82/tree/v1.31.0" }, - "time": "2021-10-20T22:22:37+00:00" + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" }, { - "name": "symfony/polyfill-php80", - "version": "v1.31.0", + "name": "symfony/service-contracts", + "version": "v3.5.1", "source": { "type": "git", - "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + "url": "https://github.com/symfony/service-contracts.git", + "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", - "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/e53260aabf78fb3d63f8d79d69ece59f80d5eda0", + "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0", "shasum": "" }, "require": { - "php": ">=7.2" + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" }, "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" } }, "autoload": { - "files": [ - "bootstrap.php" - ], "psr-4": { - "Symfony\\Polyfill\\Php80\\": "" + "Symfony\\Contracts\\Service\\": "" }, - "classmap": [ - "Resources/stubs" + "exclude-from-classmap": [ + "/Test/" ] }, "notification-url": "https://packagist.org/downloads/", @@ -174,10 +1910,6 @@ "MIT" ], "authors": [ - { - "name": "Ion Bazan", - "email": "ion.bazan@gmail.com" - }, { "name": "Nicolas Grekas", "email": "p@tchwork.com" @@ -187,16 +1919,18 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "description": "Generic abstractions related to writing services", "homepage": "https://symfony.com", "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + "source": "https://github.com/symfony/service-contracts/tree/v3.5.1" }, "funding": [ { @@ -212,7 +1946,59 @@ "type": "tidelift" } ], - "time": "2024-09-09T11:45:10+00:00" + "time": "2024-09-25T14:20:29+00:00" + }, + { + "name": "tbachert/spi", + "version": "v1.0.2", + "source": { + "type": "git", + "url": "https://github.com/Nevay/spi.git", + "reference": "2ddfaf815dafb45791a61b08170de8d583c16062" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nevay/spi/zipball/2ddfaf815dafb45791a61b08170de8d583c16062", + "reference": "2ddfaf815dafb45791a61b08170de8d583c16062", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.0", + "composer/semver": "^1.0 || ^2.0 || ^3.0", + "php": "^8.1" + }, + "require-dev": { + "composer/composer": "^2.0", + "infection/infection": "^0.27.9", + "phpunit/phpunit": "^10.5", + "psalm/phar": "^5.18" + }, + "type": "composer-plugin", + "extra": { + "class": "Nevay\\SPI\\Composer\\Plugin", + "branch-alias": { + "dev-main": "0.2.x-dev" + }, + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Nevay\\SPI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Service provider loading facility", + "keywords": [ + "service provider" + ], + "support": { + "issues": "https://github.com/Nevay/spi/issues", + "source": "https://github.com/Nevay/spi/tree/v1.0.2" + }, + "time": "2024-10-04T16:36:12+00:00" }, { "name": "utopia-php/cache", @@ -265,79 +2051,75 @@ "time": "2024-06-25T20:36:35+00:00" }, { - "name": "utopia-php/di", - "version": "0.1.0", + "name": "utopia-php/compression", + "version": "0.1.2", "source": { "type": "git", - "url": "https://github.com/utopia-php/di.git", - "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31" + "url": "https://github.com/utopia-php/compression.git", + "reference": "6062f70596415f8d5de40a589367b0eb2a435f98" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/di/zipball/22490c95f7ac3898ed1c33f1b1b5dd577305ee31", - "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "url": "https://api.github.com/repos/utopia-php/compression/zipball/6062f70596415f8d5de40a589367b0eb2a435f98", + "reference": "6062f70596415f8d5de40a589367b0eb2a435f98", "shasum": "" }, "require": { - "php": ">=8.2" + "php": ">=8.0" }, "require-dev": { - "laravel/pint": "^1.2", - "phpbench/phpbench": "^1.2", - "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25", - "swoole/ide-helper": "4.8.3" + "laravel/pint": "1.2.*", + "phpunit/phpunit": "^9.3", + "vimeo/psalm": "4.0.1" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/", - "Tests\\E2E\\": "tests/e2e" + "Utopia\\Compression\\": "src/Compression" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "description": "A simple and lite library for managing dependency injections", + "description": "A simple Compression library to handle file compression", "keywords": [ + "compression", "framework", - "http", "php", - "upf" + "upf", + "utopia" ], "support": { - "issues": "https://github.com/utopia-php/di/issues", - "source": "https://github.com/utopia-php/di/tree/0.1.0" + "issues": "https://github.com/utopia-php/compression/issues", + "source": "https://github.com/utopia-php/compression/tree/0.1.2" }, - "time": "2024-08-08T14:35:19+00:00" + "time": "2024-11-08T14:59:54+00:00" }, { "name": "utopia-php/framework", - "version": "1.0.2", + "version": "0.33.15", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "fc63ec61c720190a5ea5bb484c615145850951e6" + "reference": "83b0628900c2c53e8c3efbf069f3e13050295edc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/fc63ec61c720190a5ea5bb484c615145850951e6", - "reference": "fc63ec61c720190a5ea5bb484c615145850951e6", + "url": "https://api.github.com/repos/utopia-php/http/zipball/83b0628900c2c53e8c3efbf069f3e13050295edc", + "reference": "83b0628900c2c53e8c3efbf069f3e13050295edc", "shasum": "" }, "require": { - "ext-swoole": "*", - "php": ">=8.0", - "utopia-php/servers": "0.1.*" + "php": ">=8.1", + "utopia-php/compression": "0.1.*", + "utopia-php/telemetry": "0.1.*" }, "require-dev": { - "ext-xdebug": "*", "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25", - "swoole/ide-helper": "4.8.3" + "phpunit/phpunit": "^9.5.25" }, "type": "library", "autoload": { @@ -349,18 +2131,17 @@ "license": [ "MIT" ], - "description": "A simple, light and advanced PHP HTTP framework", + "description": "A simple, light and advanced PHP framework", "keywords": [ "framework", - "http", "php", "upf" ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/1.0.2" + "source": "https://github.com/utopia-php/http/tree/0.33.15" }, - "time": "2024-09-10T09:04:19+00:00" + "time": "2024-12-10T13:07:04+00:00" }, { "name": "utopia-php/mongo", @@ -423,57 +2204,54 @@ "time": "2023-09-01T17:25:28+00:00" }, { - "name": "utopia-php/servers", - "version": "0.1.1", + "name": "utopia-php/telemetry", + "version": "0.1.0", "source": { "type": "git", - "url": "https://github.com/utopia-php/servers.git", - "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a" + "url": "https://github.com/utopia-php/telemetry.git", + "reference": "d35f2f0632f4ee0be63fb7ace6a94a6adda71a80" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/servers/zipball/fd5c8d32778f265256c1936372a071b944f5ba8a", - "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a", + "url": "https://api.github.com/repos/utopia-php/telemetry/zipball/d35f2f0632f4ee0be63fb7ace6a94a6adda71a80", + "reference": "d35f2f0632f4ee0be63fb7ace6a94a6adda71a80", "shasum": "" }, "require": { + "ext-opentelemetry": "*", + "ext-protobuf": "*", + "nyholm/psr7": "^1.8", + "open-telemetry/exporter-otlp": "^1.1", + "open-telemetry/sdk": "^1.1", "php": ">=8.0", - "utopia-php/di": "0.1.*" + "symfony/http-client": "^7.1" }, "require-dev": { - "laravel/pint": "^0.2.3", - "phpstan/phpstan": "^1.8", - "phpunit/phpunit": "^9.5.5" + "laravel/pint": "^1.2", + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^9.5.25" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\Servers\\": "src/Servers" + "Utopia\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "authors": [ - { - "name": "Team Appwrite", - "email": "team@appwrite.io" - } - ], - "description": "A base library for building Utopia style servers.", "keywords": [ "framework", "php", - "servers", - "upf", - "utopia" + "upf" ], "support": { - "issues": "https://github.com/utopia-php/servers/issues", - "source": "https://github.com/utopia-php/servers/tree/0.1.1" + "issues": "https://github.com/utopia-php/telemetry/issues", + "source": "https://github.com/utopia-php/telemetry/tree/0.1.0" }, - "time": "2024-09-06T02:25:56+00:00" + "time": "2024-11-13T10:29:53+00:00" } ], "packages-dev": [ @@ -678,16 +2456,16 @@ }, { "name": "myclabs/deep-copy", - "version": "1.12.0", + "version": "1.12.1", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c" + "reference": "123267b2c49fbf30d78a7b2d333f6be754b94845" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c", - "reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/123267b2c49fbf30d78a7b2d333f6be754b94845", + "reference": "123267b2c49fbf30d78a7b2d333f6be754b94845", "shasum": "" }, "require": { @@ -726,7 +2504,7 @@ ], "support": { "issues": "https://github.com/myclabs/DeepCopy/issues", - "source": "https://github.com/myclabs/DeepCopy/tree/1.12.0" + "source": "https://github.com/myclabs/DeepCopy/tree/1.12.1" }, "funding": [ { @@ -734,7 +2512,7 @@ "type": "tidelift" } ], - "time": "2024-06-12T14:39:25+00:00" + "time": "2024-11-08T17:47:46+00:00" }, { "name": "nikic/php-parser", @@ -1323,16 +3101,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.21", + "version": "9.6.22", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa" + "reference": "f80235cb4d3caa59ae09be3adf1ded27521d1a9c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", - "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f80235cb4d3caa59ae09be3adf1ded27521d1a9c", + "reference": "f80235cb4d3caa59ae09be3adf1ded27521d1a9c", "shasum": "" }, "require": { @@ -1343,7 +3121,7 @@ "ext-mbstring": "*", "ext-xml": "*", "ext-xmlwriter": "*", - "myclabs/deep-copy": "^1.12.0", + "myclabs/deep-copy": "^1.12.1", "phar-io/manifest": "^2.0.4", "phar-io/version": "^3.2.1", "php": ">=7.3", @@ -1406,7 +3184,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.21" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.22" }, "funding": [ { @@ -1422,60 +3200,7 @@ "type": "tidelift" } ], - "time": "2024-09-19T10:50:18+00:00" - }, - { - "name": "psr/container", - "version": "2.0.2", - "source": { - "type": "git", - "url": "https://github.com/php-fig/container.git", - "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", - "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", - "shasum": "" - }, - "require": { - "php": ">=7.4.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Container\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "https://www.php-fig.org/" - } - ], - "description": "Common Container Interface (PHP FIG PSR-11)", - "homepage": "https://github.com/php-fig/container", - "keywords": [ - "PSR-11", - "container", - "container-interface", - "container-interop", - "psr" - ], - "support": { - "issues": "https://github.com/php-fig/container/issues", - "source": "https://github.com/php-fig/container/tree/2.0.2" - }, - "time": "2021-11-05T16:47:00+00:00" + "time": "2024-12-05T13:48:26+00:00" }, { "name": "rregeer/phpunit-coverage-check", @@ -2518,73 +4243,6 @@ }, "time": "2024-06-17T05:45:20+00:00" }, - { - "name": "symfony/deprecation-contracts", - "version": "v3.5.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", - "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", - "shasum": "" - }, - "require": { - "php": ">=8.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "3.5-dev" - }, - "thanks": { - "name": "symfony/contracts", - "url": "https://github.com/symfony/contracts" - } - }, - "autoload": { - "files": [ - "function.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "A generic function and convention to trigger deprecation notices", - "homepage": "https://symfony.com", - "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2024-04-18T09:32:20+00:00" - }, { "name": "theseer/tokenizer", "version": "1.2.3", @@ -2637,29 +4295,25 @@ }, { "name": "utopia-php/cli", - "version": "0.19.0", + "version": "0.14.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "f8af1d6087f498bc1f0191750a118d357ded9948" + "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/f8af1d6087f498bc1f0191750a118d357ded9948", - "reference": "f8af1d6087f498bc1f0191750a118d357ded9948", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", + "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/di": "0.1.*", - "utopia-php/framework": "1.0.*" + "utopia-php/framework": "0.*.*" }, "require-dev": { - "laravel/pint": "1.2.*", - "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6", - "swoole/ide-helper": "4.8.8" + "squizlabs/php_codesniffer": "^3.6" }, "type": "library", "autoload": { @@ -2671,6 +4325,12 @@ "license": [ "MIT" ], + "authors": [ + { + "name": "Eldad Fux", + "email": "eldad@appwrite.io" + } + ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2682,9 +4342,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.19.0" + "source": "https://github.com/utopia-php/cli/tree/0.14.0" }, - "time": "2024-09-05T15:46:56+00:00" + "time": "2022-10-09T10:19:07+00:00" } ], "aliases": [], diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index a5cffd444..1ef3518bf 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -6,7 +6,6 @@ use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Timeout as TimeoutException; -use Utopia\Database\Validator\Authorization; abstract class Adapter { @@ -37,35 +36,6 @@ abstract class Adapter */ protected array $metadata = []; - /** - * @var Authorization - */ - protected Authorization $authorization; - - /** - * @param Authorization $authorization - * - * @return $this - */ - public function setAuthorization(Authorization $authorization): self - { - $this->authorization = $authorization; - - return $this; - } - - /** - * @return $this - */ - public function clearTransformations(): self - { - $this->transformations = [ - '*' => [], - ]; - - return $this; - } - /** * @param string $key * @param mixed $value @@ -901,7 +871,7 @@ protected function getAttributeSelections(array $queries): array */ public function filter(string $value): string { - $value = \preg_replace("/[^A-Za-z0-9\_\-]/", '', $value); + $value = \preg_replace("/[^A-Za-z0-9_\-]/", '', $value); if (\is_null($value)) { throw new DatabaseException('Failed to filter key'); diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index e98ba76a1..73bf4d6a4 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -12,6 +12,7 @@ use Utopia\Database\Exception\Timeout as TimeoutException; use Utopia\Database\Exception\Truncate as TruncateException; use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; class MariaDB extends SQL { @@ -730,7 +731,7 @@ public function createIndex(string $collection, string $id, string $type, array $attributes[$i] = "`{$attr}`{$length} {$order}"; - if (!empty($collectionAttribute['array']) && $this->castIndexArray()) { + if(!empty($collectionAttribute['array']) && $this->castIndexArray()) { $attributes[$i] = '(CAST(' . $attr . ' AS char(' . Database::ARRAY_INDEX_LENGTH . ') ARRAY))'; } } @@ -914,7 +915,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions->execute(); } } catch (\Throwable $e) { - if ($e instanceof PDOException) { + if($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -962,7 +963,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_createdAt'] = $document->getCreatedAt(); $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if (!empty($document->getInternalId())) { + if(!empty($document->getInternalId())) { $attributes['_id'] = $document->getInternalId(); } @@ -1042,7 +1043,7 @@ public function createDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if ($e instanceof PDOException) { + if($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1290,7 +1291,7 @@ public function updateDocument(string $collection, string $id, Document $documen } } catch (\Throwable $e) { - if ($e instanceof PDOException) { + if($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1765,7 +1766,7 @@ public function deleteDocuments(string $collection, array $ids): int public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $orders = []; @@ -1847,11 +1848,11 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { + if(!empty($conditions)) { $where[] = $conditions; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } @@ -1968,18 +1969,18 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null): int { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { + if(!empty($conditions)) { $where[] = $conditions; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -2041,7 +2042,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): int|float { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -2051,7 +2052,7 @@ public function sum(string $collection, string $attribute, array $queries = [], $where[] = $this->getSQLCondition($query); } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -2192,7 +2193,7 @@ protected function getSQLCondition(Query $query): string return "`table_main`.{$attribute} {$this->getSQLOperator($query->getMethod())}"; case Query::TYPE_CONTAINS: - if ($this->getSupportForJSONOverlaps() && $query->onArray()) { + if($this->getSupportForJSONOverlaps() && $query->onArray()) { return "JSON_OVERLAPS(`table_main`.{$attribute}, :{$placeholder}_0)"; } @@ -2218,7 +2219,7 @@ protected function getSQLCondition(Query $query): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if ($array === true) { + if($array === true) { return 'JSON'; } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index b88d575cd..1bd7a095b 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -3,6 +3,7 @@ namespace Utopia\Database\Adapter; use Exception; + use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -301,7 +302,7 @@ public function getSizeOfCollection(string $collection): int } else { throw new DatabaseException('No size found'); } - } catch (Exception $e) { + } catch(Exception $e) { throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); } } @@ -1020,8 +1021,8 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("{$forPermission}\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1296,8 +1297,8 @@ public function count(string $collection, array $queries = [], ?int $max = null) $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { // skip if authorization is disabled + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1324,8 +1325,8 @@ public function sum(string $collection, string $attribute, array $queries = [], $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { // skip if authorization is disabled + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1433,7 +1434,7 @@ protected function buildFilters(array $queries, string $separator = '$and'): arr $queries = Query::groupByType($queries)['filters']; foreach ($queries as $query) { /* @var $query Query */ - if ($query->isNested()) { + if($query->isNested()) { $operator = $this->getQueryOperator($query->getMethod()); $filters[$separator][] = $this->buildFilters($query->getValues(), $operator); } else { @@ -1487,7 +1488,7 @@ protected function buildFilter(Query $query): array } elseif ($operator == '$ne' && \is_array($value)) { $filter[$attribute]['$nin'] = $value; } elseif ($operator == '$in') { - if ($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { + if($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { $filter[$attribute]['$regex'] = new Regex(".*{$this->escapeWildcards($value)}.*", 'i'); } else { $filter[$attribute]['$in'] = $query->getValues(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 7d1746fa8..fbc1aaa44 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -13,6 +13,7 @@ use Utopia\Database\Exception\Timeout; use Utopia\Database\Exception\Truncate as TruncateException; use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; class Postgres extends SQL { @@ -875,7 +876,7 @@ public function createDocument(string $collection, Document $document): Document $queryPermissions = $this->trigger(Database::EVENT_PERMISSIONS_CREATE, $queryPermissions); $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if ($sqlTenant) { + if($sqlTenant) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -934,7 +935,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if ($this->sharedTables) { + if($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1691,7 +1692,7 @@ public function deleteDocuments(string $collection, array $ids): int public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $orders = []; @@ -1767,7 +1768,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { + if(!empty($conditions)) { $where[] = $conditions; } @@ -1775,8 +1776,8 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, $where[] = "table_main._tenant = :_tenant"; } - if ($this->authorization->getStatus()) { - $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); + if (Authorization::$status) { + $where[] = $this->getSQLPermissionsCondition($name, $roles); } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; @@ -1888,14 +1889,14 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null): int { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if (!empty($conditions)) { + if(!empty($conditions)) { $where[] = $conditions; } @@ -1903,7 +1904,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $where[] = "table_main._tenant = :_tenant"; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1954,7 +1955,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): int|float { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1968,7 +1969,7 @@ public function sum(string $collection, string $attribute, array $queries = [], $where[] = "table_main._tenant = :_tenant"; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -2135,7 +2136,7 @@ protected function getFulltextValue(string $value): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if ($array === true) { + if($array === true) { return 'JSONB'; } diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index b06492f3f..567b0f6c1 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -828,14 +828,14 @@ protected function bindConditionValue(mixed $stmt, Query $query): void return; } - if ($query->isNested()) { + if($query->isNested()) { foreach ($query->getValues() as $value) { $this->bindConditionValue($stmt, $value); } return; } - if ($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { + if($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { $placeholder = $this->getSQLPlaceholder($query) . '_0'; $stmt->bindValue($placeholder, json_encode($query->getValues()), PDO::PARAM_STR); return; @@ -1085,7 +1085,7 @@ public function getSQLConditions(array $queries = [], string $separator = 'AND') continue; } - if ($query->isNested()) { + if($query->isNested()) { $conditions[] = $this->getSQLConditions($query->getValues(), $query->getMethod()); } else { $conditions[] = $this->getSQLCondition($query); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 55494fa55..27d7379ef 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -460,7 +460,7 @@ public function createDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if ($this->sharedTables) { + if($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -534,7 +534,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if ($this->sharedTables) { + if($this->sharedTables) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -579,7 +579,7 @@ public function updateDocument(string $collection, string $id, Document $documen $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if ($this->sharedTables) { + if($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -713,7 +713,7 @@ public function updateDocument(string $collection, string $id, Document $documen $stmtAddPermissions = $this->getPDO()->prepare($sql); $stmtAddPermissions->bindValue(":_uid", $document->getId()); - if ($this->sharedTables) { + if($this->sharedTables) { $stmtAddPermissions->bindValue(":_tenant", $this->tenant); } diff --git a/src/Database/Database.php b/src/Database/Database.php index 89170c484..8957f0072 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -18,7 +18,6 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Database\Validator\Authorization\Input; use Utopia\Database\Validator\Index as IndexValidator; use Utopia\Database\Validator\PartialStructure; use Utopia\Database\Validator\Permissions; @@ -346,11 +345,6 @@ class Database */ protected array $relationshipDeleteStack = []; - /** - * @var Authorization - */ - private Authorization $authorization; - /** * @param Adapter $adapter * @param Cache $cache @@ -362,8 +356,6 @@ public function __construct(Adapter $adapter, Cache $cache, array $filters = []) $this->cache = $cache; $this->instanceFilters = $filters; - $this->setAuthorization(new Authorization()); - self::addFilter( 'json', /** @@ -435,29 +427,6 @@ function (?string $value) { ); } - /** - * Sets instance of authorization for permission checks - * - * @param Authorization $authorization - * @return self - */ - public function setAuthorization(Authorization $authorization): self - { - $this->adapter->setAuthorization($authorization); - $this->authorization = $authorization; - return $this; - } - - /** - * Get instance of authorization - * - * @return Authorization - */ - public function getAuthorization(): Authorization - { - return $this->authorization; - } - /** * Add listener to events * @@ -2874,6 +2843,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $queries = \array_values($queries); + $validator = new Authorization(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); /** @@ -2890,12 +2860,10 @@ public function getDocument(string $collection, string $id, array $queries = [], $document = new Document($cache); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + if (!$validator->isValid([ ...$collection->getRead(), ...($documentSecurity ? $document->getRead() : []) - ])); - - if (!$isValid) { + ])) { return new Document(); } } @@ -2914,12 +2882,10 @@ public function getDocument(string $collection, string $id, array $queries = [], $document->setAttribute('$collection', $collection->getId()); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + if (!$validator->isValid([ ...$collection->getRead(), ...($documentSecurity ? $document->getRead() : []) - ])); - - if (!$isValid) { + ])) { return new Document(); } } @@ -3244,9 +3210,9 @@ public function createDocument(string $collection, Document $document): Document $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_CREATE, $collection->getCreate())); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + $authorization = new Authorization(self::PERMISSION_CREATE); + if (!$authorization->isValid($collection->getCreate())) { + throw new AuthorizationException($authorization->getDescription()); } } @@ -3715,7 +3681,7 @@ public function updateDocument(string $collection, string $id, Document $documen $document = $this->withTransaction(function () use ($collection, $id, $document) { $time = DateTime::now(); - $old = $this->authorization->skip(fn () => $this->silent( + $old = Authorization::skip(fn () => $this->silent( fn () => $this->getDocument($collection->getId(), $id, forUpdate: true) )); @@ -3734,6 +3700,8 @@ public function updateDocument(string $collection, string $id, Document $documen return $attribute['type'] === Database::VAR_RELATIONSHIP; }); + $updateValidator = new Authorization(self::PERMISSION_UPDATE); + $readValidator = new Authorization(self::PERMISSION_READ); $shouldUpdate = false; if ($collection->getId() !== self::METADATA) { @@ -3827,19 +3795,20 @@ public function updateDocument(string $collection, string $id, Document $documen } } - $updateValidator = new Input(self::PERMISSION_UPDATE, [ + $updatePermissions = [ ...$collection->getUpdate(), ...($documentSecurity ? $old->getUpdate() : []) - ]); + ]; - $readValidator = new Input(self::PERMISSION_READ, [ + $readPermissions = [ ...$collection->getRead(), ...($documentSecurity ? $old->getRead() : []) - ]); + ]; - if (($shouldUpdate && !$this->authorization->isValid($updateValidator)) - || (!$shouldUpdate && !$this->authorization->isValid($readValidator))) { - throw new AuthorizationException($this->authorization->getDescription()); + if ($shouldUpdate && !$updateValidator->isValid($updatePermissions)) { + throw new AuthorizationException($updateValidator->getDescription()); + } elseif (!$shouldUpdate && !$readValidator->isValid($readPermissions)) { + throw new AuthorizationException($readValidator->getDescription()); } } @@ -4196,7 +4165,7 @@ private function updateDocumentRelationships(Document $collection, Document $old $removedDocuments = \array_diff($oldIds, $newIds); foreach ($removedDocuments as $relation) { - $this->authorization->skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( + Authorization::skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation, new Document([$twoWayKey => null]) @@ -4326,7 +4295,7 @@ private function updateDocumentRelationships(Document $collection, Document $old ]); foreach ($junctions as $junction) { - $this->authorization->skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); + Authorization::skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); } } @@ -4419,10 +4388,12 @@ public function increaseDocumentAttribute(string $collection, string $id, string throw new DatabaseException('Value must be numeric and greater than 0'); } + $validator = new Authorization(self::PERMISSION_UPDATE); + /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if ($document->isEmpty()) { + if($document->isEmpty()) { return false; } @@ -4430,12 +4401,11 @@ public function increaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + if (!$validator->isValid([ ...$collection->getUpdate(), ...($documentSecurity ? $document->getUpdate() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4512,10 +4482,13 @@ public function decreaseDocumentAttribute(string $collection, string $id, string if ($value <= 0) { // Can be a float throw new DatabaseException('Value must be numeric and greater than 0'); } + + $validator = new Authorization(self::PERMISSION_UPDATE); + /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if ($document->isEmpty()) { + if($document->isEmpty()) { return false; } @@ -4523,12 +4496,11 @@ public function decreaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + if (!$validator->isValid([ ...$collection->getUpdate(), ...($documentSecurity ? $document->getUpdate() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4606,23 +4578,24 @@ public function deleteDocument(string $collection, string $id): bool $deleted = $this->withTransaction(function () use ($collection, $id, &$document) { /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent( + $document = Authorization::skip(fn () => $this->silent( fn () => $this->getDocument($collection->getId(), $id, forUpdate: true) )); - if ($document->isEmpty()) { + if($document->isEmpty()) { return false; } + $validator = new Authorization(self::PERMISSION_DELETE); + if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ + if (!$validator->isValid([ ...$collection->getDelete(), ...($documentSecurity ? $document->getDelete() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4783,7 +4756,7 @@ private function deleteRestrict( && $side === Database::RELATION_SIDE_CHILD && !$twoWay ) { - $this->authorization->skip(function () use ($document, $relatedCollection, $twoWayKey) { + Authorization::skip(function () use ($document, $relatedCollection, $twoWayKey) { $related = $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$document->getId()]) @@ -4807,7 +4780,7 @@ private function deleteRestrict( $relationType === Database::RELATION_MANY_TO_ONE && $side === Database::RELATION_SIDE_CHILD ) { - $related = $this->authorization->skip(fn () => $this->findOne($relatedCollection->getId(), [ + $related = Authorization::skip(fn () => $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$document->getId()]) ])); @@ -4843,7 +4816,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } // Shouldn't need read or update permission to delete - $this->authorization->skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { + Authorization::skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { if (!$twoWay && $side === Database::RELATION_SIDE_CHILD) { $related = $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), @@ -4875,7 +4848,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection break; } foreach ($value as $relation) { - $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { + Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation->getId(), @@ -4901,7 +4874,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } foreach ($value as $relation) { - $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { + Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation->getId(), @@ -5188,12 +5161,12 @@ public function find(string $collection, array $queries = [], string $forPermiss } } + $authorization = new Authorization(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); - - $skipAuth = $this->authorization->isValid(new Input($forPermission, $collection->getPermissionsByType($forPermission))); + $skipAuth = $authorization->isValid($collection->getPermissionsByType($forPermission))); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } $relationships = \array_filter( @@ -5281,9 +5254,9 @@ public function find(string $collection, array $queries = [], string $forPermiss $forPermission ); - $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + $results = $skipAuth ? Authorization::skip($getResults) : $getResults(); - foreach ($results as &$node) { + foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { $node = $this->silent(fn () => $this->populateDocumentRelationships($collection, $node, $nestedSelections)); } @@ -5368,13 +5341,16 @@ public function count(string $collection, array $queries = [], ?int $max = null) } } - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + $authorization = new Authorization(self::PERMISSION_READ); + if ($authorization->isValid($collection->getRead())) { + $skipAuth = true; + } $queries = Query::groupByType($queries)['filters']; $queries = self::convertQueries($collection, $queries); $getCount = fn () => $this->adapter->count($collection->getId(), $queries, $max); - $count = $skipAuth ? $this->authorization->skip($getCount) : $getCount(); + $count = $skipAuth ?? false ? Authorization::skip($getCount) : $getCount(); $this->trigger(self::EVENT_DOCUMENT_COUNT, $count); diff --git a/src/Database/Exception.php b/src/Database/Exception.php index 94099c6ae..64ad3c997 100644 --- a/src/Database/Exception.php +++ b/src/Database/Exception.php @@ -8,7 +8,7 @@ class Exception extends \Exception { public function __construct(string $message, int|string $code = 0, Throwable $previous = null) { - if (\is_string($code)) { + if(\is_string($code)) { if (\is_numeric($code)) { $code = (int) $code; } else { diff --git a/src/Database/Query.php b/src/Database/Query.php index aab17c195..6af553415 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -297,7 +297,7 @@ public function toArray(): array { $array = ['method' => $this->method]; - if (!empty($this->attribute)) { + if(!empty($this->attribute)) { $array['attribute'] = $this->attribute; } @@ -690,7 +690,7 @@ public static function groupByType(array $queries): array */ public function isNested(): bool { - if (in_array($this->getMethod(), self::LOGICAL_TYPES)) { + if(in_array($this->getMethod(), self::LOGICAL_TYPES)) { return true; } diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 22d0ebc5c..2dd645ba7 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -2,35 +2,34 @@ namespace Utopia\Database\Validator; -use Utopia\Database\Validator\Authorization\Input; -use Utopia\Http\Validator; +use Utopia\Validator; class Authorization extends Validator { /** - * @var bool + * @var array */ - protected bool $status = true; + private static array $roles = [ + 'any' => true + ]; /** - * Default value in case we need - * to reset Authorization status - * - * @var bool + * @var string */ - protected bool $statusDefault = true; + protected string $action = ''; /** - * @var array + * @var string */ - private array $roles = [ - 'any' => true - ]; + protected string $message = 'Authorization Error'; /** - * @var string + * @param string $action */ - protected string $message = 'Authorization Error'; + public function __construct(string $action) + { + $this->action = $action; + } /** * Get Description. @@ -44,43 +43,36 @@ public function getDescription(): string return $this->message; } - /* - * Validation + /** + * Is valid. * * Returns true if valid or false if not. - */ - public function isValid(mixed $input): bool // any, CREATE + * + * @param mixed $permissions + * + * @return bool + */ + public function isValid($permissions): bool { - if (!($input instanceof Input)) { - $this->message = 'Invalid input provided'; - return false; - } - - /** - * @var Input $input - */ - - $permissions = $input->getPermissions(); - $action = $input->getAction(); - - if (!$this->status) { + if (!self::$status) { return true; } if (empty($permissions)) { - $this->message = 'No permissions provided for action \''.$action.'\''; + $this->message = 'No permissions provided for action \''.$this->action.'\''; return false; } $permission = '-'; foreach ($permissions as $permission) { - if (\array_key_exists($permission, $this->roles)) { + if (\array_key_exists($permission, self::$roles)) { return true; } } - $this->message = 'Missing "'.$action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + $this->message = 'Missing "'.$this->action.'" permission for role "'.$permission.'". Only "'.\json_encode(self::getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + return false; } @@ -88,9 +80,9 @@ public function isValid(mixed $input): bool // any, CREATE * @param string $role * @return void */ - public function addRole(string $role): void // user:meldiron, users, any + public static function setRole(string $role): void { - $this->roles[$role] = true; + self::$roles[$role] = true; } /** @@ -98,25 +90,25 @@ public function addRole(string $role): void // user:meldiron, users, any * * @return void */ - public function removeRole(string $role): void + public static function unsetRole(string $role): void { - unset($this->roles[$role]); + unset(self::$roles[$role]); } /** * @return array */ - public function getRoles(): array + public static function getRoles(): array { - return \array_keys($this->roles); + return \array_keys(self::$roles); } /** * @return void */ - public function cleanRoles(): void + public static function cleanRoles(): void { - $this->roles = []; + self::$roles = []; } /** @@ -124,53 +116,36 @@ public function cleanRoles(): void * * @return bool */ - public function isRole(string $role): bool + public static function isRole(string $role): bool { - return (\array_key_exists($role, $this->roles)); + return (\array_key_exists($role, self::$roles)); } /** - * Change default status. - * This will be used for the - * value set on the $this->reset() method - * @param bool $status - * @return void + * @var bool */ - public function setDefaultStatus(bool $status): void - { - $this->statusDefault = $status; - $this->status = $status; - } + public static bool $status = true; /** - * Change status - * - * @param bool $status - * @return void - */ - public function setStatus(bool $status): void - { - $this->status = $status; - } - - /** - * Get status + * Default value in case we need + * to reset Authorization status * - * @return bool + * @var bool */ - public function getStatus(): bool - { - return $this->status; - } + public static bool $statusDefault = true; /** - * Get default status + * Change default status. + * This will be used for the + * value set on the self::reset() method * - * @return bool + * @param bool $status + * @return void */ - public function getStatusDefault(): bool + public static function setDefaultStatus(bool $status): void { - return $this->statusDefault; + self::$statusDefault = $status; + self::$status = $status; } /** @@ -182,15 +157,15 @@ public function getStatusDefault(): bool * @param callable(): T $callback * @return T */ - public function skip(callable $callback): mixed + public static function skip(callable $callback): mixed { - $initialStatus = $this->status; - $this->disable(); + $initialStatus = self::$status; + self::disable(); try { return $callback(); } finally { - $this->status = $initialStatus; + self::$status = $initialStatus; } } @@ -199,9 +174,9 @@ public function skip(callable $callback): mixed * * @return void */ - public function enable(): void + public static function enable(): void { - $this->status = true; + self::$status = true; } /** @@ -209,9 +184,9 @@ public function enable(): void * * @return void */ - public function disable(): void + public static function disable(): void { - $this->status = false; + self::$status = false; } /** @@ -219,9 +194,9 @@ public function disable(): void * * @return void */ - public function reset(): void + public static function reset(): void { - $this->status = $this->statusDefault; + self::$status = self::$statusDefault; } /** diff --git a/src/Database/Validator/Authorization/Input.php b/src/Database/Validator/Authorization/Input.php deleted file mode 100644 index 4c2387097..000000000 --- a/src/Database/Validator/Authorization/Input.php +++ /dev/null @@ -1,49 +0,0 @@ -permissions = $permissions; - $this->action = $action; - } - - /** - * @param string[] $permissions - */ - public function setPermissions(array $permissions): self - { - $this->permissions = $permissions; - return $this; - } - - public function setAction(string $action): self - { - $this->action = $action; - return $this; - } - - /** - * @return string[] - */ - public function getPermissions(): array - { - return $this->permissions; - } - - public function getAction(): string - { - return $this->action; - } -} diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index 1d8c9dfd2..e8ffee5ff 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Http\Validator; +use Utopia\Validator; class Datetime extends Validator { @@ -33,7 +33,7 @@ class Datetime extends Validator */ public function __construct(bool $requireDateInFuture = false, string $precision = self::PRECISION_ANY, int $offset = 0) { - if ($offset < 0) { + if($offset < 0) { throw new \Exception('Offset must be a positive number.'); } @@ -50,13 +50,13 @@ public function getDescription(): string { $message = 'Value must be valid date'; - if ($this->offset > 0) { + if($this->offset > 0) { $message .= " at least " . $this->offset . " seconds in future"; - } elseif ($this->requireDateInFuture) { + } elseif($this->requireDateInFuture) { $message .= " in future"; } - if ($this->precision !== self::PRECISION_ANY) { + if($this->precision !== self::PRECISION_ANY) { $message .= " with " . $this->precision . " precision"; } @@ -84,9 +84,9 @@ public function isValid($value): bool return false; } - if ($this->offset !== 0) { + if($this->offset !== 0) { $diff = $date->getTimestamp() - $now->getTimestamp(); - if ($diff <= $this->offset) { + if($diff <= $this->offset) { return false; } } @@ -109,12 +109,12 @@ public function isValid($value): bool break; } - foreach ($denyConstants as $constant) { - if (\intval($date->format($constant)) !== 0) { + foreach($denyConstants as $constant) { + if(\intval($date->format($constant)) !== 0) { return false; } } - } catch (\Exception $e) { + } catch(\Exception $e) { return false; } diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index d7f1beba4..b24e39f73 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -5,7 +5,7 @@ use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; -use Utopia\Http\Validator; +use Utopia\Validator; class Index extends Validator { @@ -126,30 +126,30 @@ public function checkArrayIndex(Document $index): bool foreach ($attributes as $attributePosition => $attributeName) { $attribute = $this->attributes[\strtolower($attributeName)] ?? new Document(); - if ($attribute->getAttribute('array', false)) { + if($attribute->getAttribute('array', false)) { // Database::INDEX_UNIQUE Is not allowed! since mariaDB VS MySQL makes the unique Different on values - if ($index->getAttribute('type') != Database::INDEX_KEY) { + if($index->getAttribute('type') != Database::INDEX_KEY) { $this->message = '"' . ucfirst($index->getAttribute('type')) . '" index is forbidden on array attributes'; return false; } - if (empty($lengths[$attributePosition])) { + if(empty($lengths[$attributePosition])) { $this->message = 'Index length for array not specified'; return false; } $arrayAttributes[] = $attribute->getAttribute('key', ''); - if (count($arrayAttributes) > 1) { + if(count($arrayAttributes) > 1) { $this->message = 'An index may only contain one array attribute'; return false; } $direction = $orders[$attributePosition] ?? ''; - if (!empty($direction)) { + if(!empty($direction)) { $this->message = 'Invalid index order "' . $direction . '" on array attribute "'. $attribute->getAttribute('key', '') .'"'; return false; } - } elseif ($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { + } elseif($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { $this->message = 'Cannot set a length on "'. $attribute->getAttribute('type') . '" attributes'; return false; } @@ -188,7 +188,7 @@ public function checkIndexLength(Document $index): bool break; } - if ($attribute->getAttribute('array', false)) { + if($attribute->getAttribute('array', false)) { $attributeSize = Database::ARRAY_INDEX_LENGTH; $indexLength = Database::ARRAY_INDEX_LENGTH; } diff --git a/src/Database/Validator/Key.php b/src/Database/Validator/Key.php index 74f175f59..ad1c5df4e 100644 --- a/src/Database/Validator/Key.php +++ b/src/Database/Validator/Key.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Http\Validator; +use Utopia\Validator; class Key extends Validator { diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index cc5ae3f5a..2e4aac71a 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -4,7 +4,7 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Query\Base; -use Utopia\Http\Validator; +use Utopia\Validator; class Queries extends Validator { @@ -71,8 +71,8 @@ public function isValid($value): bool } } - if ($query->isNested()) { - if (!self::isValid($query->getValues())) { + if($query->isNested()) { + if(!self::isValid($query->getValues())) { return false; } } diff --git a/src/Database/Validator/Query/Base.php b/src/Database/Validator/Query/Base.php index fa96b5a69..a37fdd65a 100644 --- a/src/Database/Validator/Query/Base.php +++ b/src/Database/Validator/Query/Base.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator\Query; -use Utopia\Http\Validator; +use Utopia\Validator; abstract class Base extends Validator { diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index 697c87ee9..635fa4732 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -6,10 +6,10 @@ use Utopia\Database\Document; use Utopia\Database\Query; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Http\Validator\Boolean; -use Utopia\Http\Validator\FloatValidator; -use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Text; +use Utopia\Validator\Boolean; +use Utopia\Validator\FloatValidator; +use Utopia\Validator\Integer; +use Utopia\Validator\Text; class Filter extends Base { @@ -131,29 +131,29 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s } } - if ($attributeSchema['type'] === 'relationship') { + if($attributeSchema['type'] === 'relationship') { /** * We can not disable relationship query since we have logic that use it, * so instead we validate against the relation type */ $options = $attributeSchema['options']; - if ($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { + if($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if ($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { + if($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if ($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { + if($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if ($options['relationType'] === Database::RELATION_MANY_TO_MANY) { + if($options['relationType'] === Database::RELATION_MANY_TO_MANY) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } @@ -161,7 +161,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s $array = $attributeSchema['array'] ?? false; - if ( + if( !$array && $method === Query::TYPE_CONTAINS && $attributeSchema['type'] !== Database::VAR_STRING @@ -170,7 +170,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s return false; } - if ( + if( $array && !in_array($method, [Query::TYPE_CONTAINS, Query::TYPE_IS_NULL, Query::TYPE_IS_NOT_NULL]) ) { @@ -253,12 +253,12 @@ public function isValid($value): bool case Query::TYPE_AND: $filters = Query::groupByType($value->getValues())['filters']; - if (count($value->getValues()) !== count($filters)) { + if(count($value->getValues()) !== count($filters)) { $this->message = \ucfirst($method) . ' queries can only contain filter queries'; return false; } - if (count($filters) < 2) { + if(count($filters) < 2) { $this->message = \ucfirst($method) . ' queries require at least two queries'; return false; } diff --git a/src/Database/Validator/Query/Limit.php b/src/Database/Validator/Query/Limit.php index affe0bc89..facc266d7 100644 --- a/src/Database/Validator/Query/Limit.php +++ b/src/Database/Validator/Query/Limit.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Numeric; +use Utopia\Validator\Range; class Limit extends Base { diff --git a/src/Database/Validator/Query/Offset.php b/src/Database/Validator/Query/Offset.php index 6fc7c9564..8d59be4d0 100644 --- a/src/Database/Validator/Query/Offset.php +++ b/src/Database/Validator/Query/Offset.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Numeric; +use Utopia\Validator\Range; class Offset extends Base { diff --git a/src/Database/Validator/Roles.php b/src/Database/Validator/Roles.php index 2db3e8cc7..0306118e7 100644 --- a/src/Database/Validator/Roles.php +++ b/src/Database/Validator/Roles.php @@ -3,7 +3,7 @@ namespace Utopia\Database\Validator; use Utopia\Database\Helpers\Role; -use Utopia\Http\Validator; +use Utopia\Validator; class Roles extends Validator { diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 20388a94c..46b1edafd 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -8,12 +8,12 @@ use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Http\Validator; -use Utopia\Http\Validator\Boolean; -use Utopia\Http\Validator\FloatValidator; -use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Range; -use Utopia\Http\Validator\Text; +use Utopia\Validator; +use Utopia\Validator\Boolean; +use Utopia\Validator\FloatValidator; +use Utopia\Validator\Integer; +use Utopia\Validator\Range; +use Utopia\Validator\Text; class Structure extends Validator { @@ -126,7 +126,7 @@ public static function getFormats(): array * Stores a callback and required params to create Validator * * @param string $name - * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Http\Validator + * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Validator * @param string $type Primitive data type for validation */ public static function addFormat(string $name, Closure $callback, string $type): void @@ -311,7 +311,7 @@ protected function checkForInvalidAttributeValues(array $structure, array $keys) continue; } - if ($type === Database::VAR_RELATIONSHIP) { + if($type === Database::VAR_RELATIONSHIP) { continue; } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index f3c4b7b79..d9dd2ff77 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -28,7 +28,7 @@ use Utopia\Database\Validator\Datetime as DatetimeValidator; use Utopia\Database\Validator\Index; use Utopia\Database\Validator\Structure; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Range; ini_set('memory_limit', '2048M'); @@ -36,15 +36,10 @@ abstract class Base extends TestCase { protected static string $namespace; - /** - * @var Authorization - */ - protected static ?Authorization $authorization = null; - /** * @return Database */ - abstract protected function getDatabase(): Database; + abstract protected static function getDatabase(): Database; /** * @return string @@ -53,42 +48,38 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - if (is_null(self::$authorization)) { - self::$authorization = new Authorization(); - } - - self::$authorization->addRole('any'); + Authorization::setRole('any'); } public function tearDown(): void { - self::$authorization->setDefaultStatus(true); + Authorization::setDefaultStatus(true); } protected string $testDatabase = 'utopiaTests'; public function testPing(): void { - $this->assertEquals(true, $this->getDatabase()->ping()); + $this->assertEquals(true, static::getDatabase()->ping()); } public function testCreateExistsDelete(): void { $schemaSupport = $this->getDatabase()->getAdapter()->getSupportForSchemas(); if (!$schemaSupport) { - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); + $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->create()); return; } - if (!$this->getDatabase()->exists($this->testDatabase)) { - $this->assertEquals(true, $this->getDatabase()->create()); + if (!static::getDatabase()->exists($this->testDatabase)) { + $this->assertEquals(true, static::getDatabase()->create()); } - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); - $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase)); - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); + $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase)); + $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->create()); } public function testUpdateDeleteCollectionNotFound(): void @@ -110,163 +101,163 @@ public function testUpdateDeleteCollectionNotFound(): void public function testDeleteRelatedCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createCollection('c2'); + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createCollection('c2'); // ONE_TO_ONE - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // ONE_TO_MANY - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // RELATION_MANY_TO_ONE - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); } @@ -727,27 +718,27 @@ public function testVirtualRelationsAttributes(): void public function testPreserveDatesUpdate(): void { - self::$authorization->disable(); + Authorization::disable(); - $this->getDatabase()->setPreserveDates(true); + static::getDatabase()->setPreserveDates(true); - $this->getDatabase()->createCollection('preserve_update_dates'); + static::getDatabase()->createCollection('preserve_update_dates'); - $this->getDatabase()->createAttribute('preserve_update_dates', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('preserve_update_dates', 'attr1', Database::VAR_STRING, 10, false); - $doc1 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc1 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc1', '$permissions' => [], 'attr1' => 'value1', ])); - $doc2 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc2 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc2', '$permissions' => [], 'attr1' => 'value2', ])); - $doc3 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc3 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc3', '$permissions' => [], 'attr1' => 'value3', @@ -756,8 +747,8 @@ public function testPreserveDatesUpdate(): void $newDate = '2000-01-01T10:00:00.000+00:00'; $doc1->setAttribute('$updatedAt', $newDate); - $this->getDatabase()->updateDocument('preserve_update_dates', 'doc1', $doc1); - $doc1 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc1'); + static::getDatabase()->updateDocument('preserve_update_dates', 'doc1', $doc1); + $doc1 = static::getDatabase()->getDocument('preserve_update_dates', 'doc1'); $this->assertEquals($newDate, $doc1->getAttribute('$updatedAt')); $this->getDatabase()->updateDocuments( @@ -773,38 +764,38 @@ public function testPreserveDatesUpdate(): void ] ); - $doc2 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc2'); - $doc3 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc3'); + $doc2 = static::getDatabase()->getDocument('preserve_update_dates', 'doc2'); + $doc3 = static::getDatabase()->getDocument('preserve_update_dates', 'doc3'); $this->assertEquals($newDate, $doc2->getAttribute('$updatedAt')); $this->assertEquals($newDate, $doc3->getAttribute('$updatedAt')); - $this->getDatabase()->deleteCollection('preserve_update_dates'); + static::getDatabase()->deleteCollection('preserve_update_dates'); - $this->getDatabase()->setPreserveDates(false); + static::getDatabase()->setPreserveDates(false); - self::$authorization->reset(); + Authorization::reset(); } public function testPreserveDatesCreate(): void { - self::$authorization->disable(); + Authorization::disable(); - $this->getDatabase()->setPreserveDates(true); + static::getDatabase()->setPreserveDates(true); - $this->getDatabase()->createCollection('preserve_create_dates'); + static::getDatabase()->createCollection('preserve_create_dates'); - $this->getDatabase()->createAttribute('preserve_create_dates', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('preserve_create_dates', 'attr1', Database::VAR_STRING, 10, false); $date = '2000-01-01T10:00:00.000+00:00'; - $this->getDatabase()->createDocument('preserve_create_dates', new Document([ + static::getDatabase()->createDocument('preserve_create_dates', new Document([ '$id' => 'doc1', '$permissions' => [], 'attr1' => 'value1', '$createdAt' => $date ])); - $this->getDatabase()->createDocuments('preserve_create_dates', [ + static::getDatabase()->createDocuments('preserve_create_dates', [ new Document([ '$id' => 'doc2', '$permissions' => [], @@ -819,18 +810,18 @@ public function testPreserveDatesCreate(): void ]), ], 2); - $doc1 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc1'); - $doc2 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc2'); - $doc3 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc3'); + $doc1 = static::getDatabase()->getDocument('preserve_create_dates', 'doc1'); + $doc2 = static::getDatabase()->getDocument('preserve_create_dates', 'doc2'); + $doc3 = static::getDatabase()->getDocument('preserve_create_dates', 'doc3'); $this->assertEquals($date, $doc1->getAttribute('$createdAt')); $this->assertEquals($date, $doc2->getAttribute('$createdAt')); $this->assertEquals($date, $doc3->getAttribute('$createdAt')); - $this->getDatabase()->deleteCollection('preserve_create_dates'); + static::getDatabase()->deleteCollection('preserve_create_dates'); - $this->getDatabase()->setPreserveDates(false); + static::getDatabase()->setPreserveDates(false); - self::$authorization->reset(); + Authorization::reset(); } /** @@ -880,14 +871,14 @@ public function testIndexValidation(): void 'indexes' => $indexes ]); - $validator = new Index($attributes, $this->getDatabase()->getAdapter()->getMaxIndexLength()); + $validator = new Index($attributes, static::getDatabase()->getAdapter()->getMaxIndexLength()); $errorMessage = 'Index length 701 is larger than the size for title1: 700"'; $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes, [ + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes, [ Permission::read(Role::any()), Permission::create(Role::any()), ]); @@ -908,13 +899,13 @@ public function testIndexValidation(): void $collection->setAttribute('indexes', $indexes); - if ($this->getDatabase()->getAdapter()->getMaxIndexLength() > 0) { - $errorMessage = 'Index length is longer than the maximum: ' . $this->getDatabase()->getAdapter()->getMaxIndexLength(); + if (static::getDatabase()->getAdapter()->getMaxIndexLength() > 0) { + $errorMessage = 'Index length is longer than the maximum: ' . static::getDatabase()->getAdapter()->getMaxIndexLength(); $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -950,13 +941,13 @@ public function testIndexValidation(): void 'indexes' => $indexes ]); - $validator = new Index($attributes, $this->getDatabase()->getAdapter()->getMaxIndexLength()); + $validator = new Index($attributes, static::getDatabase()->getAdapter()->getMaxIndexLength()); $errorMessage = 'Attribute "integer" cannot be part of a FULLTEXT index, must be of type string'; $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -965,9 +956,9 @@ public function testIndexValidation(): void public function testCreatedAtUpdatedAt(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('created_at')); - $this->getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); - $document = $this->getDatabase()->createDocument('created_at', new Document([ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('created_at')); + static::getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); + $document = static::getDatabase()->createDocument('created_at', new Document([ '$id' => ID::custom('uid123'), '$permissions' => [ @@ -994,7 +985,7 @@ public function testQueryTimeout(): void $this->assertEquals(true, static::getDatabase()->createAttribute('global-timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); for ($i = 0 ; $i <= 20 ; $i++) { - $this->getDatabase()->createDocument('global-timeouts', new Document([ + static::getDatabase()->createDocument('global-timeouts', new Document([ 'longtext' => file_get_contents(__DIR__ . '/../../resources/longtext.txt'), '$permissions' => [ Permission::read(Role::any()), @@ -1007,11 +998,11 @@ public function testQueryTimeout(): void static::getDatabase()->setTimeout(1); try { - $this->getDatabase()->find('global-timeouts', [ + static::getDatabase()->find('global-timeouts', [ Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); - } catch (TimeoutException $ex) { + } catch(TimeoutException $ex) { static::getDatabase()->clearTimeout(); static::getDatabase()->deleteCollection('global-timeouts'); } @@ -1022,34 +1013,34 @@ public function testQueryTimeout(): void */ public function testCreateListExistsDeleteCollection(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors', permissions: [ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), ])); - $this->assertCount(1, $this->getDatabase()->listCollections()); - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertCount(1, static::getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors')); // Collection names should not be unique - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors2', permissions: [ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors2', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), ])); - $this->assertCount(2, $this->getDatabase()->listCollections()); - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors2')); - $collection = $this->getDatabase()->getCollection('actors2'); + $this->assertCount(2, static::getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors2')); + $collection = static::getDatabase()->getCollection('actors2'); $collection->setAttribute('name', 'actors'); // change name to one that exists - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->updateDocument( + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->updateDocument( $collection->getCollection(), $collection->getId(), $collection )); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors2')); // Delete collection when finished - $this->assertCount(1, $this->getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->deleteCollection('actors2')); // Delete collection when finished + $this->assertCount(1, static::getDatabase()->listCollections()); - $this->assertEquals(false, $this->getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors')); - $this->assertEquals(true, $this->getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertEquals(false, static::getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(true, static::getDatabase()->deleteCollection('actors')); + $this->assertEquals(true, static::getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase, 'actors')); } public function testSizeCollection(): void @@ -1145,24 +1136,24 @@ public function testSizeCollectionOnDisk(): void public function testSizeFullText(): void { // SQLite does not support fulltext indexes - if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('fullTextSizeTest'); + static::getDatabase()->createCollection('fullTextSizeTest'); $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); - $this->getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); + static::getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 10; for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->createDocument('fullTextSizeTest', new Document([ + static::getDatabase()->createDocument('fullTextSizeTest', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, @@ -1173,7 +1164,7 @@ public function testSizeFullText(): void $this->assertGreaterThan($size1, $size2); - $this->getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); + static::getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); $size3 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); @@ -1182,12 +1173,12 @@ public function testSizeFullText(): void public function testPurgeCollectionCache(): void { - $this->getDatabase()->createCollection('redis'); + static::getDatabase()->createCollection('redis'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'name', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'name', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); - $this->getDatabase()->createDocument('redis', new Document([ + static::getDatabase()->createDocument('redis', new Document([ '$id' => 'doc1', 'name' => 'Richard', 'age' => 15, @@ -1196,106 +1187,106 @@ public function testPurgeCollectionCache(): void ] ])); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertEquals(15, $document->getAttribute('age')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('redis', 'age')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('redis', 'age')); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertArrayNotHasKey('age', $document); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertArrayHasKey('age', $document); } public function testCreateDeleteAttribute(): void { - $this->getDatabase()->createCollection('attributes'); + static::getDatabase()->createCollection('attributes'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(8, $collection->getAttribute('attributes')); $this->assertCount(3, $collection->getAttribute('indexes')); // Array - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(12, $collection->getAttribute('attributes')); // Default values - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(17, $collection->getAttribute('attributes')); // Delete - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string1')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string2')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string3')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string4')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'bigint')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean')); - - $collection = $this->getDatabase()->getCollection('attributes'); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string1')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string2')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string3')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string4')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'bigint')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean')); + + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(9, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // Delete Array - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_list')); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(5, $collection->getAttribute('attributes')); // Delete default - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'datetime_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'datetime_default')); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(0, $collection->getAttribute('attributes')); // Test for custom chars in ID - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); // Test non-shared tables duplicates throw duplicate static::getDatabase()->createAttribute('attributes', 'duplicate', Database::VAR_STRING, 128, true); @@ -1338,7 +1329,7 @@ public function invalidDefaultValues(): array public function testInvalidDefaultValues(string $type, mixed $default): void { $this->expectException(\Exception::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); } /** @@ -1346,18 +1337,19 @@ public function testInvalidDefaultValues(string $type, mixed $default): void */ public function testAttributeCaseInsensitivity(): void { + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'caseSensitive', Database::VAR_STRING, 128, true)); $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); } public function testAttributeKeyWithSymbols(): void { - $this->getDatabase()->createCollection('attributesWithKeys'); + static::getDatabase()->createCollection('attributesWithKeys'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); - $document = $this->getDatabase()->createDocument('attributesWithKeys', new Document([ + $document = static::getDatabase()->createDocument('attributesWithKeys', new Document([ 'key_with.sym$bols' => 'value', '$permissions' => [ Permission::read(Role::any()), @@ -1366,7 +1358,7 @@ public function testAttributeKeyWithSymbols(): void $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); - $document = $this->getDatabase()->getDocument('attributesWithKeys', $document->getId()); + $document = static::getDatabase()->getDocument('attributesWithKeys', $document->getId()); $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); } @@ -1374,7 +1366,7 @@ public function testAttributeKeyWithSymbols(): void public function testCollectionNotFound(): void { try { - $this->getDatabase()->find('not_exist', []); + static::getDatabase()->find('not_exist', []); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Collection not found', $e->getMessage()); @@ -1383,9 +1375,9 @@ public function testCollectionNotFound(): void public function testAttributeNamesWithDots(): void { - $this->getDatabase()->createCollection('dots.parent'); + static::getDatabase()->createCollection('dots.parent'); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: 'dots.parent', id: 'dots.name', type: Database::VAR_STRING, @@ -1393,14 +1385,14 @@ public function testAttributeNamesWithDots(): void required: false )); - $document = $this->getDatabase()->find('dots.parent', [ + $document = static::getDatabase()->find('dots.parent', [ Query::select(['dots.name']), ]); $this->assertEmpty($document); - $this->getDatabase()->createCollection('dots'); + static::getDatabase()->createCollection('dots'); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: 'dots', id: 'name', type: Database::VAR_STRING, @@ -1408,13 +1400,13 @@ public function testAttributeNamesWithDots(): void required: false )); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'dots.parent', relatedCollection: 'dots', type: Database::RELATION_ONE_TO_ONE ); - $this->getDatabase()->createDocument('dots.parent', new Document([ + static::getDatabase()->createDocument('dots.parent', new Document([ '$id' => ID::custom('father'), 'dots.name' => 'Bill clinton', '$permissions' => [ @@ -1434,7 +1426,7 @@ public function testAttributeNamesWithDots(): void ] ])); - $documents = $this->getDatabase()->find('dots.parent', [ + $documents = static::getDatabase()->find('dots.parent', [ Query::select(['*']), ]); @@ -1446,9 +1438,9 @@ public function testAttributeNamesWithDots(): void */ public function testIndexCaseInsensitivity(): void { - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); } /** @@ -1458,7 +1450,7 @@ public function testIndexCaseInsensitivity(): void */ public function testCleanupAttributeTests(): void { - $this->getDatabase()->deleteCollection('attributes'); + static::getDatabase()->deleteCollection('attributes'); $this->assertEquals(1, 1); } @@ -1469,39 +1461,39 @@ public function testCleanupAttributeTests(): void public function testUnknownFormat(): void { $this->expectException(\Exception::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); } public function testCreateDeleteIndex(): void { - $this->getDatabase()->createCollection('indexes'); + static::getDatabase()->createCollection('indexes'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); // Indexes - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); - - $collection = $this->getDatabase()->getCollection('indexes'); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); + + $collection = static::getDatabase()->getCollection('indexes'); $this->assertCount(6, $collection->getAttribute('indexes')); // Delete Indexes - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index1')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index2')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index3')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index4')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index5')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'order')); - - $collection = $this->getDatabase()->getCollection('indexes'); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index1')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index2')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index3')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index4')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index5')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'order')); + + $collection = static::getDatabase()->getCollection('indexes'); $this->assertCount(0, $collection->getAttribute('indexes')); // Test non-shared tables duplicates throw duplicate @@ -1572,7 +1564,7 @@ public function testCreateCollectionWithSchema(): void ]), ]; - $collection = $this->getDatabase()->createCollection('withSchema', $attributes, $indexes); + $collection = static::getDatabase()->createCollection('withSchema', $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals('withSchema', $collection->getId()); @@ -1595,10 +1587,10 @@ public function testCreateCollectionWithSchema(): void $this->assertEquals('index3', $collection->getAttribute('indexes')[2]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[2]['type']); - $this->getDatabase()->deleteCollection('withSchema'); + static::getDatabase()->deleteCollection('withSchema'); // Test collection with dash (+attribute +index) - $collection2 = $this->getDatabase()->createCollection('with-dash', [ + $collection2 = static::getDatabase()->createCollection('with-dash', [ new Document([ '$id' => ID::custom('attribute-one'), 'type' => Database::VAR_STRING, @@ -1628,7 +1620,7 @@ public function testCreateCollectionWithSchema(): void $this->assertCount(1, $collection2->getAttribute('indexes')); $this->assertEquals('index-one', $collection2->getAttribute('indexes')[0]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection2->getAttribute('indexes')[0]['type']); - $this->getDatabase()->deleteCollection('with-dash'); + static::getDatabase()->deleteCollection('with-dash'); } public function testCreateCollectionValidator(): void @@ -1727,7 +1719,7 @@ public function testCreateCollectionValidator(): void ]; foreach ($collections as $id) { - $collection = $this->getDatabase()->createCollection($id, $attributes, $indexes); + $collection = static::getDatabase()->createCollection($id, $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals($id, $collection->getId()); @@ -1754,27 +1746,27 @@ public function testCreateCollectionValidator(): void $this->assertEquals('index.4', $collection->getAttribute('indexes')[3]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[3]['type']); - $this->getDatabase()->deleteCollection($id); + static::getDatabase()->deleteCollection($id); } } public function testCreateDocument(): Document { - $this->getDatabase()->createCollection('documents'); - - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'integer_signed', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'integer_unsigned', Database::VAR_INTEGER, 4, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'bigint_signed', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'bigint_unsigned', Database::VAR_INTEGER, 9, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'float_signed', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'float_unsigned', Database::VAR_FLOAT, 0, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); - - $document = $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createCollection('documents'); + + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'integer_signed', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'integer_unsigned', Database::VAR_INTEGER, 4, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'bigint_signed', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'bigint_unsigned', Database::VAR_INTEGER, 9, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'float_signed', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'float_unsigned', Database::VAR_FLOAT, 0, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); + + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user(ID::custom('1'))), @@ -1825,7 +1817,7 @@ public function testCreateDocument(): Document $this->assertEquals('Works', $document->getAttribute('with-dash')); // Test create document with manual internal id - $manualIdDocument = $this->getDatabase()->createDocument('documents', new Document([ + $manualIdDocument = static::getDatabase()->createDocument('documents', new Document([ '$id' => '56000', '$internalId' => '56000', '$permissions' => [ @@ -1878,7 +1870,7 @@ public function testCreateDocument(): Document $this->assertEquals([], $manualIdDocument->getAttribute('empty')); $this->assertEquals('Works', $manualIdDocument->getAttribute('with-dash')); - $manualIdDocument = $this->getDatabase()->getDocument('documents', '56000'); + $manualIdDocument = static::getDatabase()->getDocument('documents', '56000'); $this->assertEquals('56000', $manualIdDocument->getInternalId()); $this->assertNotEmpty(true, $manualIdDocument->getId()); @@ -1917,7 +1909,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertStringContainsString('Invalid document structure: Attribute "float_unsigned" has invalid type. Value must be a valid range between 0 and', $e->getMessage()); } @@ -1936,7 +1928,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertEquals('Invalid document structure: Attribute "bigint_unsigned" has invalid type. Value must be a valid range between 0 and 9,223,372,036,854,775,807', $e->getMessage()); } @@ -1952,11 +1944,11 @@ public function testCreateDocuments(): array $count = 3; $collection = 'testCreateDocuments'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'bigint', Database::VAR_INTEGER, 8, true)); // Create an array of documents with random attributes. Don't use the createDocument function $documents = []; @@ -1975,7 +1967,7 @@ public function testCreateDocuments(): array ]); } - $documents = $this->getDatabase()->createDocuments($collection, $documents, 3); + $documents = static::getDatabase()->createDocuments($collection, $documents, 3); $this->assertEquals($count, count($documents)); @@ -1994,15 +1986,15 @@ public function testCreateDocuments(): array public function testRespectNulls(): Document { - $this->getDatabase()->createCollection('documents_nulls'); + static::getDatabase()->createCollection('documents_nulls'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); - $document = $this->getDatabase()->createDocument('documents_nulls', new Document([ + $document = static::getDatabase()->createDocument('documents_nulls', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2030,16 +2022,16 @@ public function testRespectNulls(): Document public function testCreateDocumentDefaults(): void { - $this->getDatabase()->createCollection('defaults'); + static::getDatabase()->createCollection('defaults'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $document = $this->getDatabase()->createDocument('defaults', new Document([ + $document = static::getDatabase()->createDocument('defaults', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -2048,7 +2040,7 @@ public function testCreateDocumentDefaults(): void ], ])); - $document2 = $this->getDatabase()->getDocument('defaults', $document->getId()); + $document2 = static::getDatabase()->getDocument('defaults', $document->getId()); $this->assertCount(4, $document2->getPermissions()); $this->assertEquals('read("any")', $document2->getPermissions()[0]); $this->assertEquals('create("any")', $document2->getPermissions()[1]); @@ -2070,7 +2062,7 @@ public function testCreateDocumentDefaults(): void $this->assertEquals('2000-06-12T14:12:55.000+00:00', $document->getAttribute('datetime')); // cleanup collection - $this->getDatabase()->deleteCollection('defaults'); + static::getDatabase()->deleteCollection('defaults'); } /** @@ -2079,14 +2071,14 @@ public function testCreateDocumentDefaults(): void public function testIncreaseDecrease(): Document { $collection = 'increase_decrease'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); - $document = $this->getDatabase()->createDocument($collection, new Document([ + $document = static::getDatabase()->createDocument($collection, new Document([ 'increase' => 100, 'decrease' => 100, 'increase_float' => 100, @@ -2103,20 +2095,20 @@ public function testIncreaseDecrease(): Document $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase', 1, 101)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(101, $document->getAttribute('increase')); $this->assertNotEquals($updatedAt, $document->getUpdatedAt()); - $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(99, $document->getAttribute('decrease')); - $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(105.5, $document->getAttribute('increase_float')); - $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(104.4, $document->getAttribute('increase_float')); return $document; @@ -2128,7 +2120,7 @@ public function testIncreaseDecrease(): Document public function testIncreaseLimitMax(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); + $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); } /** @@ -2137,7 +2129,7 @@ public function testIncreaseLimitMax(Document $document): void public function testDecreaseLimitMin(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, $this->getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); + $this->assertEquals(false, static::getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); } /** @@ -2146,7 +2138,7 @@ public function testDecreaseLimitMin(Document $document): void public function testIncreaseTextAttribute(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); + $this->assertEquals(false, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); } /** @@ -2154,7 +2146,7 @@ public function testIncreaseTextAttribute(Document $document): void */ public function testGetDocument(Document $document): Document { - $document = $this->getDatabase()->getDocument('documents', $document->getId()); + $document = static::getDatabase()->getDocument('documents', $document->getId()); $this->assertNotEmpty(true, $document->getId()); $this->assertIsString($document->getAttribute('string')); @@ -2181,7 +2173,7 @@ public function testGetDocumentSelect(Document $document): Document { $documentId = $document->getId(); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed']), ]); @@ -2202,7 +2194,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$id']), ]); @@ -2213,7 +2205,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$permissions']), ]); @@ -2224,7 +2216,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$internalId']), ]); @@ -2235,7 +2227,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$collection']), ]); @@ -2246,7 +2238,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$createdAt']), ]); @@ -2257,7 +2249,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$updatedAt']), ]); @@ -2284,7 +2276,7 @@ public function testFulltextIndexWithInteger(): void $this->expectExceptionMessage('Attribute "integer_signed" cannot be part of a FULLTEXT index, must be of type string'); } - $this->getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer_signed']); + static::getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer_signed']); } public function testListDocumentSearch(): void @@ -2295,8 +2287,8 @@ public function testListDocumentSearch(): void return; } - $this->getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); - $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); + static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -2318,7 +2310,7 @@ public function testListDocumentSearch(): void /** * Allow reserved keywords for search */ - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '*test+alias@email-provider.com'), ]); @@ -2327,7 +2319,7 @@ public function testListDocumentSearch(): void public function testEmptyTenant(): void { - if (static::getDatabase()->getAdapter()->getSharedTables()) { + if(static::getDatabase()->getAdapter()->getSharedTables()) { $this->expectNotToPerformAssertions(); return; } @@ -2358,17 +2350,17 @@ public function testEmptySearch(): void return; } - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', ''), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '*'), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '<>'), ]); $this->assertEquals(0, count($documents)); @@ -2453,6 +2445,53 @@ public function testUpdateDocument(Document $document): Document return $document; } + /** + * @depends testCreateDocuments + * @param array $documents + */ + public function testUpdateDocuments(array $documents): void + { + $collection = 'testCreateDocuments'; + + foreach ($documents as $document) { + $document + ->setAttribute('string', 'text📝 updated') + ->setAttribute('integer', 6) + ->setAttribute('$permissions', [ + Permission::read(Role::users()), + Permission::create(Role::users()), + Permission::update(Role::users()), + Permission::delete(Role::users()), + ]); + } + + $documents = static::getDatabase()->updateDocuments( + $collection, + $documents, + \count($documents) + ); + + foreach ($documents as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + $this->assertEquals(6, $document->getAttribute('integer')); + } + + $documents = static::getDatabase()->find($collection, [ + Query::limit(\count($documents)) + ]); + + foreach ($documents as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + $this->assertEquals(6, $document->getAttribute('integer')); + $this->assertEquals([ + Permission::read(Role::users()), + Permission::create(Role::users()), + Permission::update(Role::users()), + Permission::delete(Role::users()), + ], $document->getAttribute('$permissions')); + } + } + /** * @depends testUpdateDocument */ @@ -2471,7 +2510,7 @@ public function testUpdateDocumentConflict(Document $document): void return $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertTrue($e instanceof ConflictException); $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); } @@ -2534,9 +2573,9 @@ public function testDeleteDocument(Document $document): void */ public function testArrayAttribute(): void { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); - $database = $this->getDatabase(); + $database = static::getDatabase(); $collection = 'json'; $permissions = [Permission::read(Role::any())]; @@ -2612,7 +2651,7 @@ public function testArrayAttribute(): void try { $database->createDocument($collection, new Document([])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid document structure: Missing required attribute "booleans"', $e->getMessage()); } @@ -2632,7 +2671,7 @@ public function testArrayAttribute(): void 'short' => ['More than 5 size'], ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "short[\'0\']" has invalid type. Value must be a valid string and no longer than 5 chars', $e->getMessage()); } @@ -2641,7 +2680,7 @@ public function testArrayAttribute(): void 'names' => ['Joe', 100], ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "names[\'1\']" has invalid type. Value must be a valid string and no longer than 255 chars', $e->getMessage()); } @@ -2650,7 +2689,7 @@ public function testArrayAttribute(): void 'age' => 1.5, ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid integer', $e->getMessage()); } @@ -2659,7 +2698,7 @@ public function testArrayAttribute(): void 'age' => -100, ])); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid range between 0 and 2,147,483,647', $e->getMessage()); } @@ -2688,7 +2727,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->assertEquals('"Fulltext" index is forbidden on array attributes', $e->getMessage()); } else { @@ -2699,7 +2738,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_KEY, ['numbers', 'names'], [100,100]); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('An index may only contain one array attribute', $e->getMessage()); } @@ -2720,7 +2759,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx_numbers', Database::INDEX_KEY, ['tv_show', 'numbers'], [], []); // [700, 255] $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Index length is longer than the maximum: 768', $e->getMessage()); } } @@ -2731,7 +2770,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx4', Database::INDEX_KEY, ['age', 'names'], [10, 255], []); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Cannot set a length on "integer" attributes', $e->getMessage()); } @@ -2744,7 +2783,7 @@ public function testArrayAttribute(): void Query::equal('names', ['Joe']), ]); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid query: Cannot query equal on attribute "names" because it is an array.', $e->getMessage()); } @@ -2753,7 +2792,7 @@ public function testArrayAttribute(): void Query::contains('age', [10]) ]); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "age" because it is not an array or string.', $e->getMessage()); } @@ -2795,23 +2834,23 @@ public function testArrayAttribute(): void */ public function testFind(): array { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); - $this->getDatabase()->createCollection('movies', permissions: [ + static::getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ]); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'genres', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'genres', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); - $document = $this->getDatabase()->createDocument('movies', new Document([ + $document = static::getDatabase()->createDocument('movies', new Document([ '$id' => ID::custom('frozen'), '$permissions' => [ Permission::read(Role::any()), @@ -2836,7 +2875,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2860,7 +2899,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2884,7 +2923,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2908,7 +2947,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2932,7 +2971,7 @@ public function testFind(): array 'with-dash' => 'Works3' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::user('x')), Permission::create(Role::any()), @@ -2962,7 +3001,7 @@ public function testFind(): array public function testFindBasicChecks(): void { - $documents = $this->getDatabase()->find('movies'); + $documents = static::getDatabase()->find('movies'); $movieDocuments = $documents; $this->assertEquals(5, count($documents)); @@ -2995,13 +3034,13 @@ public function testFindBasicChecks(): void /** * Check $id: Notice, this orders ID names alphabetically, not by internal numeric ID */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('$id'), ]); $this->assertEquals($lastDocumentId, $documents[0]->getId()); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc('$id'), @@ -3011,13 +3050,13 @@ public function testFindBasicChecks(): void /** * Check internal numeric ID sorting */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); $this->assertEquals($movieDocuments[\count($movieDocuments) - 1]->getId(), $documents[0]->getId()); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc(''), @@ -3030,8 +3069,8 @@ public function testFindCheckPermissions(): void /** * Check Permissions */ - self::$authorization->addRole('user:x'); - $documents = $this->getDatabase()->find('movies'); + Authorization::setRole('user:x'); + $documents = static::getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); } @@ -3041,13 +3080,13 @@ public function testFindCheckInteger(): void /** * Query with dash attribute */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('with-dash', ['Works']), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('with-dash', ['Works2', 'Works3']), ]); @@ -3056,7 +3095,7 @@ public function testFindCheckInteger(): void /** * Check an Integer condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('year', [2019]), ]); @@ -3070,7 +3109,7 @@ public function testFindBoolean(): void /** * Boolean condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('active', [true]), ]); @@ -3082,7 +3121,7 @@ public function testFindStringQueryEqual(): void /** * String condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD']), ]); @@ -3100,7 +3139,7 @@ public function testFindNotEqual(): void /** * Not Equal query */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::notEqual('director', 'TBD'), ]); @@ -3122,22 +3161,22 @@ public function testFindNotEqual(): void public function testFindBetween(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('price', 25.94, 25.99), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('price', 30, 35), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('$createdAt', '1975-12-06', '2050-12-06'), ]); $this->assertEquals(6, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('$updatedAt', '1975-12-06T07:08:49.733+02:00', '2050-02-05T10:15:21.825+00:00'), ]); $this->assertEquals(6, count($documents)); @@ -3148,7 +3187,7 @@ public function testFindFloat(): void /** * Float condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::lessThan('price', 26.00), Query::greaterThan('price', 25.98), ]); @@ -3163,7 +3202,7 @@ public function testFindContains(): void return; } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['comics']) ]); @@ -3172,24 +3211,24 @@ public function testFindContains(): void /** * Array contains OR condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['comics', 'kids']), ]); $this->assertEquals(4, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['non-existent']), ]); $this->assertEquals(0, count($documents)); try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::contains('price', [10.5]), ]); $this->fail('Failed to throw exception'); - } catch (Throwable $e) { + } catch(Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "price" because it is not an array or string.', $e->getMessage()); $this->assertTrue($e instanceof DatabaseException); } @@ -3201,10 +3240,10 @@ public function testFindFulltext(): void * Fulltext search */ if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { - $success = $this->getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); + $success = static::getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); $this->assertEquals(true, $success); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::search('name', 'captain'), ]); @@ -3218,7 +3257,7 @@ public function testFindFulltext(): void // TODO: I think this needs a changes? how do we distinguish between regular full text and wildcard? if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildCardIndex()) { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::search('name', 'cap'), ]); @@ -3231,62 +3270,62 @@ public function testFindFulltext(): void public function testFindFulltextSpecialChars(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } $collection = 'full_text'; - $this->getDatabase()->createCollection($collection, permissions: [ + static::getDatabase()->createCollection($collection, permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ]); - $this->assertTrue($this->getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); - $this->assertTrue($this->getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); + $this->assertTrue(static::getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); + $this->assertTrue(static::getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'Alf: chapter_4@nasa.com' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'chapter_4'), ]); $this->assertEquals(1, count($documents)); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'al@ba.io +-*)(<>~' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'al@ba.io'), // === al ba io* ]); - if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { + if (static::getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { $this->assertEquals(0, count($documents)); } else { $this->assertEquals(1, count($documents)); } - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald duck' ])); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald trump' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'donald trump'), Query::orderAsc('ft'), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', '"donald trump"'), // Exact match ]); @@ -3298,7 +3337,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD']), Query::equal('year', [2026]), ]); @@ -3308,7 +3347,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions and OR values */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('name', ['Frozen II', 'Captain Marvel']), ]); @@ -3322,7 +3361,7 @@ public function testFindByID(): void /** * $id condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('$id', ['frozen']), ]); @@ -3342,7 +3381,7 @@ public function testFindByInternalID(array $data): void /** * Test that internal ID queries are handled correctly */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('$internalId', [$data['$internalId']]), ]); @@ -3355,7 +3394,7 @@ public function testFindByInternalID(array $data): void */ public function testSelectInternalID(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['$internalId', '$id']), Query::orderAsc(''), Query::limit(1), @@ -3366,7 +3405,7 @@ public function testSelectInternalID(): void $this->assertArrayHasKey('$internalId', $document); $this->assertCount(2, $document); - $document = $this->getDatabase()->getDocument('movies', $document->getId(), [ + $document = static::getDatabase()->getDocument('movies', $document->getId(), [ Query::select(['$internalId']), ]); @@ -3379,7 +3418,7 @@ public function testFindOrderBy(): void /** * ORDER BY */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -3400,11 +3439,11 @@ public function testFindOrderByNatural(): void /** * ORDER BY natural */ - $base = array_reverse($this->getDatabase()->find('movies', [ + $base = array_reverse(static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), @@ -3424,7 +3463,7 @@ public function testFindOrderByMultipleAttributes(): void /** * ORDER BY - Multiple attributes */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -3445,12 +3484,12 @@ public function testFindOrderByCursorAfter(): void /** * ORDER BY - After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[1]) @@ -3459,7 +3498,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[3]) @@ -3468,7 +3507,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[4]) @@ -3476,7 +3515,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[5]) @@ -3490,12 +3529,12 @@ public function testFindOrderByCursorBefore(): void /** * ORDER BY - Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[5]) @@ -3504,7 +3543,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[3]) @@ -3513,7 +3552,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[2]) @@ -3522,7 +3561,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[1]) @@ -3530,7 +3569,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[0]) @@ -3543,12 +3582,12 @@ public function testFindOrderByAfterNaturalOrder(): void /** * ORDER BY - After by natural order */ - $movies = array_reverse($this->getDatabase()->find('movies', [ + $movies = array_reverse(static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3558,7 +3597,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3568,7 +3607,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3577,7 +3616,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3591,13 +3630,13 @@ public function testFindOrderByBeforeNaturalOrder(): void /** * ORDER BY - Before by natural order */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3607,7 +3646,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3617,7 +3656,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3627,7 +3666,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3636,7 +3675,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3650,13 +3689,13 @@ public function testFindOrderBySingleAttributeAfter(): void /** * ORDER BY - Single Attribute After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3667,7 +3706,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3677,7 +3716,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3686,7 +3725,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3700,13 +3739,13 @@ public function testFindOrderBySingleAttributeBefore(): void /** * ORDER BY - Single Attribute Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3716,7 +3755,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3726,7 +3765,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3736,7 +3775,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3745,7 +3784,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3759,14 +3798,14 @@ public function testFindOrderByMultipleAttributeAfter(): void /** * ORDER BY - Multiple Attribute After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3777,7 +3816,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3788,7 +3827,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3798,7 +3837,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3813,14 +3852,14 @@ public function testFindOrderByMultipleAttributeBefore(): void /** * ORDER BY - Multiple Attribute Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3832,7 +3871,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3843,7 +3882,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3854,7 +3893,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3864,7 +3903,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3879,12 +3918,12 @@ public function testFindOrderByAndCursor(): void /** * ORDER BY + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('price'), @@ -3899,12 +3938,12 @@ public function testFindOrderByIdAndCursor(): void /** * ORDER BY ID + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$id'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$id'), @@ -3919,13 +3958,13 @@ public function testFindOrderByCreateDateAndCursor(): void /** * ORDER BY CREATE DATE + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$createdAt'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$createdAt'), @@ -3940,12 +3979,12 @@ public function testFindOrderByUpdateDateAndCursor(): void /** * ORDER BY UPDATE DATE + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$updatedAt'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$updatedAt'), @@ -3960,7 +3999,7 @@ public function testFindLimit(): void /** * Limit */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(4), Query::offset(0), Query::orderAsc('name') @@ -3978,7 +4017,7 @@ public function testFindLimitAndOffset(): void /** * Limit + Offset */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(4), Query::offset(2), Query::orderAsc('name') @@ -3996,7 +4035,7 @@ public function testFindOrQueries(): void /** * Test that OR queries are handled correctly */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); @@ -4014,7 +4053,7 @@ public function testFindOrderByAfterException(): void ]); $this->expectException(Exception::class); - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($document) @@ -4028,9 +4067,9 @@ public function testFindEdgeCases(Document $document): void { $collection = 'edgeCases'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); $values = [ 'NormalString', @@ -4049,7 +4088,7 @@ public function testFindEdgeCases(Document $document): void ]; foreach ($values as $value) { - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -4063,7 +4102,7 @@ public function testFindEdgeCases(Document $document): void /** * Check Basic */ - $documents = $this->getDatabase()->find($collection); + $documents = static::getDatabase()->find($collection); $this->assertEquals(count($values), count($documents)); $this->assertNotEmpty($documents[0]->getId()); @@ -4077,7 +4116,7 @@ public function testFindEdgeCases(Document $document): void * Check `equals` query */ foreach ($values as $value) { - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::limit(25), Query::equal('value', [$value]) ]); @@ -4090,13 +4129,13 @@ public function testFindEdgeCases(Document $document): void public function testOrSingleQuery(): void { try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::or([ Query::equal('active', [true]) ]) ]); $this->fail('Failed to throw exception'); - } catch (Exception $e) { + } catch(Exception $e) { $this->assertEquals('Invalid query: Or queries require at least two queries', $e->getMessage()); } } @@ -4109,8 +4148,8 @@ public function testOrMultipleQueries(): void Query::equal('name', ['Frozen II']) ]) ]; - $this->assertCount(4, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(4, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(4, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(4, static::getDatabase()->count('movies', $queries)); $queries = [ Query::equal('active', [true]), @@ -4121,8 +4160,8 @@ public function testOrMultipleQueries(): void ]) ]; - $this->assertCount(3, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(3, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(3, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(3, static::getDatabase()->count('movies', $queries)); } public function testOrNested(): void @@ -4139,24 +4178,24 @@ public function testOrNested(): void ]) ]; - $documents = $this->getDatabase()->find('movies', $queries); + $documents = static::getDatabase()->find('movies', $queries); $this->assertCount(1, $documents); $this->assertArrayNotHasKey('name', $documents[0]); - $count = $this->getDatabase()->count('movies', $queries); + $count = static::getDatabase()->count('movies', $queries); $this->assertEquals(1, $count); } public function testAndSingleQuery(): void { try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::and([ Query::equal('active', [true]) ]) ]); $this->fail('Failed to throw exception'); - } catch (Exception $e) { + } catch(Exception $e) { $this->assertEquals('Invalid query: And queries require at least two queries', $e->getMessage()); } } @@ -4169,8 +4208,8 @@ public function testAndMultipleQueries(): void Query::equal('name', ['Frozen II']) ]) ]; - $this->assertCount(1, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(1, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(1, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(1, static::getDatabase()->count('movies', $queries)); } public function testAndNested(): void @@ -4185,16 +4224,16 @@ public function testAndNested(): void ]) ]; - $documents = $this->getDatabase()->find('movies', $queries); + $documents = static::getDatabase()->find('movies', $queries); $this->assertCount(3, $documents); - $count = $this->getDatabase()->count('movies', $queries); + $count = static::getDatabase()->count('movies', $queries); $this->assertEquals(3, $count); } public function testNestedIDQueries(): void { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); static::getDatabase()->createCollection('movies_nested_id', permissions: [ Permission::create(Role::any()), @@ -4258,7 +4297,7 @@ public function testNestedIDQueries(): void */ public function testFindOne(): void { - $document = $this->getDatabase()->findOne('movies', [ + $document = static::getDatabase()->findOne('movies', [ Query::offset(2), Query::orderAsc('name') ]); @@ -4266,7 +4305,7 @@ public function testFindOne(): void $this->assertFalse($document->isEmpty()); $this->assertEquals('Frozen', $document->getAttribute('name')); - $document = $this->getDatabase()->findOne('movies', [ + $document = static::getDatabase()->findOne('movies', [ Query::offset(10) ]); $this->assertTrue($document->isEmpty()); @@ -4274,7 +4313,7 @@ public function testFindOne(): void public function testFindNull(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::isNull('nullable'), ]); @@ -4283,7 +4322,7 @@ public function testFindNull(): void public function testFindNotNull(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::isNotNull('nullable'), ]); @@ -4292,18 +4331,18 @@ public function testFindNotNull(): void public function testFindStartsWith(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', 'Work'), ]); $this->assertEquals(2, count($documents)); if ($this->getDatabase()->getAdapter() instanceof SQL) { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', '%ork'), ]); } else { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', '.*ork'), ]); } @@ -4313,7 +4352,7 @@ public function testFindStartsWith(): void public function testFindStartsWithWords(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', 'Work in Progress'), ]); @@ -4322,7 +4361,7 @@ public function testFindStartsWithWords(): void public function testFindEndsWith(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::endsWith('name', 'Marvel'), ]); @@ -4331,7 +4370,7 @@ public function testFindEndsWith(): void public function testFindSelect(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year']) ]); @@ -4349,7 +4388,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$id']) ]); @@ -4367,7 +4406,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$internalId']) ]); @@ -4385,7 +4424,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$collection']) ]); @@ -4403,7 +4442,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$createdAt']) ]); @@ -4421,7 +4460,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$updatedAt']) ]); @@ -4439,7 +4478,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$permissions']) ]); @@ -4463,39 +4502,40 @@ public function testFindSelect(): void */ public function testCount(): void { - $count = $this->getDatabase()->count('movies'); + $count = static::getDatabase()->count('movies'); $this->assertEquals(6, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('year', [2019])]); + $count = static::getDatabase()->count('movies', [Query::equal('year', [2019])]); + $this->assertEquals(2, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); + $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); $this->assertEquals(2, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); + $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); - self::$authorization->removeRole('user:x'); - $count = $this->getDatabase()->count('movies'); + Authorization::unsetRole('user:x'); + $count = static::getDatabase()->count('movies'); $this->assertEquals(5, $count); - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies'); + Authorization::disable(); + $count = static::getDatabase()->count('movies'); $this->assertEquals(6, $count); - self::$authorization->reset(); + Authorization::reset(); - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies', [], 3); + Authorization::disable(); + $count = static::getDatabase()->count('movies', [], 3); $this->assertEquals(3, $count); - self::$authorization->reset(); + Authorization::reset(); /** * Test that OR queries are handled correctly */ - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies', [ + Authorization::disable(); + $count = static::getDatabase()->count('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); $this->assertEquals(1, $count); - self::$authorization->reset(); + Authorization::reset(); } /** @@ -4503,28 +4543,29 @@ public function testCount(): void */ public function testSum(): void { - self::$authorization->addRole('user:x'); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + Authorization::setRole('user:x'); + + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = $this->getDatabase()->sum('movies', 'year'); + $sum = static::getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025 + 2026, $sum); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); - self::$authorization->removeRole('user:x'); - self::$authorization->removeRole('userx'); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + Authorization::unsetRole('user:x'); + Authorization::unsetRole('userx'); + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = $this->getDatabase()->sum('movies', 'year'); + $sum = static::getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025, $sum); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); } @@ -4719,7 +4760,7 @@ public function testEncodeDecode(): void ], ]); - $result = $this->getDatabase()->encode($collection, $document); + $result = static::getDatabase()->encode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -4743,7 +4784,7 @@ public function testEncodeDecode(): void $this->assertEquals(['admin', 'developer', 'tester',], $result->getAttribute('roles')); $this->assertEquals(['{"$id":"1","label":"x"}', '{"$id":"2","label":"y"}', '{"$id":"3","label":"z"}',], $result->getAttribute('tags')); - $result = $this->getDatabase()->decode($collection, $document); + $result = static::getDatabase()->decode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -4777,10 +4818,10 @@ public function testEncodeDecode(): void */ public function testReadPermissionsSuccess(Document $document): Document { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4800,22 +4841,22 @@ public function testReadPermissionsSuccess(Document $document): Document $this->assertEquals(false, $document->isEmpty()); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); return $document; } public function testReadPermissionsFailure(): Document { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::user('1')), Permission::create(Role::user('1')), @@ -4833,13 +4874,13 @@ public function testReadPermissionsFailure(): Document 'colors' => ['pink', 'green', 'blue'], ])); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); return $document; } @@ -4849,10 +4890,10 @@ public function testReadPermissionsFailure(): Document */ public function testWritePermissionsSuccess(Document $document): void { - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4878,10 +4919,10 @@ public function testWritePermissionsUpdateFailure(Document $document): Document { $this->expectException(AuthorizationException::class); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4899,9 +4940,9 @@ public function testWritePermissionsUpdateFailure(Document $document): Document 'colors' => ['pink', 'green', 'blue'], ])); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->updateDocument('documents', $document->getId(), new Document([ + $document = static::getDatabase()->updateDocument('documents', $document->getId(), new Document([ '$id' => ID::custom($document->getId()), '$permissions' => [ Permission::read(Role::any()), @@ -4923,7 +4964,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document public function testNoChangeUpdateDocumentWithoutPermission(): Document { - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()) @@ -4939,7 +4980,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document 'colors' => ['pink', 'green', 'blue'], ])); - $updatedDocument = $this->getDatabase()->updateDocument( + $updatedDocument = static::getDatabase()->updateDocument( 'documents', $document->getId(), $document @@ -4949,7 +4990,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document // It should also not throw any authorization exception without any permission because of no change. $this->assertEquals($updatedDocument->getUpdatedAt(), $document->getUpdatedAt()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$id' => ID::unique(), '$permissions' => [], 'string' => 'text📝', @@ -4965,7 +5006,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document // Should throw exception, because nothing was updated, but there was no read permission try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'documents', $document->getId(), $document @@ -4979,22 +5020,22 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document public function testStructureValidationAfterRelationsAttribute(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection("structure_1", [], [], [Permission::create(Role::any())]); - $this->getDatabase()->createCollection("structure_2", [], [], [Permission::create(Role::any())]); + static::getDatabase()->createCollection("structure_1", [], [], [Permission::create(Role::any())]); + static::getDatabase()->createCollection("structure_2", [], [], [Permission::create(Role::any())]); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: "structure_1", relatedCollection: "structure_2", type: Database::RELATION_ONE_TO_ONE, ); try { - $this->getDatabase()->createDocument('structure_1', new Document([ + static::getDatabase()->createDocument('structure_1', new Document([ '$permissions' => [ Permission::read(Role::any()), ], @@ -5002,14 +5043,14 @@ public function testStructureValidationAfterRelationsAttribute(): void 'name' => 'Frozen', // Unknown attribute 'name' after relation attribute ])); $this->fail('Failed to throw exception'); - } catch (Exception $e) { + } catch(Exception $e) { $this->assertInstanceOf(StructureException::class, $e); } } public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -5030,13 +5071,13 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void Permission::delete(Role::any()), ]; for ($i = 1; $i < 6; $i++) { - $this->getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); + static::getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); } for ($i = 1; $i < 5; $i++) { $collectionId = $i; $relatedCollectionId = $i + 1; - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: "level{$collectionId}", relatedCollection: "level{$relatedCollectionId}", type: Database::RELATION_ONE_TO_ONE, @@ -5045,7 +5086,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void } // Create document with relationship with nested data - $level1 = $this->getDatabase()->createDocument('level1', new Document([ + $level1 = static::getDatabase()->createDocument('level1', new Document([ '$id' => 'level1', '$permissions' => [], 'name' => 'Level 1', @@ -5070,18 +5111,18 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void ], ], ])); - $this->getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); - $updatedLevel1 = $this->getDatabase()->getDocument('level1', $level1->getId()); + static::getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); + $updatedLevel1 = static::getDatabase()->getDocument('level1', $level1->getId()); $this->assertEquals($level1, $updatedLevel1); try { - $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); + static::getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); - } catch (Exception $e) { + } catch(Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); - $this->getDatabase()->updateCollection('level3', [ + static::getDatabase()->updateCollection('level3', [ Permission::read(Role::any()), Permission::create(Role::any()), Permission::update(Role::any()), @@ -5094,11 +5135,11 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void $level2->setAttribute('level3', $level3); $level1->setAttribute('level2', $level2); - $level1 = $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1); + $level1 = static::getDatabase()->updateDocument('level1', $level1->getId(), $level1); $this->assertEquals('updated value', $level1['level2']['level3']['name']); for ($i = 1; $i < 6; $i++) { - $this->getDatabase()->deleteCollection("level{$i}"); + static::getDatabase()->deleteCollection("level{$i}"); } } @@ -5120,10 +5161,10 @@ public function testExceptionAttributeLimit(): void ]); } - $this->getDatabase()->createCollection('attributeLimit', $attributes); + static::getDatabase()->createCollection('attributeLimit', $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); } // Default assertion for other adapters @@ -5136,7 +5177,7 @@ public function testExceptionAttributeLimit(): void public function testCheckAttributeCountLimit(): void { if ($this->getDatabase()->getLimitForAttributes() > 0) { - $collection = $this->getDatabase()->getCollection('attributeLimit'); + $collection = static::getDatabase()->getCollection('attributeLimit'); // create same attribute in testExceptionAttributeLimit $attribute = new Document([ @@ -5151,7 +5192,7 @@ public function testCheckAttributeCountLimit(): void ]); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -5187,7 +5228,7 @@ public function rowWidthExceedsMaximum(): array */ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { + if (static::getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { $attributes = []; // Load the collection up to the limit @@ -5247,10 +5288,10 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo ]); } - $collection = $this->getDatabase()->createCollection("widthLimit{$key}", $attributes); + $collection = static::getDatabase()->createCollection("widthLimit{$key}", $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); + $this->assertEquals(false, static::getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); } // Default assertion for other adapters @@ -5263,8 +5304,8 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo */ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { - $collection = $this->getDatabase()->getCollection("widthLimit{$key}"); + if (static::getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { + $collection = static::getDatabase()->getCollection("widthLimit{$key}"); // create same attribute in testExceptionWidthLimit $attribute = new Document([ @@ -5279,7 +5320,7 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str ]); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -5288,22 +5329,22 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str public function testExceptionIndexLimit(): void { - $this->getDatabase()->createCollection('indexLimit'); + static::getDatabase()->createCollection('indexLimit'); // add unique attributes for indexing for ($i = 0; $i < 64; $i++) { - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); } // Testing for indexLimit // Add up to the limit, then check if the next index throws IndexLimitException for ($i = 0; $i < ($this->getDatabase()->getLimitForIndexes()); $i++) { - $this->assertEquals(true, $this->getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); } $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); + $this->assertEquals(false, static::getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); - $this->getDatabase()->deleteCollection('indexLimit'); + static::getDatabase()->deleteCollection('indexLimit'); } /** @@ -5312,10 +5353,9 @@ public function testExceptionIndexLimit(): void public function testExceptionDuplicate(Document $document): void { $document->setAttribute('$id', 'duplicated'); - $this->getDatabase()->createDocument($document->getCollection(), $document); - + static::getDatabase()->createDocument($document->getCollection(), $document); $this->expectException(DuplicateException::class); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); } /** @@ -5325,12 +5365,12 @@ public function testExceptionCaseInsensitiveDuplicate(Document $document): Docum { $document->setAttribute('$id', 'caseSensitive'); $document->setAttribute('$internalId', '200'); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); $document->setAttribute('$id', 'CaseSensitive'); $this->expectException(DuplicateException::class); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); return $document; } @@ -5342,9 +5382,9 @@ public function testUniqueIndexDuplicate(): void { $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -5374,9 +5414,9 @@ public function testUniqueIndexDuplicate(): void */ public function testUniqueIndexDuplicateUpdate(): void { - self::$authorization->addRole(Role::users()->toString()); + Authorization::setRole(Role::users()->toString()); // create document then update to conflict with index - $document = $this->getDatabase()->createDocument('movies', new Document([ + $document = static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -5402,7 +5442,7 @@ public function testUniqueIndexDuplicateUpdate(): void $this->expectException(DuplicateException::class); - $this->getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); + static::getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); } public function testGetAttributeLimit(): void @@ -5428,7 +5468,7 @@ public function testGetId(): void public function testRenameIndex(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $numbers = $database->createCollection('numbers'); $database->createAttribute('numbers', 'verbose', Database::VAR_STRING, 128, true); @@ -5454,7 +5494,7 @@ public function testRenameIndex(): void */ public function testRenameIndexMissing(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Index not found'); $index = $database->renameIndex('numbers', 'index1', 'index4'); } @@ -5465,14 +5505,14 @@ public function testRenameIndexMissing(): void */ public function testRenameIndexExisting(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Index name already used'); $index = $database->renameIndex('numbers', 'index3', 'index2'); } public function testRenameAttribute(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $colors = $database->createCollection('colors'); $database->createAttribute('colors', 'name', Database::VAR_STRING, 128, true); @@ -5518,7 +5558,7 @@ public function testRenameAttribute(): void */ public function textRenameAttributeMissing(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Attribute not found'); $database->renameAttribute('colors', 'name2', 'name3'); } @@ -5529,14 +5569,14 @@ public function textRenameAttributeMissing(): void */ public function testRenameAttributeExisting(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Attribute name already used'); $database->renameAttribute('colors', 'verbose', 'hex'); } public function testUpdateAttributeDefault(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $flowers = $database->createCollection('flowers'); $database->createAttribute('flowers', 'name', Database::VAR_STRING, 128, true); @@ -5591,7 +5631,7 @@ public function testUpdateAttributeDefault(): void */ public function testUpdateAttributeRequired(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->updateAttributeRequired('flowers', 'inStock', true); @@ -5613,7 +5653,7 @@ public function testUpdateAttributeRequired(): void */ public function testUpdateAttributeFilter(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createAttribute('flowers', 'cartModel', Database::VAR_STRING, 2000, false); @@ -5646,7 +5686,7 @@ public function testUpdateAttributeFilter(): void */ public function testUpdateAttributeFormat(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createAttribute('flowers', 'price', Database::VAR_INTEGER, 0, false); @@ -5707,7 +5747,7 @@ public function testUpdateAttributeStructure(): void return new Range($min, $max); }, Database::VAR_INTEGER); - $database = $this->getDatabase(); + $database = static::getDatabase(); // price attribute $collection = $database->getCollection('flowers'); @@ -6031,27 +6071,27 @@ public function testUpdateAttributeSize(): void */ public function testCreatedAtUpdatedAtAssert(): void { - $document = $this->getDatabase()->getDocument('created_at', 'uid123'); + $document = static::getDatabase()->getDocument('created_at', 'uid123'); $this->assertEquals(true, !$document->isEmpty()); sleep(1); $document->setAttribute('title', 'new title'); - $this->getDatabase()->updateDocument('created_at', 'uid123', $document); - $document = $this->getDatabase()->getDocument('created_at', 'uid123'); + static::getDatabase()->updateDocument('created_at', 'uid123', $document); + $document = static::getDatabase()->getDocument('created_at', 'uid123'); $this->assertGreaterThan($document->getCreatedAt(), $document->getUpdatedAt()); $this->expectException(DuplicateException::class); - $this->getDatabase()->createCollection('created_at'); + static::getDatabase()->createCollection('created_at'); } public function testCreateDatetime(): void { - $this->getDatabase()->createCollection('datetime'); + static::getDatabase()->createCollection('datetime'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); - $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); - $doc = $this->getDatabase()->createDocument('datetime', new Document([ + $doc = static::getDatabase()->createDocument('datetime', new Document([ '$id' => ID::custom('id1234'), '$permissions' => [ Permission::read(Role::any()), @@ -6069,25 +6109,25 @@ public function testCreateDatetime(): void $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getCreatedAt()); $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getUpdatedAt()); - $document = $this->getDatabase()->getDocument('datetime', 'id1234'); + $document = static::getDatabase()->getDocument('datetime', 'id1234'); $dateValidator = new DatetimeValidator(); $this->assertEquals(null, $document->getAttribute('date2')); $this->assertEquals(true, $dateValidator->isValid($document->getAttribute('date'))); $this->assertEquals(false, $dateValidator->isValid($document->getAttribute('date2'))); - $documents = $this->getDatabase()->find('datetime', [ + $documents = static::getDatabase()->find('datetime', [ Query::greaterThan('date', '1975-12-06 10:00:00+01:00'), Query::lessThan('date', '2030-12-06 10:00:00-01:00'), ]); $this->assertEquals(1, count($documents)); - $documents = $this->getDatabase()->find('datetime', [ + $documents = static::getDatabase()->find('datetime', [ Query::greaterThan('$createdAt', '1975-12-06 11:00:00.000'), ]); $this->assertCount(1, $documents); try { - $this->getDatabase()->createDocument('datetime', new Document([ + static::getDatabase()->createDocument('datetime', new Document([ 'date' => "1975-12-06 00:00:61" // 61 seconds is invalid ])); $this->fail('Failed to throw exception'); @@ -6112,7 +6152,7 @@ public function testCreateDatetime(): void foreach ($invalidDates as $date) { try { - $this->getDatabase()->find('datetime', [ + static::getDatabase()->find('datetime', [ Query::equal('date', [$date]) ]); $this->fail('Failed to throw exception'); @@ -6125,16 +6165,16 @@ public function testCreateDatetime(): void public function testCreateDateTimeAttributeFailure(): void { - $this->getDatabase()->createCollection('datetime_fail'); + static::getDatabase()->createCollection('datetime_fail'); /** Test for FAILURE */ $this->expectException(Exception::class); - $this->getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); + static::getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); } public function testKeywords(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $keywords = $database->getKeywords(); // Collection name tests @@ -6196,7 +6236,7 @@ public function testKeywords(): void $collection = $database->createCollection($collectionName); $this->assertEquals($collectionName, $collection->getId()); - $attribute = $this->getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); + $attribute = static::getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); $this->assertEquals(true, $attribute); $document = new Document([ @@ -6245,8 +6285,8 @@ public function testKeywords(): void public function testWritePermissions(): void { - self::$authorization->addRole(Role::any()->toString()); - $database = $this->getDatabase(); + Authorization::setRole(Role::any()->toString()); + $database = static::getDatabase(); $database->createCollection('animals', permissions: [ Permission::create(Role::any()), @@ -6311,7 +6351,7 @@ public function testWritePermissions(): void $newCat = $cat->setAttribute('type', 'newCat'); $database->updateDocument('animals', 'cat', $newCat); - $docs = self::$authorization->skip(fn () => $database->find('animals')); + $docs = Authorization::skip(fn () => $database->find('animals')); $this->assertCount(1, $docs); $this->assertEquals('cat', $docs[0]['$id']); $this->assertEquals('newCat', $docs[0]['type']); @@ -6319,19 +6359,19 @@ public function testWritePermissions(): void public function testNoInvalidKeysWithRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('species'); - $this->getDatabase()->createCollection('creatures'); - $this->getDatabase()->createCollection('characterstics'); + static::getDatabase()->createCollection('species'); + static::getDatabase()->createCollection('creatures'); + static::getDatabase()->createCollection('characterstics'); - $this->getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('characterstics', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('characterstics', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'species', relatedCollection: 'creatures', type: Database::RELATION_ONE_TO_ONE, @@ -6339,7 +6379,7 @@ public function testNoInvalidKeysWithRelationships(): void id: 'creature', twoWayKey:'species' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'creatures', relatedCollection: 'characterstics', type: Database::RELATION_ONE_TO_ONE, @@ -6348,7 +6388,7 @@ public function testNoInvalidKeysWithRelationships(): void twoWayKey:'creature' ); - $species = $this->getDatabase()->createDocument('species', new Document([ + $species = static::getDatabase()->createDocument('species', new Document([ '$id' => ID::custom('1'), '$permissions' => [ Permission::read(Role::any()), @@ -6370,7 +6410,7 @@ public function testNoInvalidKeysWithRelationships(): void ] ] ])); - $this->getDatabase()->updateDocument('species', $species->getId(), new Document([ + static::getDatabase()->updateDocument('species', $species->getId(), new Document([ '$id' => ID::custom('1'), '$collection' => 'species', 'creature' => [ @@ -6383,33 +6423,33 @@ public function testNoInvalidKeysWithRelationships(): void ] ] ])); - $updatedSpecies = $this->getDatabase()->getDocument('species', $species->getId()); + $updatedSpecies = static::getDatabase()->getDocument('species', $species->getId()); $this->assertEquals($species, $updatedSpecies); } // Relationships public function testOneToOneOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('person'); - $this->getDatabase()->createCollection('library'); + static::getDatabase()->createCollection('person'); + static::getDatabase()->createCollection('library'); - $this->getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'person', relatedCollection: 'library', type: Database::RELATION_ONE_TO_ONE ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('person'); + $collection = static::getDatabase()->getCollection('person'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -6425,14 +6465,14 @@ public function testOneToOneOneWayRelationship(): void } try { - $this->getDatabase()->deleteAttribute('person', 'library'); + static::getDatabase()->deleteAttribute('person', 'library'); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete relationship as an attribute', $e->getMessage()); } // Create document with relationship with nested data - $person1 = $this->getDatabase()->createDocument('person', new Document([ + $person1 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -6453,24 +6493,24 @@ public function testOneToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'no-library') ); - $person1Document = $this->getDatabase()->getDocument('person', 'person1'); + $person1Document = static::getDatabase()->getDocument('person', 'person1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $person1Document->getAttribute('library')); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'library1') ); // Update through create - $library10 = $this->getDatabase()->createDocument('library', new Document([ + $library10 = static::getDatabase()->createDocument('library', new Document([ '$id' => 'library10', '$permissions' => [ Permission::read(Role::any()), @@ -6479,7 +6519,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 10', 'area' => 'Area 10', ])); - $person10 = $this->getDatabase()->createDocument('person', new Document([ + $person10 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person10', '$permissions' => [ Permission::read(Role::any()), @@ -6494,11 +6534,11 @@ public function testOneToOneOneWayRelationship(): void ], ])); $this->assertEquals('Library 10 Updated', $person10->getAttribute('library')->getAttribute('name')); - $library10 = $this->getDatabase()->getDocument('library', $library10->getId()); + $library10 = static::getDatabase()->getDocument('library', $library10->getId()); $this->assertEquals('Library 10 Updated', $library10->getAttribute('name')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('library', new Document([ + static::getDatabase()->createDocument('library', new Document([ '$id' => 'library2', '$permissions' => [ Permission::read(Role::any()), @@ -6507,7 +6547,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 2', 'area' => 'Area 2', ])); - $this->getDatabase()->createDocument('person', new Document([ + static::getDatabase()->createDocument('person', new Document([ '$id' => 'person2', '$permissions' => [ Permission::read(Role::any()), @@ -6519,34 +6559,34 @@ public function testOneToOneOneWayRelationship(): void ])); // Get documents with relationship - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $library = $person1->getAttribute('library'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('person', $library); - $person = $this->getDatabase()->getDocument('person', 'person2'); + $person = static::getDatabase()->getDocument('person', 'person2'); $library = $person->getAttribute('library'); $this->assertEquals('library2', $library['$id']); $this->assertArrayNotHasKey('person', $library); // Get related documents - $library = $this->getDatabase()->getDocument('library', 'library1'); + $library = static::getDatabase()->getDocument('library', 'library1'); $this->assertArrayNotHasKey('person', $library); - $library = $this->getDatabase()->getDocument('library', 'library2'); + $library = static::getDatabase()->getDocument('library', 'library2'); $this->assertArrayNotHasKey('person', $library); - $people = $this->getDatabase()->find('person', [ + $people = static::getDatabase()->find('person', [ Query::select(['name']) ]); $this->assertArrayNotHasKey('library', $people[0]); - $people = $this->getDatabase()->find('person'); + $people = static::getDatabase()->find('person'); $this->assertEquals(3, \count($people)); // Select related document attributes - $person = $this->getDatabase()->findOne('person', [ + $person = static::getDatabase()->findOne('person', [ Query::select(['*', 'library.name']) ]); @@ -6557,7 +6597,7 @@ public function testOneToOneOneWayRelationship(): void $this->assertEquals('Library 1', $person->getAttribute('library')->getAttribute('name')); $this->assertArrayNotHasKey('area', $person->getAttribute('library')); - $person = $this->getDatabase()->getDocument('person', 'person1', [ + $person = static::getDatabase()->getDocument('person', 'person1', [ Query::select(['*', 'library.name', '$id']) ]); @@ -6566,36 +6606,36 @@ public function testOneToOneOneWayRelationship(): void - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['name']), ]); $this->assertArrayNotHasKey('library', $document); $this->assertEquals('Person 1', $document['name']); - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['*']), ]); $this->assertEquals('library1', $document['library']); - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['library.*']), ]); $this->assertEquals('Library 1', $document['library']['name']); $this->assertArrayNotHasKey('name', $document); // Update root document attribute without altering relationship - $person1 = $this->getDatabase()->updateDocument( + $person1 = static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('name', 'Person 1 Updated') ); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); // Update nested document attribute - $person1 = $this->getDatabase()->updateDocument( + $person1 = static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute( @@ -6607,11 +6647,11 @@ public function testOneToOneOneWayRelationship(): void ); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); // Create new document with no relationship - $person3 = $this->getDatabase()->createDocument('person', new Document([ + $person3 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person3', '$permissions' => [ Permission::read(Role::any()), @@ -6622,7 +6662,7 @@ public function testOneToOneOneWayRelationship(): void ])); // Update to relate to created document - $person3 = $this->getDatabase()->updateDocument( + $person3 = static::getDatabase()->updateDocument( 'person', $person3->getId(), $person3->setAttribute('library', new Document([ @@ -6637,23 +6677,23 @@ public function testOneToOneOneWayRelationship(): void ); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); - $person3 = $this->getDatabase()->getDocument('person', 'person3'); + $person3 = static::getDatabase()->getDocument('person', 'person3'); $this->assertEquals('Library 3', $person3['library']['name']); - $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); + $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); $libraryDocument->setAttribute('name', 'Library 3 updated'); - $this->getDatabase()->updateDocument('library', 'library3', $libraryDocument); - $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); + static::getDatabase()->updateDocument('library', 'library3', $libraryDocument); + $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); $this->assertEquals('Library 3 updated', $libraryDocument['name']); - $person3 = $this->getDatabase()->getDocument('person', 'person3'); + $person3 = static::getDatabase()->getDocument('person', 'person3'); // Todo: This is failing $this->assertEquals($libraryDocument['name'], $person3['library']['name']); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library2') @@ -6664,7 +6704,7 @@ public function testOneToOneOneWayRelationship(): void } // Create new document - $library4 = $this->getDatabase()->createDocument('library', new Document([ + $library4 = static::getDatabase()->createDocument('library', new Document([ '$id' => 'library4', '$permissions' => [ Permission::read(Role::any()), @@ -6675,33 +6715,33 @@ public function testOneToOneOneWayRelationship(): void ])); // Relate existing document to new document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library4') ); // Relate existing document to new document as nested data - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', $library4) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'library', newKey: 'newLibrary' ); // Get document with again - $person = $this->getDatabase()->getDocument('person', 'person1'); + $person = static::getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary'); $this->assertEquals('library4', $library['$id']); // Create person with no relationship - $this->getDatabase()->createDocument('person', new Document([ + static::getDatabase()->createDocument('person', new Document([ '$id' => 'person4', '$permissions' => [ Permission::read(Role::any()), @@ -6712,22 +6752,22 @@ public function testOneToOneOneWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = $this->getDatabase()->deleteDocument('person', 'person4'); + $deleted = static::getDatabase()->deleteDocument('person', 'person4'); $this->assertEquals(true, $deleted); - $person4 = $this->getDatabase()->getDocument('person', 'person4'); + $person4 = static::getDatabase()->getDocument('person', 'person4'); $this->assertEquals(true, $person4->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - $this->getDatabase()->deleteDocument('person', 'person1'); + static::getDatabase()->deleteDocument('person', 'person1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Can delete child document while still related to another with on delete set to restrict - $person5 = $this->getDatabase()->createDocument('person', new Document([ + $person5 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person5', '$permissions' => [ Permission::read(Role::any()), @@ -6745,60 +6785,60 @@ public function testOneToOneOneWayRelationship(): void 'area' => 'Area 5', ], ])); - $deleted = $this->getDatabase()->deleteDocument('library', 'library5'); + $deleted = static::getDatabase()->deleteDocument('library', 'library5'); $this->assertEquals(true, $deleted); - $person5 = $this->getDatabase()->getDocument('person', 'person5'); + $person5 = static::getDatabase()->getDocument('person', 'person5'); $this->assertEquals(null, $person5->getAttribute('newLibrary')); // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, no effect on children for one-way - $this->getDatabase()->deleteDocument('person', 'person1'); + static::getDatabase()->deleteDocument('person', 'person1'); // Delete child, set parent relating attribute to null for one-way - $this->getDatabase()->deleteDocument('library', 'library2'); + static::getDatabase()->deleteDocument('library', 'library2'); // Check relation was set to null - $person2 = $this->getDatabase()->getDocument('person', 'person2'); + $person2 = static::getDatabase()->getDocument('person', 'person2'); $this->assertEquals(null, $person2->getAttribute('newLibrary', '')); // Relate to another document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person2->getId(), $person2->setAttribute('newLibrary', 'library4') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('person', 'person2'); + static::getDatabase()->deleteDocument('person', 'person2'); // Check parent and child were deleted - $person = $this->getDatabase()->getDocument('person', 'person2'); + $person = static::getDatabase()->getDocument('person', 'person2'); $this->assertEquals(true, $person->isEmpty()); - $library = $this->getDatabase()->getDocument('library', 'library4'); + $library = static::getDatabase()->getDocument('library', 'library4'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'person', 'newLibrary' ); // Check parent doesn't have relationship anymore - $person = $this->getDatabase()->getDocument('person', 'person1'); + $person = static::getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary', ''); $this->assertEquals(null, $library); } @@ -6812,26 +6852,26 @@ public function testOneToOneOneWayRelationship(): void */ public function testOneToOneTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('country'); - $this->getDatabase()->createCollection('city'); + static::getDatabase()->createCollection('country'); + static::getDatabase()->createCollection('city'); - $this->getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); - $this->getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); + static::getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'country', relatedCollection: 'city', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $collection = $this->getDatabase()->getCollection('country'); + $collection = static::getDatabase()->getCollection('country'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'city') { @@ -6845,7 +6885,7 @@ public function testOneToOneTwoWayRelationship(): void } } - $collection = $this->getDatabase()->getCollection('city'); + $collection = static::getDatabase()->getCollection('city'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'country') { @@ -6880,40 +6920,40 @@ public function testOneToOneTwoWayRelationship(): void ], ]); - $this->getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + static::getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); + static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); - $country1Document = $this->getDatabase()->getDocument('country', 'country1'); + $country1Document = static::getDatabase()->getDocument('country', 'country1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $country1Document->getAttribute('city')); - $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); + static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); try { - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertInstanceOf(RestrictedException::class, $e); } - $this->assertTrue($this->getDatabase()->deleteDocument('city', 'city1')); + $this->assertTrue(static::getDatabase()->deleteDocument('city', 'city1')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertTrue($city1->isEmpty()); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertTrue($country1->getAttribute('city')->isEmpty()); - $this->assertTrue($this->getDatabase()->deleteDocument('country', 'country1')); + $this->assertTrue(static::getDatabase()->deleteDocument('country', 'country1')); - $this->getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + static::getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city2', '$permissions' => [ Permission::read(Role::any()), @@ -6923,7 +6963,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'Paris', 'code' => 'PAR', ])); - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country2', '$permissions' => [ Permission::read(Role::any()), @@ -6935,7 +6975,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city3', '$permissions' => [ Permission::read(Role::any()), @@ -6954,7 +6994,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'New Zealand', ], ])); - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country4', '$permissions' => [ Permission::read(Role::any()), @@ -6963,7 +7003,7 @@ public function testOneToOneTwoWayRelationship(): void ], 'name' => 'Australia', ])); - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city4', '$permissions' => [ Permission::read(Role::any()), @@ -6976,53 +7016,53 @@ public function testOneToOneTwoWayRelationship(): void ])); // Get document with relationship - $city = $this->getDatabase()->getDocument('city', 'city1'); + $city = static::getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('country'); $this->assertEquals('country1', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city2'); + $city = static::getDatabase()->getDocument('city', 'city2'); $country = $city->getAttribute('country'); $this->assertEquals('country2', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city3'); + $city = static::getDatabase()->getDocument('city', 'city3'); $country = $city->getAttribute('country'); $this->assertEquals('country3', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city4'); + $city = static::getDatabase()->getDocument('city', 'city4'); $country = $city->getAttribute('country'); $this->assertEquals('country4', $country['$id']); $this->assertArrayNotHasKey('city', $country); // Get inverse document with relationship - $country = $this->getDatabase()->getDocument('country', 'country1'); + $country = static::getDatabase()->getDocument('country', 'country1'); $city = $country->getAttribute('city'); $this->assertEquals('city1', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country2'); + $country = static::getDatabase()->getDocument('country', 'country2'); $city = $country->getAttribute('city'); $this->assertEquals('city2', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country3'); + $country = static::getDatabase()->getDocument('country', 'country3'); $city = $country->getAttribute('city'); $this->assertEquals('city3', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country4'); + $country = static::getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('city'); $this->assertEquals('city4', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $countries = $this->getDatabase()->find('country'); + $countries = static::getDatabase()->find('country'); $this->assertEquals(4, \count($countries)); // Select related document attributes - $country = $this->getDatabase()->findOne('country', [ + $country = static::getDatabase()->findOne('country', [ Query::select(['*', 'city.name']) ]); @@ -7033,41 +7073,41 @@ public function testOneToOneTwoWayRelationship(): void $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country = $this->getDatabase()->getDocument('country', 'country1', [ + $country = static::getDatabase()->getDocument('country', 'country1', [ Query::select(['*', 'city.name']) ]); $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); // Update root document attribute without altering relationship - $country1 = $this->getDatabase()->updateDocument( + $country1 = static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('name', 'Country 1 Updated') ); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); // Update inverse root document attribute without altering relationship - $city2 = $this->getDatabase()->updateDocument( + $city2 = static::getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute('name', 'City 2 Updated') ); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); // Update nested document attribute - $country1 = $this->getDatabase()->updateDocument( + $country1 = static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute( @@ -7079,11 +7119,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); // Update inverse nested document attribute - $city2 = $this->getDatabase()->updateDocument( + $city2 = static::getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute( @@ -7095,11 +7135,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); // Create new document with no relationship - $country5 = $this->getDatabase()->createDocument('country', new Document([ + $country5 = static::getDatabase()->createDocument('country', new Document([ '$id' => 'country5', '$permissions' => [ Permission::read(Role::any()), @@ -7110,7 +7150,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $country5 = $this->getDatabase()->updateDocument( + $country5 = static::getDatabase()->updateDocument( 'country', $country5->getId(), $country5->setAttribute('city', new Document([ @@ -7125,11 +7165,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); - $country5 = $this->getDatabase()->getDocument('country', 'country5'); + $country5 = static::getDatabase()->getDocument('country', 'country5'); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); // Create new document with no relationship - $city6 = $this->getDatabase()->createDocument('city', new Document([ + $city6 = static::getDatabase()->createDocument('city', new Document([ '$id' => 'city6', '$permissions' => [ Permission::read(Role::any()), @@ -7141,7 +7181,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $city6 = $this->getDatabase()->updateDocument( + $city6 = static::getDatabase()->updateDocument( 'city', $city6->getId(), $city6->setAttribute('country', new Document([ @@ -7155,12 +7195,12 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); - $city6 = $this->getDatabase()->getDocument('city', 'city6'); + $city6 = static::getDatabase()->getDocument('city', 'city6'); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city2') @@ -7170,21 +7210,21 @@ public function testOneToOneTwoWayRelationship(): void $this->assertInstanceOf(DuplicateException::class, $e); } - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); // Set relationship to null - $city1 = $this->getDatabase()->updateDocument( + $city1 = static::getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', null) ); $this->assertEquals(null, $city1->getAttribute('country')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertEquals(null, $city1->getAttribute('country')); // Create a new city with no relation - $city7 = $this->getDatabase()->createDocument('city', new Document([ + $city7 = static::getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -7196,21 +7236,21 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update document with relation to new document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city7') ); // Relate existing document to new document as nested data - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', $city7) ); // Create a new country with no relation - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country7', '$permissions' => [ Permission::read(Role::any()), @@ -7221,14 +7261,14 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update inverse document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', 'country7') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'country', 'city', 'newCity', @@ -7236,17 +7276,17 @@ public function testOneToOneTwoWayRelationship(): void ); // Get document with new relationship key - $city = $this->getDatabase()->getDocument('city', 'city1'); + $city = static::getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('newCountry'); $this->assertEquals('country7', $country['$id']); // Get inverse document with new relationship key - $country = $this->getDatabase()->getDocument('country', 'country7'); + $country = static::getDatabase()->getDocument('country', 'country7'); $city = $country->getAttribute('newCity'); $this->assertEquals('city1', $city['$id']); // Create a new country with no relation - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country8', '$permissions' => [ Permission::read(Role::any()), @@ -7257,87 +7297,87 @@ public function testOneToOneTwoWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = $this->getDatabase()->deleteDocument('country', 'country8'); + $deleted = static::getDatabase()->deleteDocument('country', 'country8'); $this->assertEquals(1, $deleted); - $country8 = $this->getDatabase()->getDocument('country', 'country8'); + $country8 = static::getDatabase()->getDocument('country', 'country8'); $this->assertEquals(true, $country8->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $this->getDatabase()->updateDocument('city', 'city1', new Document(['newCountry' => null, '$id' => 'city1'])); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + static::getDatabase()->updateDocument('city', 'city1', new Document(['newCountry' => null, '$id' => 'city1'])); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertNull($city1->getAttribute('newCountry')); // Check Delete TwoWay TRUE && RELATION_MUTATE_SET_NULL && related value NULL - $this->assertTrue($this->getDatabase()->deleteDocument('city', 'city1')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $this->assertTrue(static::getDatabase()->deleteDocument('city', 'city1')); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertTrue($city1->isEmpty()); // Delete parent, will set child relationship to null for two-way - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); // Check relation was set to null - $city7 = $this->getDatabase()->getDocument('city', 'city7'); + $city7 = static::getDatabase()->getDocument('city', 'city7'); $this->assertEquals(null, $city7->getAttribute('country', '')); // Delete child, set parent relationship to null for two-way - $this->getDatabase()->deleteDocument('city', 'city2'); + static::getDatabase()->deleteDocument('city', 'city2'); // Check relation was set to null - $country2 = $this->getDatabase()->getDocument('country', 'country2'); + $country2 = static::getDatabase()->getDocument('country', 'country2'); $this->assertEquals(null, $country2->getAttribute('city', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'city', $city7->getId(), $city7->setAttribute('newCountry', 'country2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('country', 'country7'); + static::getDatabase()->deleteDocument('country', 'country7'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('country', 'country7'); + $library = static::getDatabase()->getDocument('country', 'country7'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('city', 'city1'); + $library = static::getDatabase()->getDocument('city', 'city1'); $this->assertEquals(true, $library->isEmpty()); // Delete child, will delete parent for two-way - $this->getDatabase()->deleteDocument('city', 'city7'); + static::getDatabase()->deleteDocument('city', 'city7'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('city', 'city7'); + $library = static::getDatabase()->getDocument('city', 'city7'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('country', 'country2'); + $library = static::getDatabase()->getDocument('country', 'country2'); $this->assertEquals(true, $library->isEmpty()); // Create new document to check after deleting relationship - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -7353,33 +7393,33 @@ public function testOneToOneTwoWayRelationship(): void ])); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'country', 'newCity' ); // Try to get document again - $country = $this->getDatabase()->getDocument('country', 'country4'); + $country = static::getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('newCity'); $this->assertEquals(null, $city); // Try to get inverse document again - $city = $this->getDatabase()->getDocument('city', 'city7'); + $city = static::getDatabase()->getDocument('city', 'city7'); $country = $city->getAttribute('newCountry'); $this->assertEquals(null, $country); } public function testIdenticalTwoWayKeyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('parent'); - $this->getDatabase()->createCollection('child'); + static::getDatabase()->createCollection('parent'); + static::getDatabase()->createCollection('child'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_ONE, @@ -7387,7 +7427,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ); try { - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -7398,7 +7438,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('Related attribute already exists', $e->getMessage()); } - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -7406,7 +7446,7 @@ public function testIdenticalTwoWayKeyRelationship(): void twoWayKey: 'parent_id' ); - $collection = $this->getDatabase()->getCollection('parent'); + $collection = static::getDatabase()->getCollection('parent'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'child1') { @@ -7418,7 +7458,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } } - $this->getDatabase()->createDocument('parent', new Document([ + static::getDatabase()->createDocument('parent', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -7436,7 +7476,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ], ])); - $documents = $this->getDatabase()->find('parent', []); + $documents = static::getDatabase()->find('parent', []); $document = array_pop($documents); $this->assertArrayHasKey('child1', $document); $this->assertEquals('foo', $document->getAttribute('child1')->getId()); @@ -7444,7 +7484,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('bar', $document->getAttribute('children')[0]->getId()); try { - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'parent', id: 'children', newKey: 'child1' @@ -7455,7 +7495,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } try { - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'parent', id: 'children', newTwoWayKey: 'parent' @@ -7468,19 +7508,19 @@ public function testIdenticalTwoWayKeyRelationship(): void public function testOneToManyOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('artist'); - $this->getDatabase()->createCollection('album'); + static::getDatabase()->createCollection('artist'); + static::getDatabase()->createCollection('album'); - $this->getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); + static::getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'artist', relatedCollection: 'album', type: Database::RELATION_ONE_TO_MANY, @@ -7488,7 +7528,7 @@ public function testOneToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('artist'); + $collection = static::getDatabase()->getCollection('artist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -7504,7 +7544,7 @@ public function testOneToManyOneWayRelationship(): void } // Create document with relationship with nested data - $artist1 = $this->getDatabase()->createDocument('artist', new Document([ + $artist1 = static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist1', '$permissions' => [ Permission::read(Role::any()), @@ -7526,14 +7566,14 @@ public function testOneToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); + static::getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); - $artist1Document = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1Document = static::getDatabase()->getDocument('artist', 'artist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($artist1Document->getAttribute('albums'))); // Create document with relationship with related ID - $this->getDatabase()->createDocument('album', new Document([ + static::getDatabase()->createDocument('album', new Document([ '$id' => 'album2', '$permissions' => [ Permission::read(Role::any()), @@ -7543,7 +7583,7 @@ public function testOneToManyOneWayRelationship(): void 'name' => 'Album 2', 'price' => 19.99, ])); - $this->getDatabase()->createDocument('artist', new Document([ + static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist2', '$permissions' => [ Permission::read(Role::any()), @@ -7565,19 +7605,19 @@ public function testOneToManyOneWayRelationship(): void ] ])); - $documents = $this->getDatabase()->find('artist', [ + $documents = static::getDatabase()->find('artist', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayNotHasKey('albums', $documents[0]); // Get document with relationship - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album1', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); - $artist = $this->getDatabase()->getDocument('artist', 'artist2'); + $artist = static::getDatabase()->getDocument('artist', 'artist2'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album2', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); @@ -7585,18 +7625,18 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(2, $albums); // Get related document - $album = $this->getDatabase()->getDocument('album', 'album1'); + $album = static::getDatabase()->getDocument('album', 'album1'); $this->assertArrayNotHasKey('artist', $album); - $album = $this->getDatabase()->getDocument('album', 'album2'); + $album = static::getDatabase()->getDocument('album', 'album2'); $this->assertArrayNotHasKey('artist', $album); - $artists = $this->getDatabase()->find('artist'); + $artists = static::getDatabase()->find('artist'); $this->assertEquals(2, \count($artists)); // Select related document attributes - $artist = $this->getDatabase()->findOne('artist', [ + $artist = static::getDatabase()->findOne('artist', [ Query::select(['*', 'albums.name']) ]); @@ -7607,7 +7647,7 @@ public function testOneToManyOneWayRelationship(): void $this->assertEquals('Album 1', $artist->getAttribute('albums')[0]->getAttribute('name')); $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); - $artist = $this->getDatabase()->getDocument('artist', 'artist1', [ + $artist = static::getDatabase()->getDocument('artist', 'artist1', [ Query::select(['*', 'albums.name']) ]); @@ -7615,43 +7655,43 @@ public function testOneToManyOneWayRelationship(): void $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); // Update root document attribute without altering relationship - $artist1 = $this->getDatabase()->updateDocument( + $artist1 = static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('name', 'Artist 1 Updated') ); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); - $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); // Update nested document attribute $albums = $artist1->getAttribute('albums', []); $albums[0]->setAttribute('name', 'Album 1 Updated'); - $artist1 = $this->getDatabase()->updateDocument( + $artist1 = static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', $albums) ); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); - $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); $albumId = $artist1->getAttribute('albums')[0]->getAttribute('$id'); - $albumDocument = $this->getDatabase()->getDocument('album', $albumId); + $albumDocument = static::getDatabase()->getDocument('album', $albumId); $albumDocument->setAttribute('name', 'Album 1 Updated!!!'); - $this->getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); - $albumDocument = $this->getDatabase()->getDocument('album', $albumDocument->getId()); - $artist1 = $this->getDatabase()->getDocument('artist', $artist1->getId()); + static::getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); + $albumDocument = static::getDatabase()->getDocument('album', $albumDocument->getId()); + $artist1 = static::getDatabase()->getDocument('artist', $artist1->getId()); $this->assertEquals('Album 1 Updated!!!', $albumDocument['name']); $this->assertEquals($albumDocument->getId(), $artist1->getAttribute('albums')[0]->getId()); $this->assertEquals($albumDocument->getAttribute('name'), $artist1->getAttribute('albums')[0]->getAttribute('name')); // Create new document with no relationship - $artist3 = $this->getDatabase()->createDocument('artist', new Document([ + $artist3 = static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist3', '$permissions' => [ Permission::read(Role::any()), @@ -7662,7 +7702,7 @@ public function testOneToManyOneWayRelationship(): void ])); // Update to relate to created document - $artist3 = $this->getDatabase()->updateDocument( + $artist3 = static::getDatabase()->updateDocument( 'artist', $artist3->getId(), $artist3->setAttribute('albums', [new Document([ @@ -7678,37 +7718,37 @@ public function testOneToManyOneWayRelationship(): void ); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); - $artist3 = $this->getDatabase()->getDocument('artist', 'artist3'); + $artist3 = static::getDatabase()->getDocument('artist', 'artist3'); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); // Update document with new related documents, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album2']) ); // Update document with new related documents, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album1', 'album2']) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'artist', 'albums', 'newAlbums' ); // Get document with new relationship key - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums'); $this->assertEquals('album1', $albums[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('artist', new Document([ + static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist4', '$permissions' => [ Permission::read(Role::any()), @@ -7719,56 +7759,56 @@ public function testOneToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('artist', 'artist4'); + $deleted = static::getDatabase()->deleteDocument('artist', 'artist4'); $this->assertEquals(true, $deleted); - $artist4 = $this->getDatabase()->getDocument('artist', 'artist4'); + $artist4 = static::getDatabase()->getDocument('artist', 'artist4'); $this->assertEquals(true, $artist4->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('artist', 'artist1'); + static::getDatabase()->deleteDocument('artist', 'artist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - $this->getDatabase()->deleteDocument('artist', 'artist1'); + static::getDatabase()->deleteDocument('artist', 'artist1'); // Check relation was set to null - $album2 = $this->getDatabase()->getDocument('album', 'album2'); + $album2 = static::getDatabase()->getDocument('album', 'album2'); $this->assertEquals(null, $album2->getAttribute('artist', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'album', $album2->getId(), $album2->setAttribute('artist', 'artist2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('artist', 'artist2'); + static::getDatabase()->deleteDocument('artist', 'artist2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('artist', 'artist2'); + $library = static::getDatabase()->getDocument('artist', 'artist2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('album', 'album2'); + $library = static::getDatabase()->getDocument('album', 'album2'); $this->assertEquals(true, $library->isEmpty()); $albums = []; @@ -7785,7 +7825,7 @@ public function testOneToManyOneWayRelationship(): void ]; } - $artist = $this->getDatabase()->createDocument('artist', new Document([ + $artist = static::getDatabase()->createDocument('artist', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::delete(Role::any()), @@ -7794,29 +7834,29 @@ public function testOneToManyOneWayRelationship(): void 'newAlbums' => $albums ])); - $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); + $artist = static::getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(50, $artist->getAttribute('newAlbums')); - $albums = $this->getDatabase()->find('album', [ + $albums = static::getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); $this->assertCount(50, $albums); - $count = $this->getDatabase()->count('album', [ + $count = static::getDatabase()->count('album', [ Query::equal('artist', [$artist->getId()]), ]); $this->assertEquals(50, $count); - $this->getDatabase()->deleteDocument('album', 'album_1'); - $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); + static::getDatabase()->deleteDocument('album', 'album_1'); + $artist = static::getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(49, $artist->getAttribute('newAlbums')); - $this->getDatabase()->deleteDocument('artist', $artist->getId()); + static::getDatabase()->deleteDocument('artist', $artist->getId()); - $albums = $this->getDatabase()->find('album', [ + $albums = static::getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); @@ -7824,32 +7864,32 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(0, $albums); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'artist', 'newAlbums' ); // Try to get document again - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums', ''); $this->assertEquals(null, $albums); } public function testOneToManyTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('customer'); - $this->getDatabase()->createCollection('account'); + static::getDatabase()->createCollection('customer'); + static::getDatabase()->createCollection('account'); - $this->getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'customer', relatedCollection: 'account', type: Database::RELATION_ONE_TO_MANY, @@ -7858,7 +7898,7 @@ public function testOneToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('customer'); + $collection = static::getDatabase()->getCollection('customer'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'accounts') { @@ -7873,7 +7913,7 @@ public function testOneToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('account'); + $collection = static::getDatabase()->getCollection('account'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'customer') { @@ -7888,7 +7928,7 @@ public function testOneToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $customer1 = $this->getDatabase()->createDocument('customer', new Document([ + $customer1 = static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer1', '$permissions' => [ Permission::read(Role::any()), @@ -7911,14 +7951,14 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); + static::getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); - $customer1Document = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1Document = static::getDatabase()->getDocument('customer', 'customer1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($customer1Document->getAttribute('accounts'))); // Create document with relationship with related ID - $account2 = $this->getDatabase()->createDocument('account', new Document([ + $account2 = static::getDatabase()->createDocument('account', new Document([ '$id' => 'account2', '$permissions' => [ Permission::read(Role::any()), @@ -7928,7 +7968,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Account 2', 'number' => '987654321', ])); - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer2', '$permissions' => [ Permission::read(Role::any()), @@ -7942,7 +7982,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('account', new Document([ + static::getDatabase()->createDocument('account', new Document([ '$id' => 'account3', '$permissions' => [ Permission::read(Role::any()), @@ -7961,7 +8001,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Customer 3' ] ])); - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer4', '$permissions' => [ Permission::read(Role::any()), @@ -7970,7 +8010,7 @@ public function testOneToManyTwoWayRelationship(): void ], 'name' => 'Customer 4', ])); - $this->getDatabase()->createDocument('account', new Document([ + static::getDatabase()->createDocument('account', new Document([ '$id' => 'account4', '$permissions' => [ Permission::read(Role::any()), @@ -7983,53 +8023,53 @@ public function testOneToManyTwoWayRelationship(): void ])); // Get documents with relationship - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account1', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer2'); + $customer = static::getDatabase()->getDocument('customer', 'customer2'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account2', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer3'); + $customer = static::getDatabase()->getDocument('customer', 'customer3'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account3', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer4'); + $customer = static::getDatabase()->getDocument('customer', 'customer4'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account4', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); // Get related documents - $account = $this->getDatabase()->getDocument('account', 'account1'); + $account = static::getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer1', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account2'); + $account = static::getDatabase()->getDocument('account', 'account2'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer2', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account3'); + $account = static::getDatabase()->getDocument('account', 'account3'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer3', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account4'); + $account = static::getDatabase()->getDocument('account', 'account4'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer4', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $customers = $this->getDatabase()->find('customer'); + $customers = static::getDatabase()->find('customer'); $this->assertEquals(4, \count($customers)); // Select related document attributes - $customer = $this->getDatabase()->findOne('customer', [ + $customer = static::getDatabase()->findOne('customer', [ Query::select(['*', 'accounts.name']) ]); @@ -8040,7 +8080,7 @@ public function testOneToManyTwoWayRelationship(): void $this->assertEquals('Account 1', $customer->getAttribute('accounts')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer1', [ + $customer = static::getDatabase()->getDocument('customer', 'customer1', [ Query::select(['*', 'accounts.name']) ]); @@ -8048,45 +8088,45 @@ public function testOneToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); // Update root document attribute without altering relationship - $customer1 = $this->getDatabase()->updateDocument( + $customer1 = static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('name', 'Customer 1 Updated') ); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); // Update inverse root document attribute without altering relationship - $account2 = $this->getDatabase()->updateDocument( + $account2 = static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('name', 'Account 2 Updated') ); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); // Update nested document attribute $accounts = $customer1->getAttribute('accounts', []); $accounts[0]->setAttribute('name', 'Account 1 Updated'); - $customer1 = $this->getDatabase()->updateDocument( + $customer1 = static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', $accounts) ); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); - $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); // Update inverse nested document attribute - $account2 = $this->getDatabase()->updateDocument( + $account2 = static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute( @@ -8098,11 +8138,11 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); // Create new document with no relationship - $customer5 = $this->getDatabase()->createDocument('customer', new Document([ + $customer5 = static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer5', '$permissions' => [ Permission::read(Role::any()), @@ -8113,7 +8153,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update to relate to created document - $customer5 = $this->getDatabase()->updateDocument( + $customer5 = static::getDatabase()->updateDocument( 'customer', $customer5->getId(), $customer5->setAttribute('accounts', [new Document([ @@ -8129,11 +8169,11 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); - $customer5 = $this->getDatabase()->getDocument('customer', 'customer5'); + $customer5 = static::getDatabase()->getDocument('customer', 'customer5'); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); // Create new child document with no relationship - $account6 = $this->getDatabase()->createDocument('account', new Document([ + $account6 = static::getDatabase()->createDocument('account', new Document([ '$id' => 'account6', '$permissions' => [ Permission::read(Role::any()), @@ -8145,7 +8185,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update inverse to relate to created document - $account6 = $this->getDatabase()->updateDocument( + $account6 = static::getDatabase()->updateDocument( 'account', $account6->getId(), $account6->setAttribute('customer', new Document([ @@ -8160,32 +8200,32 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); - $account6 = $this->getDatabase()->getDocument('account', 'account6'); + $account6 = static::getDatabase()->getDocument('account', 'account6'); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); // Update document with new related document, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account2']) ); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account1', 'account2']) ); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('customer', 'customer2') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'customer', 'accounts', 'newAccounts', @@ -8193,17 +8233,17 @@ public function testOneToManyTwoWayRelationship(): void ); // Get document with new relationship key - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals('account1', $accounts[0]['$id']); // Get inverse document with new relationship key - $account = $this->getDatabase()->getDocument('account', 'account1'); + $account = static::getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('newCustomer'); $this->assertEquals('customer1', $customer['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer7', '$permissions' => [ Permission::read(Role::any()), @@ -8214,91 +8254,91 @@ public function testOneToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('customer', 'customer7'); + $deleted = static::getDatabase()->deleteDocument('customer', 'customer7'); $this->assertEquals(true, $deleted); - $customer7 = $this->getDatabase()->getDocument('customer', 'customer7'); + $customer7 = static::getDatabase()->getDocument('customer', 'customer7'); $this->assertEquals(true, $customer7->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('customer', 'customer1'); + static::getDatabase()->deleteDocument('customer', 'customer1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - $this->getDatabase()->deleteDocument('customer', 'customer1'); + static::getDatabase()->deleteDocument('customer', 'customer1'); // Check relation was set to null - $account1 = $this->getDatabase()->getDocument('account', 'account1'); + $account1 = static::getDatabase()->getDocument('account', 'account1'); $this->assertEquals(null, $account2->getAttribute('newCustomer', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'account', $account1->getId(), $account1->setAttribute('newCustomer', 'customer2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('customer', 'customer2'); + static::getDatabase()->deleteDocument('customer', 'customer2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('customer', 'customer2'); + $library = static::getDatabase()->getDocument('customer', 'customer2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('account', 'account2'); + $library = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'customer', 'newAccounts' ); // Try to get document again - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals(null, $accounts); // Try to get inverse document again - $accounts = $this->getDatabase()->getDocument('account', 'account1'); + $accounts = static::getDatabase()->getDocument('account', 'account1'); $customer = $accounts->getAttribute('newCustomer'); $this->assertEquals(null, $customer); } public function testManyToOneOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('review'); - $this->getDatabase()->createCollection('movie'); + static::getDatabase()->createCollection('review'); + static::getDatabase()->createCollection('movie'); - $this->getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); - $this->getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - $this->getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - $this->getDatabase()->createRelationship( + static::getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); + static::getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + static::getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + static::getDatabase()->createRelationship( collection: 'review', relatedCollection: 'movie', type: Database::RELATION_MANY_TO_ONE, @@ -8306,7 +8346,7 @@ public function testManyToOneOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('review'); + $collection = static::getDatabase()->getCollection('review'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'movie') { @@ -8321,7 +8361,7 @@ public function testManyToOneOneWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('movie'); + $collection = static::getDatabase()->getCollection('movie'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'reviews') { @@ -8336,7 +8376,7 @@ public function testManyToOneOneWayRelationship(): void } // Create document with relationship with nested data - $review1 = $this->getDatabase()->createDocument('review', new Document([ + $review1 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review1', '$permissions' => [ Permission::read(Role::any()), @@ -8359,16 +8399,16 @@ public function testManyToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); + static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); - $review1Document = $this->getDatabase()->getDocument('review', 'review1'); + $review1Document = static::getDatabase()->getDocument('review', 'review1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $review1Document->getAttribute('movie')); - $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); + static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); // Create document with relationship to existing document by ID - $review10 = $this->getDatabase()->createDocument('review', new Document([ + $review10 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review10', '$permissions' => [ Permission::read(Role::any()), @@ -8381,7 +8421,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Create document with relationship with related ID - $this->getDatabase()->createDocument('movie', new Document([ + static::getDatabase()->createDocument('movie', new Document([ '$id' => 'movie2', '$permissions' => [ Permission::read(Role::any()), @@ -8392,7 +8432,7 @@ public function testManyToOneOneWayRelationship(): void 'length' => 90, 'date' => '2023-04-03 10:35:27.390', ])); - $this->getDatabase()->createDocument('review', new Document([ + static::getDatabase()->createDocument('review', new Document([ '$id' => 'review2', '$permissions' => [ Permission::read(Role::any()), @@ -8405,12 +8445,12 @@ public function testManyToOneOneWayRelationship(): void ])); // Get document with relationship - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie1', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); - $documents = $this->getDatabase()->find('review', [ + $documents = static::getDatabase()->find('review', [ Query::select(['date', 'movie.date']) ]); @@ -8424,24 +8464,24 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals(29, strlen($document['date'])); // checks filter $this->assertEquals(29, strlen($document['movie']['date'])); - $review = $this->getDatabase()->getDocument('review', 'review2'); + $review = static::getDatabase()->getDocument('review', 'review2'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie2', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); // Get related document - $movie = $this->getDatabase()->getDocument('movie', 'movie1'); + $movie = static::getDatabase()->getDocument('movie', 'movie1'); $this->assertArrayNotHasKey('reviews', $movie); - $movie = $this->getDatabase()->getDocument('movie', 'movie2'); + $movie = static::getDatabase()->getDocument('movie', 'movie2'); $this->assertArrayNotHasKey('reviews', $movie); - $reviews = $this->getDatabase()->find('review'); + $reviews = static::getDatabase()->find('review'); $this->assertEquals(3, \count($reviews)); // Select related document attributes - $review = $this->getDatabase()->findOne('review', [ + $review = static::getDatabase()->findOne('review', [ Query::select(['*', 'movie.name']) ]); @@ -8452,7 +8492,7 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals('Movie 1', $review->getAttribute('movie')->getAttribute('name')); $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); - $review = $this->getDatabase()->getDocument('review', 'review1', [ + $review = static::getDatabase()->getDocument('review', 'review1', [ Query::select(['*', 'movie.name']) ]); @@ -8460,32 +8500,32 @@ public function testManyToOneOneWayRelationship(): void $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); // Update root document attribute without altering relationship - $review1 = $this->getDatabase()->updateDocument( + $review1 = static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('name', 'Review 1 Updated') ); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); // Update nested document attribute $movie = $review1->getAttribute('movie'); $movie->setAttribute('name', 'Movie 1 Updated'); - $review1 = $this->getDatabase()->updateDocument( + $review1 = static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', $movie) ); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); // Create new document with no relationship - $review5 = $this->getDatabase()->createDocument('review', new Document([ + $review5 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review5', '$permissions' => [ Permission::read(Role::any()), @@ -8496,7 +8536,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Update to relate to created document - $review5 = $this->getDatabase()->updateDocument( + $review5 = static::getDatabase()->updateDocument( 'review', $review5->getId(), $review5->setAttribute('movie', new Document([ @@ -8512,39 +8552,39 @@ public function testManyToOneOneWayRelationship(): void ); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); - $review5 = $this->getDatabase()->getDocument('review', 'review5'); + $review5 = static::getDatabase()->getDocument('review', 'review5'); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', 'movie2') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'review', 'movie', 'newMovie', ); // Get document with new relationship key - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals('movie2', $movie['$id']); // Reset values - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('newMovie', 'movie1') ); // Create new document with no relationship - $this->getDatabase()->createDocument('movie', new Document([ + static::getDatabase()->createDocument('movie', new Document([ '$id' => 'movie3', '$permissions' => [ Permission::read(Role::any()), @@ -8556,78 +8596,78 @@ public function testManyToOneOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('movie', 'movie3'); + $deleted = static::getDatabase()->deleteDocument('movie', 'movie3'); $this->assertEquals(true, $deleted); - $movie3 = $this->getDatabase()->getDocument('movie', 'movie3'); + $movie3 = static::getDatabase()->getDocument('movie', 'movie3'); $this->assertEquals(true, $movie3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('movie', 'movie1'); + static::getDatabase()->deleteDocument('movie', 'movie1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - $this->getDatabase()->deleteDocument('movie', 'movie1'); + static::getDatabase()->deleteDocument('movie', 'movie1'); // Check relation was set to null - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals(null, $review1->getAttribute('newMovie')); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - $this->getDatabase()->deleteDocument('movie', 'movie2'); + static::getDatabase()->deleteDocument('movie', 'movie2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('movie', 'movie2'); + $library = static::getDatabase()->getDocument('movie', 'movie2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('review', 'review2'); + $library = static::getDatabase()->getDocument('review', 'review2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'review', 'newMovie' ); // Try to get document again - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals(null, $movie); } public function testManyToOneTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('product'); - $this->getDatabase()->createCollection('store'); + static::getDatabase()->createCollection('product'); + static::getDatabase()->createCollection('store'); - $this->getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); + static::getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); - $this->getDatabase()->createAttribute( + static::getDatabase()->createAttribute( collection: 'product', id: 'name', type: Database::VAR_STRING, @@ -8635,7 +8675,7 @@ public function testManyToOneTwoWayRelationship(): void required: true ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'product', relatedCollection: 'store', type: Database::RELATION_MANY_TO_ONE, @@ -8644,7 +8684,7 @@ public function testManyToOneTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('product'); + $collection = static::getDatabase()->getCollection('product'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'store') { @@ -8659,7 +8699,7 @@ public function testManyToOneTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('store'); + $collection = static::getDatabase()->getCollection('store'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'products') { @@ -8674,7 +8714,7 @@ public function testManyToOneTwoWayRelationship(): void } // Create document with relationship with nested data - $product1 = $this->getDatabase()->createDocument('product', new Document([ + $product1 = static::getDatabase()->createDocument('product', new Document([ '$id' => 'product1', '$permissions' => [ Permission::read(Role::any()), @@ -8695,16 +8735,16 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); + static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); - $product1Document = $this->getDatabase()->getDocument('product', 'product1'); + $product1Document = static::getDatabase()->getDocument('product', 'product1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $product1Document->getAttribute('store')); - $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); + static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store2', '$permissions' => [ Permission::read(Role::any()), @@ -8714,7 +8754,7 @@ public function testManyToOneTwoWayRelationship(): void 'name' => 'Store 2', 'opensAt' => '09:30', ])); - $this->getDatabase()->createDocument('product', new Document([ + static::getDatabase()->createDocument('product', new Document([ '$id' => 'product2', '$permissions' => [ Permission::read(Role::any()), @@ -8726,7 +8766,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store3', '$permissions' => [ Permission::read(Role::any()), @@ -8748,7 +8788,7 @@ public function testManyToOneTwoWayRelationship(): void ], ])); - $this->getDatabase()->createDocument('product', new Document([ + static::getDatabase()->createDocument('product', new Document([ '$id' => 'product4', '$permissions' => [ Permission::read(Role::any()), @@ -8757,7 +8797,7 @@ public function testManyToOneTwoWayRelationship(): void ], 'name' => 'Product 4', ])); - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store4', '$permissions' => [ Permission::read(Role::any()), @@ -8772,53 +8812,53 @@ public function testManyToOneTwoWayRelationship(): void ])); // Get document with relationship - $product = $this->getDatabase()->getDocument('product', 'product1'); + $product = static::getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('store', []); $this->assertEquals('store1', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product2'); + $product = static::getDatabase()->getDocument('product', 'product2'); $store = $product->getAttribute('store', []); $this->assertEquals('store2', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product3'); + $product = static::getDatabase()->getDocument('product', 'product3'); $store = $product->getAttribute('store', []); $this->assertEquals('store3', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product4'); + $product = static::getDatabase()->getDocument('product', 'product4'); $store = $product->getAttribute('store', []); $this->assertEquals('store4', $store['$id']); $this->assertArrayNotHasKey('products', $store); // Get related document - $store = $this->getDatabase()->getDocument('store', 'store1'); + $store = static::getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('products'); $this->assertEquals('product1', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store2'); + $store = static::getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('products'); $this->assertEquals('product2', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store3'); + $store = static::getDatabase()->getDocument('store', 'store3'); $products = $store->getAttribute('products'); $this->assertEquals('product3', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store4'); + $store = static::getDatabase()->getDocument('store', 'store4'); $products = $store->getAttribute('products'); $this->assertEquals('product4', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $products = $this->getDatabase()->find('product'); + $products = static::getDatabase()->find('product'); $this->assertEquals(4, \count($products)); // Select related document attributes - $product = $this->getDatabase()->findOne('product', [ + $product = static::getDatabase()->findOne('product', [ Query::select(['*', 'store.name']) ]); @@ -8829,7 +8869,7 @@ public function testManyToOneTwoWayRelationship(): void $this->assertEquals('Store 1', $product->getAttribute('store')->getAttribute('name')); $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); - $product = $this->getDatabase()->getDocument('product', 'product1', [ + $product = static::getDatabase()->getDocument('product', 'product1', [ Query::select(['*', 'store.name']) ]); @@ -8837,58 +8877,58 @@ public function testManyToOneTwoWayRelationship(): void $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); // Update root document attribute without altering relationship - $product1 = $this->getDatabase()->updateDocument( + $product1 = static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('name', 'Product 1 Updated') ); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); - $product1 = $this->getDatabase()->getDocument('product', 'product1'); + $product1 = static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); // Update inverse document attribute without altering relationship - $store1 = $this->getDatabase()->getDocument('store', 'store1'); - $store1 = $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('name', 'Store 1 Updated') ); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); // Update nested document attribute $store = $product1->getAttribute('store'); $store->setAttribute('name', 'Store 1 Updated'); - $product1 = $this->getDatabase()->updateDocument( + $product1 = static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', $store) ); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); - $product1 = $this->getDatabase()->getDocument('product', 'product1'); + $product1 = static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); // Update inverse nested document attribute $product = $store1->getAttribute('products')[0]; $product->setAttribute('name', 'Product 1 Updated'); - $store1 = $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', [$product]) ); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); // Create new document with no relationship - $product5 = $this->getDatabase()->createDocument('product', new Document([ + $product5 = static::getDatabase()->createDocument('product', new Document([ '$id' => 'product5', '$permissions' => [ Permission::read(Role::any()), @@ -8899,7 +8939,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update to relate to created document - $product5 = $this->getDatabase()->updateDocument( + $product5 = static::getDatabase()->updateDocument( 'product', $product5->getId(), $product5->setAttribute('store', new Document([ @@ -8915,11 +8955,11 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); - $product5 = $this->getDatabase()->getDocument('product', 'product5'); + $product5 = static::getDatabase()->getDocument('product', 'product5'); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); // Create new child document with no relationship - $store6 = $this->getDatabase()->createDocument('store', new Document([ + $store6 = static::getDatabase()->createDocument('store', new Document([ '$id' => 'store6', '$permissions' => [ Permission::read(Role::any()), @@ -8931,7 +8971,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update inverse to related to newly created document - $store6 = $this->getDatabase()->updateDocument( + $store6 = static::getDatabase()->updateDocument( 'store', $store6->getId(), $store6->setAttribute('products', [new Document([ @@ -8946,36 +8986,36 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); - $store6 = $this->getDatabase()->getDocument('store', 'store6'); + $store6 = static::getDatabase()->getDocument('store', 'store6'); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', 'store2') ); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', ['product1']) ); - $store2 = $this->getDatabase()->getDocument('store', 'store2'); + $store2 = static::getDatabase()->getDocument('store', 'store2'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'store', $store2->getId(), $store2->setAttribute('products', ['product1', 'product2']) ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'product', 'store', 'newStore', @@ -8983,25 +9023,25 @@ public function testManyToOneTwoWayRelationship(): void ); // Get document with new relationship key - $store = $this->getDatabase()->getDocument('store', 'store2'); + $store = static::getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('newProducts'); $this->assertEquals('product1', $products[0]['$id']); // Get inverse document with new relationship key - $product = $this->getDatabase()->getDocument('product', 'product1'); + $product = static::getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('newStore'); $this->assertEquals('store2', $store['$id']); // Reset relationships - $store1 = $this->getDatabase()->getDocument('store', 'store1'); - $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->getDocument('store', 'store1'); + static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('newProducts', ['product1']) ); // Create new document with no relationship - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store7', '$permissions' => [ Permission::read(Role::any()), @@ -9013,87 +9053,87 @@ public function testManyToOneTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('store', 'store7'); + $deleted = static::getDatabase()->deleteDocument('store', 'store7'); $this->assertEquals(true, $deleted); - $store7 = $this->getDatabase()->getDocument('store', 'store7'); + $store7 = static::getDatabase()->getDocument('store', 'store7'); $this->assertEquals(true, $store7->isEmpty()); // Try to delete child while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('store', 'store1'); + static::getDatabase()->deleteDocument('store', 'store1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Delete parent while still related to another with on delete: restrict - $result = $this->getDatabase()->deleteDocument('product', 'product5'); + $result = static::getDatabase()->deleteDocument('product', 'product5'); $this->assertEquals(true, $result); // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - $this->getDatabase()->deleteDocument('store', 'store1'); + static::getDatabase()->deleteDocument('store', 'store1'); // Check relation was set to null - $this->getDatabase()->getDocument('product', 'product1'); + static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals(null, $product1->getAttribute('newStore')); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - $this->getDatabase()->deleteDocument('store', 'store2'); + static::getDatabase()->deleteDocument('store', 'store2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('store', 'store2'); + $library = static::getDatabase()->getDocument('store', 'store2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('product', 'product2'); + $library = static::getDatabase()->getDocument('product', 'product2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'product', 'newStore' ); // Try to get document again - $products = $this->getDatabase()->getDocument('product', 'product1'); + $products = static::getDatabase()->getDocument('product', 'product1'); $store = $products->getAttribute('newStore'); $this->assertEquals(null, $store); // Try to get inverse document again - $store = $this->getDatabase()->getDocument('store', 'store1'); + $store = static::getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('newProducts'); $this->assertEquals(null, $products); } public function testManyToManyOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('playlist'); - $this->getDatabase()->createCollection('song'); + static::getDatabase()->createCollection('playlist'); + static::getDatabase()->createCollection('song'); - $this->getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'playlist', relatedCollection: 'song', type: Database::RELATION_MANY_TO_MANY, @@ -9101,7 +9141,7 @@ public function testManyToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('playlist'); + $collection = static::getDatabase()->getCollection('playlist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -9117,7 +9157,7 @@ public function testManyToManyOneWayRelationship(): void } // Create document with relationship with nested data - $playlist1 = $this->getDatabase()->createDocument('playlist', new Document([ + $playlist1 = static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist1', '$permissions' => [ Permission::read(Role::any()), @@ -9140,7 +9180,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Create document with relationship with related ID - $this->getDatabase()->createDocument('song', new Document([ + static::getDatabase()->createDocument('song', new Document([ '$id' => 'song2', '$permissions' => [ Permission::read(Role::any()), @@ -9150,7 +9190,7 @@ public function testManyToManyOneWayRelationship(): void 'name' => 'Song 2', 'length' => 140, ])); - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist2', '$permissions' => [ Permission::read(Role::any()), @@ -9164,13 +9204,13 @@ public function testManyToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); + static::getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); - $playlist1Document = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1Document = static::getDatabase()->getDocument('playlist', 'playlist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($playlist1Document->getAttribute('songs'))); - $documents = $this->getDatabase()->find('playlist', [ + $documents = static::getDatabase()->find('playlist', [ Query::select(['name']), Query::limit(1) ]); @@ -9178,29 +9218,29 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('songs', $documents[0]); // Get document with relationship - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song1', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist2'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist2'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song2', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); // Get related document - $library = $this->getDatabase()->getDocument('song', 'song1'); + $library = static::getDatabase()->getDocument('song', 'song1'); $this->assertArrayNotHasKey('songs', $library); - $library = $this->getDatabase()->getDocument('song', 'song2'); + $library = static::getDatabase()->getDocument('song', 'song2'); $this->assertArrayNotHasKey('songs', $library); - $playlists = $this->getDatabase()->find('playlist'); + $playlists = static::getDatabase()->find('playlist'); $this->assertEquals(2, \count($playlists)); // Select related document attributes - $playlist = $this->getDatabase()->findOne('playlist', [ + $playlist = static::getDatabase()->findOne('playlist', [ Query::select(['*', 'songs.name']) ]); @@ -9211,7 +9251,7 @@ public function testManyToManyOneWayRelationship(): void $this->assertEquals('Song 1', $playlist->getAttribute('songs')[0]->getAttribute('name')); $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1', [ + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1', [ Query::select(['*', 'songs.name']) ]); @@ -9219,32 +9259,32 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); // Update root document attribute without altering relationship - $playlist1 = $this->getDatabase()->updateDocument( + $playlist1 = static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('name', 'Playlist 1 Updated') ); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); // Update nested document attribute $songs = $playlist1->getAttribute('songs', []); $songs[0]->setAttribute('name', 'Song 1 Updated'); - $playlist1 = $this->getDatabase()->updateDocument( + $playlist1 = static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', $songs) ); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); // Create new document with no relationship - $playlist5 = $this->getDatabase()->createDocument('playlist', new Document([ + $playlist5 = static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist5', '$permissions' => [ Permission::read(Role::any()), @@ -9255,7 +9295,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Update to relate to created document - $playlist5 = $this->getDatabase()->updateDocument( + $playlist5 = static::getDatabase()->updateDocument( 'playlist', $playlist5->getId(), $playlist5->setAttribute('songs', [new Document([ @@ -9271,7 +9311,7 @@ public function testManyToManyOneWayRelationship(): void ); // Playlist relating to existing songs that belong to other playlists - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist6', '$permissions' => [ Permission::read(Role::any()), @@ -9287,30 +9327,30 @@ public function testManyToManyOneWayRelationship(): void ])); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); - $playlist5 = $this->getDatabase()->getDocument('playlist', 'playlist5'); + $playlist5 = static::getDatabase()->getDocument('playlist', 'playlist5'); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', ['song2']) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'playlist', 'songs', 'newSongs' ); // Get document with new relationship key - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals('song2', $songs[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist3', '$permissions' => [ Permission::read(Role::any()), @@ -9321,87 +9361,87 @@ public function testManyToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('playlist', 'playlist3'); + $deleted = static::getDatabase()->deleteDocument('playlist', 'playlist3'); $this->assertEquals(true, $deleted); - $playlist3 = $this->getDatabase()->getDocument('playlist', 'playlist3'); + $playlist3 = static::getDatabase()->getDocument('playlist', 'playlist3'); $this->assertEquals(true, $playlist3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('playlist', 'playlist1'); + static::getDatabase()->deleteDocument('playlist', 'playlist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); // Reset relationships - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('newSongs', ['song1']) ); // Delete child, will delete junction - $this->getDatabase()->deleteDocument('song', 'song1'); + static::getDatabase()->deleteDocument('song', 'song1'); // Check relation was set to null - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals(0, \count($playlist1->getAttribute('newSongs'))); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('playlist', 'playlist2'); + static::getDatabase()->deleteDocument('playlist', 'playlist2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('playlist', 'playlist2'); + $library = static::getDatabase()->getDocument('playlist', 'playlist2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('song', 'song2'); + $library = static::getDatabase()->getDocument('song', 'song2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'playlist', 'newSongs' ); // Try to get document again - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals(null, $songs); } public function testManyToManyTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('students'); - $this->getDatabase()->createCollection('classes'); + static::getDatabase()->createCollection('students'); + static::getDatabase()->createCollection('classes'); - $this->getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'students', relatedCollection: 'classes', type: Database::RELATION_MANY_TO_MANY, @@ -9409,7 +9449,7 @@ public function testManyToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('students'); + $collection = static::getDatabase()->getCollection('students'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'students') { @@ -9424,7 +9464,7 @@ public function testManyToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('classes'); + $collection = static::getDatabase()->getCollection('classes'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'classes') { @@ -9439,7 +9479,7 @@ public function testManyToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $student1 = $this->getDatabase()->createDocument('students', new Document([ + $student1 = static::getDatabase()->createDocument('students', new Document([ '$id' => 'student1', '$permissions' => [ Permission::read(Role::any()), @@ -9462,14 +9502,14 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); + static::getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); - $student1Document = $this->getDatabase()->getDocument('students', 'student1'); + $student1Document = static::getDatabase()->getDocument('students', 'student1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($student1Document->getAttribute('classes'))); // Create document with relationship with related ID - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class2', '$permissions' => [ Permission::read(Role::any()), @@ -9480,7 +9520,7 @@ public function testManyToManyTwoWayRelationship(): void 'name' => 'Class 2', 'number' => 2, ])); - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student2', '$permissions' => [ Permission::read(Role::any()), @@ -9494,7 +9534,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class3', '$permissions' => [ Permission::read(Role::any()), @@ -9515,7 +9555,7 @@ public function testManyToManyTwoWayRelationship(): void ] ], ])); - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student4', '$permissions' => [ Permission::read(Role::any()), @@ -9524,7 +9564,7 @@ public function testManyToManyTwoWayRelationship(): void ], 'name' => 'Student 4' ])); - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class4', '$permissions' => [ Permission::read(Role::any()), @@ -9540,49 +9580,49 @@ public function testManyToManyTwoWayRelationship(): void ])); // Get document with relationship - $student = $this->getDatabase()->getDocument('students', 'student1'); + $student = static::getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class1', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student2'); + $student = static::getDatabase()->getDocument('students', 'student2'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class2', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student3'); + $student = static::getDatabase()->getDocument('students', 'student3'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class3', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student4'); + $student = static::getDatabase()->getDocument('students', 'student4'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class4', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); // Get related document - $class = $this->getDatabase()->getDocument('classes', 'class1'); + $class = static::getDatabase()->getDocument('classes', 'class1'); $student = $class->getAttribute('students'); $this->assertEquals('student1', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class2'); + $class = static::getDatabase()->getDocument('classes', 'class2'); $student = $class->getAttribute('students'); $this->assertEquals('student2', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class3'); + $class = static::getDatabase()->getDocument('classes', 'class3'); $student = $class->getAttribute('students'); $this->assertEquals('student3', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class4'); + $class = static::getDatabase()->getDocument('classes', 'class4'); $student = $class->getAttribute('students'); $this->assertEquals('student4', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); // Select related document attributes - $student = $this->getDatabase()->findOne('students', [ + $student = static::getDatabase()->findOne('students', [ Query::select(['*', 'classes.name']) ]); @@ -9593,7 +9633,7 @@ public function testManyToManyTwoWayRelationship(): void $this->assertEquals('Class 1', $student->getAttribute('classes')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); - $student = $this->getDatabase()->getDocument('students', 'student1', [ + $student = static::getDatabase()->getDocument('students', 'student1', [ Query::select(['*', 'classes.name']) ]); @@ -9601,58 +9641,58 @@ public function testManyToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); // Update root document attribute without altering relationship - $student1 = $this->getDatabase()->updateDocument( + $student1 = static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('name', 'Student 1 Updated') ); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); // Update inverse root document attribute without altering relationship - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); - $class2 = $this->getDatabase()->updateDocument( + $class2 = static::getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('name', 'Class 2 Updated') ); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); // Update nested document attribute $classes = $student1->getAttribute('classes', []); $classes[0]->setAttribute('name', 'Class 1 Updated'); - $student1 = $this->getDatabase()->updateDocument( + $student1 = static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', $classes) ); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); // Update inverse nested document attribute $students = $class2->getAttribute('students', []); $students[0]->setAttribute('name', 'Student 2 Updated'); - $class2 = $this->getDatabase()->updateDocument( + $class2 = static::getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('students', $students) ); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); // Create new document with no relationship - $student5 = $this->getDatabase()->createDocument('students', new Document([ + $student5 = static::getDatabase()->createDocument('students', new Document([ '$id' => 'student5', '$permissions' => [ Permission::read(Role::any()), @@ -9663,7 +9703,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $student5 = $this->getDatabase()->updateDocument( + $student5 = static::getDatabase()->updateDocument( 'students', $student5->getId(), $student5->setAttribute('classes', [new Document([ @@ -9679,11 +9719,11 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); - $student5 = $this->getDatabase()->getDocument('students', 'student5'); + $student5 = static::getDatabase()->getDocument('students', 'student5'); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); // Create child document with no relationship - $class6 = $this->getDatabase()->createDocument('classes', new Document([ + $class6 = static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class6', '$permissions' => [ Permission::read(Role::any()), @@ -9695,7 +9735,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $class6 = $this->getDatabase()->updateDocument( + $class6 = static::getDatabase()->updateDocument( 'classes', $class6->getId(), $class6->setAttribute('students', [new Document([ @@ -9710,27 +9750,27 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); - $class6 = $this->getDatabase()->getDocument('classes', 'class6'); + $class6 = static::getDatabase()->getDocument('classes', 'class6'); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', ['class2']) ); - $class1 = $this->getDatabase()->getDocument('classes', 'class1'); + $class1 = static::getDatabase()->getDocument('classes', 'class1'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'classes', $class1->getId(), $class1->setAttribute('students', ['student1']) ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'students', 'classes', 'newClasses', @@ -9738,17 +9778,17 @@ public function testManyToManyTwoWayRelationship(): void ); // Get document with new relationship key - $students = $this->getDatabase()->getDocument('students', 'student1'); + $students = static::getDatabase()->getDocument('students', 'student1'); $classes = $students->getAttribute('newClasses'); $this->assertEquals('class2', $classes[0]['$id']); // Get inverse document with new relationship key - $class = $this->getDatabase()->getDocument('classes', 'class1'); + $class = static::getDatabase()->getDocument('classes', 'class1'); $students = $class->getAttribute('newStudents'); $this->assertEquals('student1', $students[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student7', '$permissions' => [ Permission::read(Role::any()), @@ -9759,107 +9799,107 @@ public function testManyToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('students', 'student7'); + $deleted = static::getDatabase()->deleteDocument('students', 'student7'); $this->assertEquals(true, $deleted); - $student6 = $this->getDatabase()->getDocument('students', 'student7'); + $student6 = static::getDatabase()->getDocument('students', 'student7'); $this->assertEquals(true, $student6->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('students', 'student1'); + static::getDatabase()->deleteDocument('students', 'student1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); // Reset relationships - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('newClasses', ['class1']) ); // Delete child, will delete junction - $this->getDatabase()->deleteDocument('classes', 'class1'); + static::getDatabase()->deleteDocument('classes', 'class1'); // Check relation was set to null - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals(0, \count($student1->getAttribute('newClasses'))); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('students', 'student2'); + static::getDatabase()->deleteDocument('students', 'student2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('students', 'student2'); + $library = static::getDatabase()->getDocument('students', 'student2'); $this->assertEquals(true, $library->isEmpty()); // Delete child, should not delete parent - $this->getDatabase()->deleteDocument('classes', 'class6'); + static::getDatabase()->deleteDocument('classes', 'class6'); // Check only child was deleted - $student6 = $this->getDatabase()->getDocument('students', 'student6'); + $student6 = static::getDatabase()->getDocument('students', 'student6'); $this->assertEquals(false, $student6->isEmpty()); $this->assertEmpty($student6->getAttribute('newClasses')); - $library = $this->getDatabase()->getDocument('classes', 'class2'); + $library = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'students', 'newClasses' ); // Try to get documents again - $student = $this->getDatabase()->getDocument('students', 'student1'); + $student = static::getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('newClasses'); $this->assertEquals(null, $classes); // Try to get inverse documents again - $classes = $this->getDatabase()->getDocument('classes', 'class1'); + $classes = static::getDatabase()->getDocument('classes', 'class1'); $students = $classes->getAttribute('newStudents'); $this->assertEquals(null, $students); } public function testSelectRelationshipAttributes(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('make'); - $this->getDatabase()->createCollection('model'); + static::getDatabase()->createCollection('make'); + static::getDatabase()->createCollection('model'); - $this->getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'make', relatedCollection: 'model', type: Database::RELATION_ONE_TO_MANY, id: 'models' ); - $this->getDatabase()->createDocument('make', new Document([ + static::getDatabase()->createDocument('make', new Document([ '$id' => 'ford', '$permissions' => [ Permission::read(Role::any()), @@ -9886,7 +9926,7 @@ public function testSelectRelationshipAttributes(): void ])); // Select some parent attributes, some child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', 'models.name']), ]); @@ -9908,7 +9948,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); // Select internal attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$id']), ]); @@ -9923,7 +9963,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$internalId']), ]); @@ -9938,7 +9978,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$collection']), ]); @@ -9953,7 +9993,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$createdAt']), ]); @@ -9968,7 +10008,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$updatedAt']), ]); @@ -9983,7 +10023,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$permissions']), ]); @@ -9999,7 +10039,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$permissions', $make); // Select all parent attributes, some child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['*', 'models.year']), ]); @@ -10015,7 +10055,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, all child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['*', 'models.*']), ]); @@ -10032,7 +10072,7 @@ public function testSelectRelationshipAttributes(): void // Select all parent attributes, all child attributes // Must select parent if selecting children - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['models.*']), ]); @@ -10048,7 +10088,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, no child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name']), ]); @@ -10062,20 +10102,20 @@ public function testSelectRelationshipAttributes(): void public function testNestedOneToOne_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('pattern'); - $this->getDatabase()->createCollection('shirt'); - $this->getDatabase()->createCollection('team'); + static::getDatabase()->createCollection('pattern'); + static::getDatabase()->createCollection('shirt'); + static::getDatabase()->createCollection('team'); - $this->getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'pattern', relatedCollection: 'shirt', type: Database::RELATION_ONE_TO_ONE, @@ -10083,7 +10123,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void id: 'shirt', twoWayKey: 'pattern' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'shirt', relatedCollection: 'team', type: Database::RELATION_ONE_TO_ONE, @@ -10092,7 +10132,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void twoWayKey: 'shirt' ); - $this->getDatabase()->createDocument('pattern', new Document([ + static::getDatabase()->createDocument('pattern', new Document([ '$id' => 'stripes', '$permissions' => [ Permission::read(Role::any()), @@ -10114,13 +10154,13 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $pattern = $this->getDatabase()->getDocument('pattern', 'stripes'); + $pattern = static::getDatabase()->getDocument('pattern', 'stripes'); $this->assertEquals('red', $pattern['shirt']['$id']); $this->assertArrayNotHasKey('pattern', $pattern['shirt']); $this->assertEquals('reds', $pattern['shirt']['team']['$id']); $this->assertArrayNotHasKey('shirt', $pattern['shirt']['team']); - $this->getDatabase()->createDocument('team', new Document([ + static::getDatabase()->createDocument('team', new Document([ '$id' => 'blues', '$permissions' => [ Permission::read(Role::any()), @@ -10142,7 +10182,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $team = $this->getDatabase()->getDocument('team', 'blues'); + $team = static::getDatabase()->getDocument('team', 'blues'); $this->assertEquals('blue', $team['shirt']['$id']); $this->assertArrayNotHasKey('team', $team['shirt']); $this->assertEquals('plain', $team['shirt']['pattern']['$id']); @@ -10151,20 +10191,20 @@ public function testNestedOneToOne_OneToOneRelationship(): void public function testNestedOneToOne_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('teachers'); - $this->getDatabase()->createCollection('classrooms'); - $this->getDatabase()->createCollection('children'); + static::getDatabase()->createCollection('teachers'); + static::getDatabase()->createCollection('classrooms'); + static::getDatabase()->createCollection('children'); - $this->getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'teachers', relatedCollection: 'classrooms', type: Database::RELATION_ONE_TO_ONE, @@ -10172,7 +10212,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void id: 'classroom', twoWayKey: 'teacher' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'classrooms', relatedCollection: 'children', type: Database::RELATION_ONE_TO_MANY, @@ -10180,7 +10220,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void twoWayKey: 'classroom' ); - $this->getDatabase()->createDocument('teachers', new Document([ + static::getDatabase()->createDocument('teachers', new Document([ '$id' => 'teacher1', '$permissions' => [ Permission::read(Role::any()), @@ -10211,14 +10251,14 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $teacher1 = $this->getDatabase()->getDocument('teachers', 'teacher1'); + $teacher1 = static::getDatabase()->getDocument('teachers', 'teacher1'); $this->assertEquals('classroom1', $teacher1['classroom']['$id']); $this->assertArrayNotHasKey('teacher', $teacher1['classroom']); $this->assertEquals(2, \count($teacher1['classroom']['children'])); $this->assertEquals('Child 1', $teacher1['classroom']['children'][0]['name']); $this->assertEquals('Child 2', $teacher1['classroom']['children'][1]['name']); - $this->getDatabase()->createDocument('children', new Document([ + static::getDatabase()->createDocument('children', new Document([ '$id' => 'child3', '$permissions' => [ Permission::read(Role::any()), @@ -10240,7 +10280,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $child3 = $this->getDatabase()->getDocument('children', 'child3'); + $child3 = static::getDatabase()->getDocument('children', 'child3'); $this->assertEquals('classroom2', $child3['classroom']['$id']); $this->assertArrayNotHasKey('children', $child3['classroom']); $this->assertEquals('teacher2', $child3['classroom']['teacher']['$id']); @@ -10249,20 +10289,20 @@ public function testNestedOneToOne_OneToManyRelationship(): void public function testNestedOneToOne_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('users'); - $this->getDatabase()->createCollection('profiles'); - $this->getDatabase()->createCollection('avatars'); + static::getDatabase()->createCollection('users'); + static::getDatabase()->createCollection('profiles'); + static::getDatabase()->createCollection('avatars'); - $this->getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'users', relatedCollection: 'profiles', type: Database::RELATION_ONE_TO_ONE, @@ -10270,7 +10310,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'profile', twoWayKey: 'user' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'profiles', relatedCollection: 'avatars', type: Database::RELATION_MANY_TO_ONE, @@ -10278,7 +10318,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'avatar', ); - $this->getDatabase()->createDocument('users', new Document([ + static::getDatabase()->createDocument('users', new Document([ '$id' => 'user1', '$permissions' => [ Permission::read(Role::any()), @@ -10300,13 +10340,13 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $user1 = $this->getDatabase()->getDocument('users', 'user1'); + $user1 = static::getDatabase()->getDocument('users', 'user1'); $this->assertEquals('profile1', $user1['profile']['$id']); $this->assertArrayNotHasKey('user', $user1['profile']); $this->assertEquals('avatar1', $user1['profile']['avatar']['$id']); $this->assertArrayNotHasKey('profile', $user1['profile']['avatar']); - $this->getDatabase()->createDocument('avatars', new Document([ + static::getDatabase()->createDocument('avatars', new Document([ '$id' => 'avatar2', '$permissions' => [ Permission::read(Role::any()), @@ -10330,7 +10370,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $avatar2 = $this->getDatabase()->getDocument('avatars', 'avatar2'); + $avatar2 = static::getDatabase()->getDocument('avatars', 'avatar2'); $this->assertEquals('profile2', $avatar2['profiles'][0]['$id']); $this->assertArrayNotHasKey('avatars', $avatar2['profiles'][0]); $this->assertEquals('user2', $avatar2['profiles'][0]['user']['$id']); @@ -10339,20 +10379,20 @@ public function testNestedOneToOne_ManyToOneRelationship(): void public function testNestedOneToOne_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('addresses'); - $this->getDatabase()->createCollection('houses'); - $this->getDatabase()->createCollection('buildings'); + static::getDatabase()->createCollection('addresses'); + static::getDatabase()->createCollection('houses'); + static::getDatabase()->createCollection('buildings'); - $this->getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'addresses', relatedCollection: 'houses', type: Database::RELATION_ONE_TO_ONE, @@ -10360,14 +10400,14 @@ public function testNestedOneToOne_ManyToManyRelationship(): void id: 'house', twoWayKey: 'address' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'houses', relatedCollection: 'buildings', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createDocument('addresses', new Document([ + static::getDatabase()->createDocument('addresses', new Document([ '$id' => 'address1', '$permissions' => [ Permission::read(Role::any()), @@ -10398,7 +10438,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void ], ])); - $address1 = $this->getDatabase()->getDocument('addresses', 'address1'); + $address1 = static::getDatabase()->getDocument('addresses', 'address1'); $this->assertEquals('house1', $address1['house']['$id']); $this->assertArrayNotHasKey('address', $address1['house']); $this->assertEquals('building1', $address1['house']['buildings'][0]['$id']); @@ -10406,7 +10446,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][0]); $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][1]); - $this->getDatabase()->createDocument('buildings', new Document([ + static::getDatabase()->createDocument('buildings', new Document([ '$id' => 'building3', '$permissions' => [ Permission::read(Role::any()), @@ -10433,27 +10473,27 @@ public function testNestedOneToOne_ManyToManyRelationship(): void public function testNestedOneToMany_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('countries'); - $this->getDatabase()->createCollection('cities'); - $this->getDatabase()->createCollection('mayors'); + static::getDatabase()->createCollection('countries'); + static::getDatabase()->createCollection('cities'); + static::getDatabase()->createCollection('mayors'); - $this->getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'countries', relatedCollection: 'cities', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'country' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cities', relatedCollection: 'mayors', type: Database::RELATION_ONE_TO_ONE, @@ -10462,7 +10502,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void twoWayKey: 'city' ); - $this->getDatabase()->createDocument('countries', new Document([ + static::getDatabase()->createDocument('countries', new Document([ '$id' => 'country1', '$permissions' => [ Permission::read(Role::any()), @@ -10503,26 +10543,26 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::limit(1) ]); $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['*']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['*', 'cities.*', 'cities.mayor.*']), Query::limit(1) ]); @@ -10530,12 +10570,12 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); // Insert docs to cache: - $country1 = $this->getDatabase()->getDocument('countries', 'country1'); - $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = static::getDatabase()->getDocument('countries', 'country1'); + $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); $this->assertEquals('City 1', $mayor1['city']['name']); $this->assertEquals('City 1', $country1['cities'][0]['name']); - $this->getDatabase()->updateDocument('cities', 'city1', new Document([ + static::getDatabase()->updateDocument('cities', 'city1', new Document([ '$id' => 'city1', '$collection' => 'cities', 'name' => 'City 1 updated', @@ -10546,8 +10586,8 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); - $country1 = $this->getDatabase()->getDocument('countries', 'country1'); + $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = static::getDatabase()->getDocument('countries', 'country1'); $this->assertEquals('City 1 updated', $mayor1['city']['name']); $this->assertEquals('City 1 updated', $country1['cities'][0]['name']); @@ -10558,7 +10598,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertArrayNotHasKey('city', $country1['cities'][0]['mayor']); $this->assertArrayNotHasKey('city', $country1['cities'][1]['mayor']); - $this->getDatabase()->createDocument('mayors', new Document([ + static::getDatabase()->createDocument('mayors', new Document([ '$id' => 'mayor3', '$permissions' => [ Permission::read(Role::any()), @@ -10580,7 +10620,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $country2 = $this->getDatabase()->getDocument('countries', 'country2'); + $country2 = static::getDatabase()->getDocument('countries', 'country2'); $this->assertEquals('city3', $country2['cities'][0]['$id']); $this->assertEquals('mayor3', $country2['cities'][0]['mayor']['$id']); $this->assertArrayNotHasKey('country', $country2['cities'][0]); @@ -10589,27 +10629,27 @@ public function testNestedOneToMany_OneToOneRelationship(): void public function testNestedOneToMany_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('dormitories'); - $this->getDatabase()->createCollection('occupants'); - $this->getDatabase()->createCollection('pets'); + static::getDatabase()->createCollection('dormitories'); + static::getDatabase()->createCollection('occupants'); + static::getDatabase()->createCollection('pets'); - $this->getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'dormitories', relatedCollection: 'occupants', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'dormitory' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'occupants', relatedCollection: 'pets', type: Database::RELATION_ONE_TO_MANY, @@ -10617,7 +10657,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void twoWayKey: 'occupant' ); - $this->getDatabase()->createDocument('dormitories', new Document([ + static::getDatabase()->createDocument('dormitories', new Document([ '$id' => 'dormitory1', '$permissions' => [ Permission::read(Role::any()), @@ -10673,7 +10713,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $dormitory1 = $this->getDatabase()->getDocument('dormitories', 'dormitory1'); + $dormitory1 = static::getDatabase()->getDocument('dormitories', 'dormitory1'); $this->assertEquals('occupant1', $dormitory1['occupants'][0]['$id']); $this->assertEquals('occupant2', $dormitory1['occupants'][1]['$id']); $this->assertEquals('pet1', $dormitory1['occupants'][0]['pets'][0]['$id']); @@ -10687,7 +10727,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][0]); $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][1]); - $this->getDatabase()->createDocument('pets', new Document([ + static::getDatabase()->createDocument('pets', new Document([ '$id' => 'pet5', '$permissions' => [ Permission::read(Role::any()), @@ -10709,7 +10749,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $pet5 = $this->getDatabase()->getDocument('pets', 'pet5'); + $pet5 = static::getDatabase()->getDocument('pets', 'pet5'); $this->assertEquals('occupant3', $pet5['occupant']['$id']); $this->assertEquals('dormitory2', $pet5['occupant']['dormitory']['$id']); $this->assertArrayNotHasKey('pets', $pet5['occupant']); @@ -10718,26 +10758,26 @@ public function testNestedOneToMany_OneToManyRelationship(): void public function testNestedOneToMany_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('home'); - $this->getDatabase()->createCollection('renters'); - $this->getDatabase()->createCollection('floors'); + static::getDatabase()->createCollection('home'); + static::getDatabase()->createCollection('renters'); + static::getDatabase()->createCollection('floors'); - $this->getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'home', relatedCollection: 'renters', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'renters', relatedCollection: 'floors', type: Database::RELATION_MANY_TO_ONE, @@ -10745,7 +10785,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void id: 'floor' ); - $this->getDatabase()->createDocument('home', new Document([ + static::getDatabase()->createDocument('home', new Document([ '$id' => 'home1', '$permissions' => [ Permission::read(Role::any()), @@ -10769,13 +10809,13 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $home1 = $this->getDatabase()->getDocument('home', 'home1'); + $home1 = static::getDatabase()->getDocument('home', 'home1'); $this->assertEquals('renter1', $home1['renters'][0]['$id']); $this->assertEquals('floor1', $home1['renters'][0]['floor']['$id']); $this->assertArrayNotHasKey('home', $home1['renters'][0]); $this->assertArrayNotHasKey('renters', $home1['renters'][0]['floor']); - $this->getDatabase()->createDocument('floors', new Document([ + static::getDatabase()->createDocument('floors', new Document([ '$id' => 'floor2', '$permissions' => [ Permission::read(Role::any()), @@ -10799,7 +10839,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $floor2 = $this->getDatabase()->getDocument('floors', 'floor2'); + $floor2 = static::getDatabase()->getDocument('floors', 'floor2'); $this->assertEquals('renter2', $floor2['renters'][0]['$id']); $this->assertArrayNotHasKey('floor', $floor2['renters'][0]); $this->assertEquals('home2', $floor2['renters'][0]['home']['$id']); @@ -10808,34 +10848,34 @@ public function testNestedOneToMany_ManyToOneRelationship(): void public function testNestedOneToMany_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('owners'); - $this->getDatabase()->createCollection('cats'); - $this->getDatabase()->createCollection('toys'); + static::getDatabase()->createCollection('owners'); + static::getDatabase()->createCollection('cats'); + static::getDatabase()->createCollection('toys'); - $this->getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'owners', relatedCollection: 'cats', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'owner' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cats', relatedCollection: 'toys', type: Database::RELATION_MANY_TO_MANY, twoWay: true ); - $this->getDatabase()->createDocument('owners', new Document([ + static::getDatabase()->createDocument('owners', new Document([ '$id' => 'owner1', '$permissions' => [ Permission::read(Role::any()), @@ -10861,13 +10901,13 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $owner1 = $this->getDatabase()->getDocument('owners', 'owner1'); + $owner1 = static::getDatabase()->getDocument('owners', 'owner1'); $this->assertEquals('cat1', $owner1['cats'][0]['$id']); $this->assertArrayNotHasKey('owner', $owner1['cats'][0]); $this->assertEquals('toy1', $owner1['cats'][0]['toys'][0]['$id']); $this->assertArrayNotHasKey('cats', $owner1['cats'][0]['toys'][0]); - $this->getDatabase()->createDocument('toys', new Document([ + static::getDatabase()->createDocument('toys', new Document([ '$id' => 'toy2', '$permissions' => [ Permission::read(Role::any()), @@ -10891,7 +10931,7 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $toy2 = $this->getDatabase()->getDocument('toys', 'toy2'); + $toy2 = static::getDatabase()->getDocument('toys', 'toy2'); $this->assertEquals('cat2', $toy2['cats'][0]['$id']); $this->assertArrayNotHasKey('toys', $toy2['cats'][0]); $this->assertEquals('owner2', $toy2['cats'][0]['owner']['$id']); @@ -10900,27 +10940,27 @@ public function testNestedOneToMany_ManyToManyRelationship(): void public function testNestedManyToOne_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('towns'); - $this->getDatabase()->createCollection('homelands'); - $this->getDatabase()->createCollection('capitals'); + static::getDatabase()->createCollection('towns'); + static::getDatabase()->createCollection('homelands'); + static::getDatabase()->createCollection('capitals'); - $this->getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'towns', relatedCollection: 'homelands', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'homeland' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'homelands', relatedCollection: 'capitals', type: Database::RELATION_ONE_TO_ONE, @@ -10929,7 +10969,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void twoWayKey: 'homeland' ); - $this->getDatabase()->createDocument('towns', new Document([ + static::getDatabase()->createDocument('towns', new Document([ '$id' => 'town1', '$permissions' => [ Permission::read(Role::any()), @@ -10951,13 +10991,13 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $town1 = $this->getDatabase()->getDocument('towns', 'town1'); + $town1 = static::getDatabase()->getDocument('towns', 'town1'); $this->assertEquals('homeland1', $town1['homeland']['$id']); $this->assertArrayNotHasKey('towns', $town1['homeland']); $this->assertEquals('capital1', $town1['homeland']['capital']['$id']); $this->assertArrayNotHasKey('homeland', $town1['homeland']['capital']); - $this->getDatabase()->createDocument('capitals', new Document([ + static::getDatabase()->createDocument('capitals', new Document([ '$id' => 'capital2', '$permissions' => [ Permission::read(Role::any()), @@ -10988,7 +11028,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $capital2 = $this->getDatabase()->getDocument('capitals', 'capital2'); + $capital2 = static::getDatabase()->getDocument('capitals', 'capital2'); $this->assertEquals('homeland2', $capital2['homeland']['$id']); $this->assertArrayNotHasKey('capital', $capital2['homeland']); $this->assertEquals(2, \count($capital2['homeland']['towns'])); @@ -10998,27 +11038,27 @@ public function testNestedManyToOne_OneToOneRelationship(): void public function testNestedManyToOne_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('players'); - $this->getDatabase()->createCollection('teams'); - $this->getDatabase()->createCollection('supporters'); + static::getDatabase()->createCollection('players'); + static::getDatabase()->createCollection('teams'); + static::getDatabase()->createCollection('supporters'); - $this->getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'players', relatedCollection: 'teams', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'team' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'teams', relatedCollection: 'supporters', type: Database::RELATION_ONE_TO_MANY, @@ -11027,7 +11067,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void twoWayKey: 'team' ); - $this->getDatabase()->createDocument('players', new Document([ + static::getDatabase()->createDocument('players', new Document([ '$id' => 'player1', '$permissions' => [ Permission::read(Role::any()), @@ -11058,14 +11098,14 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $player1 = $this->getDatabase()->getDocument('players', 'player1'); + $player1 = static::getDatabase()->getDocument('players', 'player1'); $this->assertEquals('team1', $player1['team']['$id']); $this->assertArrayNotHasKey('players', $player1['team']); $this->assertEquals(2, \count($player1['team']['supporters'])); $this->assertEquals('supporter1', $player1['team']['supporters'][0]['$id']); $this->assertEquals('supporter2', $player1['team']['supporters'][1]['$id']); - $this->getDatabase()->createDocument('supporters', new Document([ + static::getDatabase()->createDocument('supporters', new Document([ '$id' => 'supporter3', '$permissions' => [ Permission::read(Role::any()), @@ -11096,7 +11136,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $supporter3 = $this->getDatabase()->getDocument('supporters', 'supporter3'); + $supporter3 = static::getDatabase()->getDocument('supporters', 'supporter3'); $this->assertEquals('team2', $supporter3['team']['$id']); $this->assertArrayNotHasKey('supporters', $supporter3['team']); $this->assertEquals(2, \count($supporter3['team']['players'])); @@ -11106,27 +11146,27 @@ public function testNestedManyToOne_OneToManyRelationship(): void public function testNestedManyToOne_ManyToOne(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('cows'); - $this->getDatabase()->createCollection('farms'); - $this->getDatabase()->createCollection('farmer'); + static::getDatabase()->createCollection('cows'); + static::getDatabase()->createCollection('farms'); + static::getDatabase()->createCollection('farmer'); - $this->getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cows', relatedCollection: 'farms', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'farm' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'farms', relatedCollection: 'farmer', type: Database::RELATION_MANY_TO_ONE, @@ -11134,7 +11174,7 @@ public function testNestedManyToOne_ManyToOne(): void id: 'farmer' ); - $this->getDatabase()->createDocument('cows', new Document([ + static::getDatabase()->createDocument('cows', new Document([ '$id' => 'cow1', '$permissions' => [ Permission::read(Role::any()), @@ -11156,13 +11196,13 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $cow1 = $this->getDatabase()->getDocument('cows', 'cow1'); + $cow1 = static::getDatabase()->getDocument('cows', 'cow1'); $this->assertEquals('farm1', $cow1['farm']['$id']); $this->assertArrayNotHasKey('cows', $cow1['farm']); $this->assertEquals('farmer1', $cow1['farm']['farmer']['$id']); $this->assertArrayNotHasKey('farms', $cow1['farm']['farmer']); - $this->getDatabase()->createDocument('farmer', new Document([ + static::getDatabase()->createDocument('farmer', new Document([ '$id' => 'farmer2', '$permissions' => [ Permission::read(Role::any()), @@ -11195,7 +11235,7 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $farmer2 = $this->getDatabase()->getDocument('farmer', 'farmer2'); + $farmer2 = static::getDatabase()->getDocument('farmer', 'farmer2'); $this->assertEquals('farm2', $farmer2['farms'][0]['$id']); $this->assertArrayNotHasKey('farmer', $farmer2['farms'][0]); $this->assertEquals(2, \count($farmer2['farms'][0]['cows'])); @@ -11205,34 +11245,34 @@ public function testNestedManyToOne_ManyToOne(): void public function testNestedManyToOne_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('books'); - $this->getDatabase()->createCollection('entrants'); - $this->getDatabase()->createCollection('rooms'); + static::getDatabase()->createCollection('books'); + static::getDatabase()->createCollection('entrants'); + static::getDatabase()->createCollection('rooms'); - $this->getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'books', relatedCollection: 'entrants', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'entrant' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'entrants', relatedCollection: 'rooms', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createDocument('books', new Document([ + static::getDatabase()->createDocument('books', new Document([ '$id' => 'book1', '$permissions' => [ Permission::read(Role::any()), @@ -11263,7 +11303,7 @@ public function testNestedManyToOne_ManyToManyRelationship(): void ], ])); - $book1 = $this->getDatabase()->getDocument('books', 'book1'); + $book1 = static::getDatabase()->getDocument('books', 'book1'); $this->assertEquals('entrant1', $book1['entrant']['$id']); $this->assertArrayNotHasKey('books', $book1['entrant']); $this->assertEquals(2, \count($book1['entrant']['rooms'])); @@ -11273,26 +11313,26 @@ public function testNestedManyToOne_ManyToManyRelationship(): void public function testNestedManyToMany_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('stones'); - $this->getDatabase()->createCollection('hearths'); - $this->getDatabase()->createCollection('plots'); + static::getDatabase()->createCollection('stones'); + static::getDatabase()->createCollection('hearths'); + static::getDatabase()->createCollection('plots'); - $this->getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'stones', relatedCollection: 'hearths', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'hearths', relatedCollection: 'plots', type: Database::RELATION_ONE_TO_ONE, @@ -11301,7 +11341,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void twoWayKey: 'hearth' ); - $this->getDatabase()->createDocument('stones', new Document([ + static::getDatabase()->createDocument('stones', new Document([ '$id' => 'stone1', '$permissions' => [ Permission::read(Role::any()), @@ -11339,7 +11379,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $stone1 = $this->getDatabase()->getDocument('stones', 'stone1'); + $stone1 = static::getDatabase()->getDocument('stones', 'stone1'); $this->assertEquals(2, \count($stone1['hearths'])); $this->assertEquals('hearth1', $stone1['hearths'][0]['$id']); $this->assertEquals('hearth2', $stone1['hearths'][1]['$id']); @@ -11348,7 +11388,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void $this->assertEquals('plot2', $stone1['hearths'][1]['plot']['$id']); $this->assertArrayNotHasKey('hearth', $stone1['hearths'][0]['plot']); - $this->getDatabase()->createDocument('plots', new Document([ + static::getDatabase()->createDocument('plots', new Document([ '$id' => 'plot3', '$permissions' => [ Permission::read(Role::any()), @@ -11372,7 +11412,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $plot3 = $this->getDatabase()->getDocument('plots', 'plot3'); + $plot3 = static::getDatabase()->getDocument('plots', 'plot3'); $this->assertEquals('hearth3', $plot3['hearth']['$id']); $this->assertArrayNotHasKey('plot', $plot3['hearth']); $this->assertEquals('stone2', $plot3['hearth']['stones'][0]['$id']); @@ -11381,26 +11421,26 @@ public function testNestedManyToMany_OneToOneRelationship(): void public function testNestedManyToMany_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('groups'); - $this->getDatabase()->createCollection('tounaments'); - $this->getDatabase()->createCollection('prizes'); + static::getDatabase()->createCollection('groups'); + static::getDatabase()->createCollection('tounaments'); + static::getDatabase()->createCollection('prizes'); - $this->getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'groups', relatedCollection: 'tounaments', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'tounaments', relatedCollection: 'prizes', type: Database::RELATION_ONE_TO_MANY, @@ -11465,7 +11505,7 @@ public function testNestedManyToMany_OneToManyRelationship(): void ], ])); - $group1 = $this->getDatabase()->getDocument('groups', 'group1'); + $group1 = static::getDatabase()->getDocument('groups', 'group1'); $this->assertEquals(2, \count($group1['tounaments'])); $this->assertEquals('tounament1', $group1['tounaments'][0]['$id']); $this->assertEquals('tounament2', $group1['tounaments'][1]['$id']); @@ -11478,26 +11518,26 @@ public function testNestedManyToMany_OneToManyRelationship(): void public function testNestedManyToMany_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('platforms'); - $this->getDatabase()->createCollection('games'); - $this->getDatabase()->createCollection('publishers'); + static::getDatabase()->createCollection('platforms'); + static::getDatabase()->createCollection('games'); + static::getDatabase()->createCollection('publishers'); - $this->getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'platforms', relatedCollection: 'games', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'games', relatedCollection: 'publishers', type: Database::RELATION_MANY_TO_ONE, @@ -11506,7 +11546,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void twoWayKey: 'games' ); - $this->getDatabase()->createDocument('platforms', new Document([ + static::getDatabase()->createDocument('platforms', new Document([ '$id' => 'platform1', '$permissions' => [ Permission::read(Role::any()), @@ -11544,7 +11584,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ] ])); - $platform1 = $this->getDatabase()->getDocument('platforms', 'platform1'); + $platform1 = static::getDatabase()->getDocument('platforms', 'platform1'); $this->assertEquals(2, \count($platform1['games'])); $this->assertEquals('game1', $platform1['games'][0]['$id']); $this->assertEquals('game2', $platform1['games'][1]['$id']); @@ -11553,7 +11593,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void $this->assertEquals('publisher2', $platform1['games'][1]['publisher']['$id']); $this->assertArrayNotHasKey('games', $platform1['games'][0]['publisher']); - $this->getDatabase()->createDocument('publishers', new Document([ + static::getDatabase()->createDocument('publishers', new Document([ '$id' => 'publisher3', '$permissions' => [ Permission::read(Role::any()), @@ -11579,7 +11619,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ], ])); - $publisher3 = $this->getDatabase()->getDocument('publishers', 'publisher3'); + $publisher3 = static::getDatabase()->getDocument('publishers', 'publisher3'); $this->assertEquals(1, \count($publisher3['games'])); $this->assertEquals('game3', $publisher3['games'][0]['$id']); $this->assertArrayNotHasKey('publisher', $publisher3['games'][0]); @@ -11589,26 +11629,26 @@ public function testNestedManyToMany_ManyToOneRelationship(): void public function testNestedManyToMany_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('sauces'); - $this->getDatabase()->createCollection('pizzas'); - $this->getDatabase()->createCollection('toppings'); + static::getDatabase()->createCollection('sauces'); + static::getDatabase()->createCollection('pizzas'); + static::getDatabase()->createCollection('toppings'); - $this->getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'sauces', relatedCollection: 'pizzas', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'pizzas', relatedCollection: 'toppings', type: Database::RELATION_MANY_TO_MANY, @@ -11617,7 +11657,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void twoWayKey: 'pizzas' ); - $this->getDatabase()->createDocument('sauces', new Document([ + static::getDatabase()->createDocument('sauces', new Document([ '$id' => 'sauce1', '$permissions' => [ Permission::read(Role::any()), @@ -11673,7 +11713,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void ] ])); - $sauce1 = $this->getDatabase()->getDocument('sauces', 'sauce1'); + $sauce1 = static::getDatabase()->getDocument('sauces', 'sauce1'); $this->assertEquals(2, \count($sauce1['pizzas'])); $this->assertEquals('pizza1', $sauce1['pizzas'][0]['$id']); $this->assertEquals('pizza2', $sauce1['pizzas'][1]['$id']); @@ -11690,20 +11730,20 @@ public function testNestedManyToMany_ManyToManyRelationship(): void public function testInheritRelationshipPermissions(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'lawns', relatedCollection: 'trees', type: Database::RELATION_ONE_TO_MANY, @@ -11711,7 +11751,7 @@ public function testInheritRelationshipPermissions(): void twoWayKey: 'lawn', onDelete: Database::RELATION_MUTATE_CASCADE, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'trees', relatedCollection: 'birds', type: Database::RELATION_MANY_TO_MANY, @@ -11726,7 +11766,7 @@ public function testInheritRelationshipPermissions(): void Permission::delete(Role::user('user2')), ]; - $this->getDatabase()->createDocument('lawns', new Document([ + static::getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn1', '$permissions' => $permissions, 'name' => 'Lawn 1', @@ -11748,13 +11788,13 @@ public function testInheritRelationshipPermissions(): void ], ])); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals($permissions, $lawn1->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][1]->getPermissions()); - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals($permissions, $tree1->getPermissions()); $this->assertEquals($permissions, $tree1['lawn']->getPermissions()); $this->assertEquals($permissions, $tree1['birds'][0]->getPermissions()); @@ -11766,18 +11806,18 @@ public function testInheritRelationshipPermissions(): void */ public function testEnforceRelationshipPermissions(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); // Try update root document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'lawns', $lawn1->getId(), $lawn1->setAttribute('name', 'Lawn 1 Updated') @@ -11789,7 +11829,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete root document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'lawns', $lawn1->getId(), ); @@ -11798,11 +11838,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); // Try update nested document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -11814,7 +11854,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete nested document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); @@ -11823,11 +11863,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); + $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -11839,7 +11879,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete multi-level nested document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); @@ -11848,12 +11888,12 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - self::$authorization->addRole(Role::user('user1')->toString()); + Authorization::setRole(Role::user('user1')->toString()); - $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); + $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document - $bird1 = $this->getDatabase()->updateDocument( + $bird1 = static::getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -11861,20 +11901,20 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Bird 1 Updated', $bird1['name']); - self::$authorization->addRole(Role::user('user2')->toString()); + Authorization::setRole(Role::user('user2')->toString()); // Try delete multi-level nested document - $deleted = $this->getDatabase()->deleteDocument( + $deleted = static::getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); $this->assertEquals(true, $deleted); - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals(1, count($tree1['birds'])); // Try update nested document - $tree1 = $this->getDatabase()->updateDocument( + $tree1 = static::getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -11883,17 +11923,17 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Tree 1 Updated', $tree1['name']); // Try delete nested document - $deleted = $this->getDatabase()->deleteDocument( + $deleted = static::getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); $this->assertEquals(true, $deleted); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals(0, count($lawn1['trees'])); // Create document with no permissions - $this->getDatabase()->createDocument('lawns', new Document([ + static::getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn2', 'name' => 'Lawn 2', 'trees' => [ @@ -11910,19 +11950,19 @@ public function testEnforceRelationshipPermissions(): void ], ])); - $lawn2 = $this->getDatabase()->getDocument('lawns', 'lawn2'); + $lawn2 = static::getDatabase()->getDocument('lawns', 'lawn2'); $this->assertEquals(true, $lawn2->isEmpty()); - $tree2 = $this->getDatabase()->getDocument('trees', 'tree2'); + $tree2 = static::getDatabase()->getDocument('trees', 'tree2'); $this->assertEquals(true, $tree2->isEmpty()); - $bird3 = $this->getDatabase()->getDocument('birds', 'bird3'); + $bird3 = static::getDatabase()->getDocument('birds', 'bird3'); $this->assertEquals(true, $bird3->isEmpty()); } public function testExceedMaxDepthOneToMany(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -11932,24 +11972,24 @@ public function testExceedMaxDepthOneToMany(): void $level3Collection = 'level3OneToMany'; $level4Collection = 'level4OneToMany'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, @@ -11957,7 +11997,7 @@ public function testExceedMaxDepthOneToMany(): void ); // Exceed create depth - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -11986,13 +12026,13 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey('level4', $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); $this->assertTrue($level4->isEmpty()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertEquals(1, count($level1[$level2Collection])); $this->assertEquals('level2', $level1[$level2Collection][0]->getId()); $this->assertEquals(1, count($level1[$level2Collection][0][$level3Collection])); @@ -12001,7 +12041,7 @@ public function testExceedMaxDepthOneToMany(): void // Exceed update depth - $level1 = $this->getDatabase()->updateDocument( + $level1 = static::getDatabase()->updateDocument( $level1Collection, 'level1', $level1 @@ -12026,15 +12066,15 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3new'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3new'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4new'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4new'); $this->assertTrue($level4->isEmpty()); } public function testExceedMaxDepthOneToOne(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12044,24 +12084,24 @@ public function testExceedMaxDepthOneToOne(): void $level3Collection = 'level3OneToOne'; $level4Collection = 'level4OneToOne'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, @@ -12069,7 +12109,7 @@ public function testExceedMaxDepthOneToOne(): void ); // Exceed create depth - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12092,18 +12132,18 @@ public function testExceedMaxDepthOneToOne(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12113,7 +12153,7 @@ public function testExceedMaxDepthOneToOne(): void public function testExceedMaxDepthOneToOneNull(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12123,31 +12163,31 @@ public function testExceedMaxDepthOneToOneNull(): void $level3Collection = 'level3OneToOneNull'; $level4Collection = 'level4OneToOneNull'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12170,20 +12210,20 @@ public function testExceedMaxDepthOneToOneNull(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12193,7 +12233,7 @@ public function testExceedMaxDepthOneToOneNull(): void public function testExceedMaxDepthManyToOneParent(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12203,31 +12243,31 @@ public function testExceedMaxDepthManyToOneParent(): void $level3Collection = 'level3ManyToOneParent'; $level4Collection = 'level4ManyToOneParent'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12250,20 +12290,20 @@ public function testExceedMaxDepthManyToOneParent(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12273,7 +12313,7 @@ public function testExceedMaxDepthManyToOneParent(): void public function testExceedMaxDepthOneToManyChild(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12283,31 +12323,31 @@ public function testExceedMaxDepthOneToManyChild(): void $level3Collection = 'level3OneToManyChild'; $level4Collection = 'level4OneToManyChild'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12336,23 +12376,23 @@ public function testExceedMaxDepthOneToManyChild(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); // Create level 4 document $level3->setAttribute($level4Collection, [new Document([ '$id' => 'level4', ])]); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Verify level 4 document is set - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertArrayHasKey($level4Collection, $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Exceed fetch depth - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); $this->assertArrayHasKey($level3Collection, $level4); $this->assertEquals('level3', $level4[$level3Collection]->getId()); $this->assertArrayHasKey($level2Collection, $level4[$level3Collection]); @@ -12362,7 +12402,7 @@ public function testExceedMaxDepthOneToManyChild(): void public function testCreateRelationshipMissingCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12370,7 +12410,7 @@ public function testCreateRelationshipMissingCollection(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Collection not found'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'missing', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -12380,17 +12420,17 @@ public function testCreateRelationshipMissingCollection(): void public function testCreateRelationshipMissingRelatedCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test'); + static::getDatabase()->createCollection('test'); $this->expectException(Exception::class); $this->expectExceptionMessage('Related collection not found'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -12400,15 +12440,15 @@ public function testCreateRelationshipMissingRelatedCollection(): void public function testCreateDuplicateRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test1'); - $this->getDatabase()->createCollection('test2'); + static::getDatabase()->createCollection('test1'); + static::getDatabase()->createCollection('test2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -12418,7 +12458,7 @@ public function testCreateDuplicateRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute already exists'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -12428,18 +12468,18 @@ public function testCreateDuplicateRelationship(): void public function testCreateInvalidRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test3'); - $this->getDatabase()->createCollection('test4'); + static::getDatabase()->createCollection('test3'); + static::getDatabase()->createCollection('test4'); $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship type'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test3', relatedCollection: 'test4', type: 'invalid', @@ -12504,7 +12544,7 @@ public function testOneToManyAndManyToOneDeleteRelationship(): void public function testDeleteMissingRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12512,20 +12552,20 @@ public function testDeleteMissingRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute not found'); - $this->getDatabase()->deleteRelationship('test', 'test2'); + static::getDatabase()->deleteRelationship('test', 'test2'); } public function testCreateInvalidIntValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('invalid1'); - $this->getDatabase()->createCollection('invalid2'); + static::getDatabase()->createCollection('invalid1'); + static::getDatabase()->createCollection('invalid2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_ONE, @@ -12535,7 +12575,7 @@ public function testCreateInvalidIntValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => 10, ])); @@ -12546,7 +12586,7 @@ public function testCreateInvalidIntValueRelationship(): void */ public function testCreateInvalidObjectValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12554,7 +12594,7 @@ public function testCreateInvalidObjectValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => new \stdClass(), ])); @@ -12565,12 +12605,12 @@ public function testCreateInvalidObjectValueRelationship(): void */ public function testCreateInvalidArrayIntValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_MANY, @@ -12582,7 +12622,7 @@ public function testCreateInvalidArrayIntValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid3' => [10], ])); @@ -12590,21 +12630,21 @@ public function testCreateInvalidArrayIntValueRelationship(): void public function testCreateEmptyValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('null1'); - $this->getDatabase()->createCollection('null2'); + static::getDatabase()->createCollection('null1'); + static::getDatabase()->createCollection('null2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_MANY, @@ -12612,7 +12652,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null3', twoWayKey: 'null4', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_ONE, @@ -12620,7 +12660,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null4', twoWayKey: 'null5', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_MANY, @@ -12629,21 +12669,21 @@ public function testCreateEmptyValueRelationship(): void twoWayKey: 'null7', ); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null2' => null, ])); $this->assertEquals(null, $document->getAttribute('null2')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null1' => null, ])); $this->assertEquals(null, $document->getAttribute('null1')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null3' => null, ])); @@ -12651,35 +12691,35 @@ public function testCreateEmptyValueRelationship(): void // One to many will be empty array instead of null $this->assertEquals([], $document->getAttribute('null3')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null5' => null, ])); $this->assertEquals([], $document->getAttribute('null5')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null6' => null, ])); $this->assertEquals([], $document->getAttribute('null6')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null7' => null, ])); @@ -12689,15 +12729,15 @@ public function testCreateEmptyValueRelationship(): void public function testDeleteCollectionDeletesRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('testers'); - $this->getDatabase()->createCollection('devices'); + static::getDatabase()->createCollection('testers'); + static::getDatabase()->createCollection('devices'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'testers', relatedCollection: 'devices', type: Database::RELATION_ONE_TO_MANY, @@ -12705,17 +12745,17 @@ public function testDeleteCollectionDeletesRelationships(): void twoWayKey: 'tester' ); - $testers = $this->getDatabase()->getCollection('testers'); - $devices = $this->getDatabase()->getCollection('devices'); + $testers = static::getDatabase()->getCollection('testers'); + $devices = static::getDatabase()->getCollection('devices'); $this->assertEquals(1, \count($testers->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('indexes'))); - $this->getDatabase()->deleteCollection('testers'); + static::getDatabase()->deleteCollection('testers'); - $testers = $this->getDatabase()->getCollection('testers'); - $devices = $this->getDatabase()->getCollection('devices'); + $testers = static::getDatabase()->getCollection('testers'); + $devices = static::getDatabase()->getCollection('devices'); $this->assertEquals(true, $testers->isEmpty()); $this->assertEquals(0, \count($devices->getAttribute('attributes'))); @@ -12724,15 +12764,15 @@ public function testDeleteCollectionDeletesRelationships(): void public function testDeleteTwoWayRelationshipFromChild(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('drivers'); - $this->getDatabase()->createCollection('licenses'); + static::getDatabase()->createCollection('drivers'); + static::getDatabase()->createCollection('licenses'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_ONE, @@ -12741,25 +12781,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(1, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('licenses', 'driver'); + static::getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_MANY, @@ -12768,25 +12808,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('licenses', 'driver'); + static::getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_ONE, @@ -12795,25 +12835,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('drivers', 'licenses'); + static::getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_MANY, @@ -12822,9 +12862,9 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); - $junction = $this->getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); + $junction = static::getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -12833,11 +12873,11 @@ public function testDeleteTwoWayRelationshipFromChild(): void $this->assertEquals(2, \count($junction->getAttribute('attributes'))); $this->assertEquals(2, \count($junction->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('drivers', 'licenses'); + static::getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); - $junction = $this->getDatabase()->getCollection('_licenses_drivers'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); + $junction = static::getDatabase()->getCollection('_licenses_drivers'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -12849,20 +12889,20 @@ public function testDeleteTwoWayRelationshipFromChild(): void public function testUpdateRelationshipToExistingKey(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('ovens'); - $this->getDatabase()->createCollection('cakes'); + static::getDatabase()->createCollection('ovens'); + static::getDatabase()->createCollection('cakes'); - $this->getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'ovens', relatedCollection: 'cakes', type: Database::RELATION_ONE_TO_MANY, @@ -12872,14 +12912,14 @@ public function testUpdateRelationshipToExistingKey(): void ); try { - $this->getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); + static::getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Attribute already exists', $e->getMessage()); } try { - $this->getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); + static::getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Related attribute already exists', $e->getMessage()); @@ -12888,29 +12928,29 @@ public function testUpdateRelationshipToExistingKey(): void public function testOneToOneRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection1'); - $this->getDatabase()->createCollection('$symbols_coll.ection2'); + static::getDatabase()->createCollection('$symbols_coll.ection1'); + static::getDatabase()->createCollection('$symbols_coll.ection2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection1', relatedCollection: '$symbols_coll.ection2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection2', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection2', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection1', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection1', new Document([ '$id' => ID::unique(), '$symbols_coll.ection2' => $doc1->getId(), '$permissions' => [ @@ -12919,8 +12959,8 @@ public function testOneToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection1')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection2')->getId()); @@ -12928,29 +12968,29 @@ public function testOneToOneRelationshipKeyWithSymbols(): void public function testOneToManyRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection3'); - $this->getDatabase()->createCollection('$symbols_coll.ection4'); + static::getDatabase()->createCollection('$symbols_coll.ection3'); + static::getDatabase()->createCollection('$symbols_coll.ection4'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection3', relatedCollection: '$symbols_coll.ection4', type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection4', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection4', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection3', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection3', new Document([ '$id' => ID::unique(), '$symbols_coll.ection4' => [$doc1->getId()], '$permissions' => [ @@ -12959,8 +12999,8 @@ public function testOneToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection3')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection4')[0]->getId()); @@ -12968,29 +13008,29 @@ public function testOneToManyRelationshipKeyWithSymbols(): void public function testManyToOneRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection5'); - $this->getDatabase()->createCollection('$symbols_coll.ection6'); + static::getDatabase()->createCollection('$symbols_coll.ection5'); + static::getDatabase()->createCollection('$symbols_coll.ection6'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection5', relatedCollection: '$symbols_coll.ection6', type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection6', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection6', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection5', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection5', new Document([ '$id' => ID::unique(), '$symbols_coll.ection6' => $doc1->getId(), '$permissions' => [ @@ -12999,8 +13039,8 @@ public function testManyToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection5')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection6')->getId()); @@ -13008,29 +13048,29 @@ public function testManyToOneRelationshipKeyWithSymbols(): void public function testManyToManyRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection7'); - $this->getDatabase()->createCollection('$symbols_coll.ection8'); + static::getDatabase()->createCollection('$symbols_coll.ection7'); + static::getDatabase()->createCollection('$symbols_coll.ection8'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection7', relatedCollection: '$symbols_coll.ection8', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection8', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection8', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection7', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection7', new Document([ '$id' => ID::unique(), '$symbols_coll.ection8' => [$doc1->getId()], '$permissions' => [ @@ -13039,8 +13079,8 @@ public function testManyToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection7')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection8')[0]->getId()); @@ -13048,16 +13088,16 @@ public function testManyToManyRelationshipKeyWithSymbols(): void public function testCascadeMultiDelete(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('cascadeMultiDelete1'); - $this->getDatabase()->createCollection('cascadeMultiDelete2'); - $this->getDatabase()->createCollection('cascadeMultiDelete3'); + static::getDatabase()->createCollection('cascadeMultiDelete1'); + static::getDatabase()->createCollection('cascadeMultiDelete2'); + static::getDatabase()->createCollection('cascadeMultiDelete3'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cascadeMultiDelete1', relatedCollection: 'cascadeMultiDelete2', type: Database::RELATION_ONE_TO_MANY, @@ -13065,7 +13105,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cascadeMultiDelete2', relatedCollection: 'cascadeMultiDelete3', type: Database::RELATION_ONE_TO_MANY, @@ -13073,7 +13113,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - $root = $this->getDatabase()->createDocument('cascadeMultiDelete1', new Document([ + $root = static::getDatabase()->createDocument('cascadeMultiDelete1', new Document([ '$id' => 'cascadeMultiDelete1', '$permissions' => [ Permission::read(Role::any()), @@ -13102,18 +13142,18 @@ public function testCascadeMultiDelete(): void $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')); $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')[0]->getAttribute('cascadeMultiDelete3')); - $this->assertEquals(true, $this->getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); + $this->assertEquals(true, static::getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); - $multi2 = $this->getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); + $multi2 = static::getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); $this->assertEquals(true, $multi2->isEmpty()); - $multi3 = $this->getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); + $multi3 = static::getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); $this->assertEquals(true, $multi3->isEmpty()); } public function testCollectionUpdate(): Document { - $collection = $this->getDatabase()->createCollection('collectionUpdate', permissions: [ + $collection = static::getDatabase()->createCollection('collectionUpdate', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13122,19 +13162,19 @@ public function testCollectionUpdate(): Document $this->assertInstanceOf(Document::class, $collection); - $collection = $this->getDatabase()->getCollection('collectionUpdate'); + $collection = static::getDatabase()->getCollection('collectionUpdate'); $this->assertFalse($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertCount(4, $collection->getPermissions()); - $collection = $this->getDatabase()->updateCollection('collectionUpdate', [], true); + $collection = static::getDatabase()->updateCollection('collectionUpdate', [], true); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertEmpty($collection->getPermissions()); - $collection = $this->getDatabase()->getCollection('collectionUpdate'); + $collection = static::getDatabase()->getCollection('collectionUpdate'); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); @@ -13149,14 +13189,14 @@ public function testCollectionUpdate(): Document public function testCollectionUpdatePermissionsThrowException(Document $collection): void { $this->expectException(DatabaseException::class); - $this->getDatabase()->updateCollection($collection->getId(), permissions: [ + static::getDatabase()->updateCollection($collection->getId(), permissions: [ 'i dont work' ], documentSecurity: false); } public function testCollectionPermissions(): Document { - $collection = $this->getDatabase()->createCollection('collectionSecurity', permissions: [ + $collection = static::getDatabase()->createCollection('collectionSecurity', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13165,7 +13205,7 @@ public function testCollectionPermissions(): Document $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -13179,7 +13219,7 @@ public function testCollectionPermissions(): Document public function testCollectionPermissionsExceptions(): void { $this->expectException(DatabaseException::class); - $this->getDatabase()->createCollection('collectionSecurity', permissions: [ + static::getDatabase()->createCollection('collectionSecurity', permissions: [ 'i dont work' ]); } @@ -13190,10 +13230,10 @@ public function testCollectionPermissionsExceptions(): void */ public function testCollectionPermissionsCreateWorks(Document $collection): array { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ + $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -13213,11 +13253,11 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra */ public function testCollectionPermissionsCreateThrowsException(Document $collection): void { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument($collection->getId(), new Document([ + static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -13237,10 +13277,10 @@ public function testCollectionPermissionsGetWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13258,10 +13298,10 @@ public function testCollectionPermissionsGetThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -13278,17 +13318,17 @@ public function testCollectionPermissionsFindWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->find($collection->getId()); + $documents = static::getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); try { - $this->getDatabase()->find($collection->getId()); + static::getDatabase()->find($collection->getId()); $this->fail('Failed to throw exception'); } catch (AuthorizationException) { } @@ -13304,11 +13344,11 @@ public function testCollectionPermissionsFindThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->find($collection->getId()); + static::getDatabase()->find($collection->getId()); } /** @@ -13320,10 +13360,10 @@ public function testCollectionPermissionsCountWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $count = $this->getDatabase()->count( + $count = static::getDatabase()->count( $collection->getId() ); @@ -13340,10 +13380,10 @@ public function testCollectionPermissionsCountThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $count = $this->getDatabase()->count( + $count = static::getDatabase()->count( $collection->getId() ); $this->assertEmpty($count); @@ -13358,10 +13398,10 @@ public function testCollectionPermissionsUpdateWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertInstanceOf(Document::class, $this->getDatabase()->updateDocument( + $this->assertInstanceOf(Document::class, static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -13377,11 +13417,11 @@ public function testCollectionPermissionsUpdateWorks(array $data): array public function testCollectionPermissionsUpdateThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->updateDocument( + $document = static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'lorem') @@ -13396,11 +13436,11 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -13414,10 +13454,10 @@ public function testCollectionPermissionsDeleteWorks(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertTrue($this->getDatabase()->deleteDocument( + $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -13428,7 +13468,7 @@ public function testCollectionPermissionsDeleteWorks(array $data): void */ public function testCollectionPermissionsRelationships(): array { - $collection = $this->getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ + $collection = static::getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13437,7 +13477,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -13445,7 +13485,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $collectionOneToOne = $this->getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ + $collectionOneToOne = static::getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13454,7 +13494,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToOne); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collectionOneToOne->getId(), id: 'test', type: Database::VAR_STRING, @@ -13462,7 +13502,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue($this->getDatabase()->createRelationship( + $this->assertTrue(static::getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToOne->getId(), type: Database::RELATION_ONE_TO_ONE, @@ -13470,7 +13510,7 @@ public function testCollectionPermissionsRelationships(): array onDelete: Database::RELATION_MUTATE_CASCADE )); - $collectionOneToMany = $this->getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ + $collectionOneToMany = static::getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13479,7 +13519,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToMany); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collectionOneToMany->getId(), id: 'test', type: Database::VAR_STRING, @@ -13487,7 +13527,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue($this->getDatabase()->createRelationship( + $this->assertTrue(static::getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToMany->getId(), type: Database::RELATION_ONE_TO_MANY, @@ -13506,10 +13546,10 @@ public function testCollectionPermissionsRelationships(): array public function testCollectionPermissionsRelationshipsCreateWorks(array $data): array { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ + $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -13559,11 +13599,11 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument($collection->getId(), new Document([ + static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -13582,10 +13622,10 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13596,10 +13636,10 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13621,10 +13661,10 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -13640,10 +13680,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13656,10 +13696,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13672,10 +13712,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(1, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('unknown')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('unknown')->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13691,28 +13731,28 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); $this->assertEquals(1, $documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); $this->assertEquals(1, $documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('unknown')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('unknown')->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); @@ -13728,9 +13768,9 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); - $this->getDatabase()->updateDocument( + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); + static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document @@ -13738,10 +13778,10 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->assertTrue(true); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -13760,11 +13800,11 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->updateDocument( + $document = static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', $document->getAttribute('test').'new_value') @@ -13779,11 +13819,11 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->deleteDocument( + $document = static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -13797,10 +13837,10 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertTrue($this->getDatabase()->deleteDocument( + $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -13808,28 +13848,28 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): public function testCreateRelationDocumentWithoutUpdatePermission(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('a')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('a')->toString()); - $this->getDatabase()->createCollection('parentRelationTest', [], [], [ + static::getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), Permission::create(Role::user('a')), Permission::update(Role::user('a')), Permission::delete(Role::user('a')) ]); - $this->getDatabase()->createCollection('childRelationTest', [], [], [ + static::getDatabase()->createCollection('childRelationTest', [], [], [ Permission::create(Role::user('a')), Permission::read(Role::user('a')), ]); - $this->getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); - $this->getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); + static::getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); + static::getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parentRelationTest', relatedCollection: 'childRelationTest', type: Database::RELATION_ONE_TO_MANY, @@ -13837,7 +13877,7 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void ); // Create document with relationship with nested data - $parent = $this->getDatabase()->createDocument('parentRelationTest', new Document([ + $parent = static::getDatabase()->createDocument('parentRelationTest', new Document([ '$id' => 'parent1', 'name' => 'Parent 1', 'children' => [ @@ -13853,21 +13893,21 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void '$id' => 'child2', ], ]); - $updatedParent = $this->getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); + $updatedParent = static::getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); $this->assertEquals('child2', $updatedParent->getAttribute('children')[0]->getId()); - $this->getDatabase()->deleteCollection('parentRelationTest'); - $this->getDatabase()->deleteCollection('childRelationTest'); + static::getDatabase()->deleteCollection('parentRelationTest'); + static::getDatabase()->deleteCollection('childRelationTest'); } public function testUpdateDocumentWithRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('userProfiles', [ + static::getDatabase()->createCollection('userProfiles', [ new Document([ '$id' => ID::custom('username'), 'type' => Database::VAR_STRING, @@ -13885,7 +13925,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('links', [ + static::getDatabase()->createCollection('links', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13903,7 +13943,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('videos', [ + static::getDatabase()->createCollection('videos', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13921,7 +13961,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('products', [ + static::getDatabase()->createCollection('products', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13939,7 +13979,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('settings', [ + static::getDatabase()->createCollection('settings', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -13957,7 +13997,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('appearance', [ + static::getDatabase()->createCollection('appearance', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -13975,7 +14015,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('group', [ + static::getDatabase()->createCollection('group', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -13993,7 +14033,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('community', [ + static::getDatabase()->createCollection('community', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -14012,21 +14052,21 @@ public function testUpdateDocumentWithRelationships(): void Permission::delete(Role::any()) ]); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'links', type: Database::RELATION_ONE_TO_MANY, id: 'links' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'videos', type: Database::RELATION_ONE_TO_MANY, id: 'videos' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'products', type: Database::RELATION_ONE_TO_MANY, @@ -14035,35 +14075,35 @@ public function testUpdateDocumentWithRelationships(): void twoWayKey: 'userProfile', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'settings', type: Database::RELATION_ONE_TO_ONE, id: 'settings' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'appearance', type: Database::RELATION_ONE_TO_ONE, id: 'appearance' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'group', type: Database::RELATION_MANY_TO_ONE, id: 'group' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'community', type: Database::RELATION_MANY_TO_ONE, id: 'community' ); - $profile = $this->getDatabase()->createDocument('userProfiles', new Document([ + $profile = static::getDatabase()->createDocument('userProfiles', new Document([ '$id' => '1', 'username' => 'user1', 'links' => [ @@ -14126,7 +14166,7 @@ public function testUpdateDocumentWithRelationships(): void 'name' => 'New Group Name', ]); - $updatedProfile = $this->getDatabase()->updateDocument('userProfiles', '1', $profile); + $updatedProfile = static::getDatabase()->updateDocument('userProfiles', '1', $profile); $this->assertEquals('New Link Value', $updatedProfile->getAttribute('links')[0]->getAttribute('title')); $this->assertEquals('New Meta Title', $updatedProfile->getAttribute('settings')->getAttribute('metaTitle')); @@ -14139,25 +14179,25 @@ public function testUpdateDocumentWithRelationships(): void $this->assertEquals('Community 1', $updatedProfile->getAttribute('community')->getAttribute('name')); // updating document using two way key in one to many relationship - $product = $this->getDatabase()->getDocument('products', 'product1'); + $product = static::getDatabase()->getDocument('products', 'product1'); $product->setAttribute('userProfile', [ '$id' => '1', 'username' => 'updated user value', ]); - $updatedProduct = $this->getDatabase()->updateDocument('products', 'product1', $product); + $updatedProduct = static::getDatabase()->updateDocument('products', 'product1', $product); $this->assertEquals('updated user value', $updatedProduct->getAttribute('userProfile')->getAttribute('username')); $this->assertEquals('Product 1', $updatedProduct->getAttribute('title')); $this->assertEquals('product1', $updatedProduct->getId()); $this->assertEquals('1', $updatedProduct->getAttribute('userProfile')->getId()); - $this->getDatabase()->deleteCollection('userProfiles'); - $this->getDatabase()->deleteCollection('links'); - $this->getDatabase()->deleteCollection('settings'); - $this->getDatabase()->deleteCollection('group'); - $this->getDatabase()->deleteCollection('community'); - $this->getDatabase()->deleteCollection('videos'); - $this->getDatabase()->deleteCollection('products'); - $this->getDatabase()->deleteCollection('appearance'); + static::getDatabase()->deleteCollection('userProfiles'); + static::getDatabase()->deleteCollection('links'); + static::getDatabase()->deleteCollection('settings'); + static::getDatabase()->deleteCollection('group'); + static::getDatabase()->deleteCollection('community'); + static::getDatabase()->deleteCollection('videos'); + static::getDatabase()->deleteCollection('products'); + static::getDatabase()->deleteCollection('appearance'); } public function testRecreateOneToOneOneWayRelationshipFromParent(): void @@ -15186,12 +15226,12 @@ public function testRecreateManyToManyTwoWayRelationshipFromChild(): void public function testLabels(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection( + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection( 'labels_test', )); - $this->getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); - $this->getDatabase()->createDocument('labels_test', new Document([ + static::getDatabase()->createDocument('labels_test', new Document([ '$id' => 'doc1', 'attr1' => 'value1', '$permissions' => [ @@ -15199,20 +15239,20 @@ public function testLabels(): void ], ])); - $documents = $this->getDatabase()->find('labels_test'); + $documents = static::getDatabase()->find('labels_test'); $this->assertEmpty($documents); - self::$authorization->addRole(Role::label('reader')->toString()); + Authorization::setRole(Role::label('reader')->toString()); - $documents = $this->getDatabase()->find('labels_test'); + $documents = static::getDatabase()->find('labels_test'); $this->assertCount(1, $documents); } public function testEnableDisableValidation(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createCollection('validation', permissions: [ Permission::create(Role::any()), @@ -15269,21 +15309,21 @@ public function testEnableDisableValidation(): void public function testMetadata(): void { - $this->getDatabase()->setMetadata('key', 'value'); + static::getDatabase()->setMetadata('key', 'value'); - $this->getDatabase()->createCollection('testers'); + static::getDatabase()->createCollection('testers'); - $this->assertEquals(['key' => 'value'], $this->getDatabase()->getMetadata()); + $this->assertEquals(['key' => 'value'], static::getDatabase()->getMetadata()); - $this->getDatabase()->resetMetadata(); + static::getDatabase()->resetMetadata(); - $this->assertEquals([], $this->getDatabase()->getMetadata()); + $this->assertEquals([], static::getDatabase()->getMetadata()); } public function testEmptyOperatorValues(): void { try { - $this->getDatabase()->findOne('documents', [ + static::getDatabase()->findOne('documents', [ Query::equal('string', []), ]); $this->fail('Failed to throw exception'); @@ -15293,7 +15333,7 @@ public function testEmptyOperatorValues(): void } try { - $this->getDatabase()->findOne('documents', [ + static::getDatabase()->findOne('documents', [ Query::contains('string', []), ]); $this->fail('Failed to throw exception'); @@ -15317,7 +15357,7 @@ public function testSharedTables(): void /** * Default mode already tested, we'll test 'schema' and 'table' isolation here */ - $database = $this->getDatabase(); + $database = static::getDatabase(); if (!$database->getAdapter()->getSupportForSchemas()) { $this->expectNotToPerformAssertions(); @@ -15544,7 +15584,7 @@ public function testSharedTablesDuplicatesDontThrow(): void public function testTransformations(): void { - $this->getDatabase()->createCollection('docs', attributes: [ + static::getDatabase()->createCollection('docs', attributes: [ new Document([ '$id' => 'name', 'type' => Database::VAR_STRING, @@ -15553,16 +15593,16 @@ public function testTransformations(): void ]) ]); - $this->getDatabase()->createDocument('docs', new Document([ + static::getDatabase()->createDocument('docs', new Document([ '$id' => 'doc1', 'name' => 'value1', ])); - $this->getDatabase()->before(Database::EVENT_DOCUMENT_READ, 'test', function (string $query) { + static::getDatabase()->before(Database::EVENT_DOCUMENT_READ, 'test', function (string $query) { return "SELECT 1"; }); - $result = $this->getDatabase()->getDocument('docs', 'doc1'); + $result = static::getDatabase()->getDocument('docs', 'doc1'); $this->assertTrue($result->isEmpty()); } @@ -16616,8 +16656,8 @@ public function testUpdateDocumentsRelationships(): void public function testEvents(): void { - self::$authorization->skip(function () { - $database = $this->getDatabase(); + Authorization::skip(function () { + $database = static::getDatabase(); $events = [ Database::EVENT_DATABASE_CREATE, diff --git a/tests/e2e/Adapter/MariaDBTest.php b/tests/e2e/Adapter/MariaDBTest.php index c60dfbed9..d7966e657 100644 --- a/tests/e2e/Adapter/MariaDBTest.php +++ b/tests/e2e/Adapter/MariaDBTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(bool $fresh = false): Database + public static function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; @@ -46,9 +46,9 @@ public function getDatabase(bool $fresh = false): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MariaDB($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); diff --git a/tests/e2e/Adapter/MongoDBTest.php b/tests/e2e/Adapter/MongoDBTest.php index a17e595bd..3f3b5d5de 100644 --- a/tests/e2e/Adapter/MongoDBTest.php +++ b/tests/e2e/Adapter/MongoDBTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -51,9 +51,9 @@ public function getDatabase(): Database ); $database = new Database(new Mongo($client), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase($schema); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase($schema) + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -70,10 +70,10 @@ public function getDatabase(): Database public function testCreateExistsDelete(): void { // Mongo creates databases on the fly, so exists would always pass. So we override this test to remove the exists check. - $this->assertNotNull($this->getDatabase()->create()); - $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); + $this->assertNotNull(static::getDatabase()->create()); + $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->create()); + $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); } public function testRenameAttribute(): void diff --git a/tests/e2e/Adapter/MySQLTest.php b/tests/e2e/Adapter/MySQLTest.php index bae839a10..8d855d6ca 100644 --- a/tests/e2e/Adapter/MySQLTest.php +++ b/tests/e2e/Adapter/MySQLTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -48,9 +48,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MySQL($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); diff --git a/tests/e2e/Adapter/PostgresTest.php b/tests/e2e/Adapter/PostgresTest.php index 19b972115..e024e4442 100644 --- a/tests/e2e/Adapter/PostgresTest.php +++ b/tests/e2e/Adapter/PostgresTest.php @@ -27,7 +27,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -45,9 +45,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new Postgres($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); diff --git a/tests/e2e/Adapter/SQLiteTest.php b/tests/e2e/Adapter/SQLiteTest.php index bc903fd7d..2d4240994 100644 --- a/tests/e2e/Adapter/SQLiteTest.php +++ b/tests/e2e/Adapter/SQLiteTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -51,9 +51,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new SQLite($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); diff --git a/tests/e2e/Adapter/SharedTables/MariaDBTest.php b/tests/e2e/Adapter/SharedTables/MariaDBTest.php index 7ee04ac5b..249e13319 100644 --- a/tests/e2e/Adapter/SharedTables/MariaDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MariaDBTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(bool $fresh = false): Database + public static function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; @@ -48,7 +48,6 @@ public function getDatabase(bool $fresh = false): Database $database = new Database(new MariaDB($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/MongoDBTest.php b/tests/e2e/Adapter/SharedTables/MongoDBTest.php index c5968727c..47f480073 100644 --- a/tests/e2e/Adapter/SharedTables/MongoDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MongoDBTest.php @@ -30,7 +30,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -53,7 +53,6 @@ public function getDatabase(): Database $database = new Database(new Mongo($client), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase($schema) ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/MySQLTest.php b/tests/e2e/Adapter/SharedTables/MySQLTest.php index af244d985..689ea49c7 100644 --- a/tests/e2e/Adapter/SharedTables/MySQLTest.php +++ b/tests/e2e/Adapter/SharedTables/MySQLTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -50,7 +50,6 @@ public function getDatabase(): Database $database = new Database(new MySQL($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/PostgresTest.php b/tests/e2e/Adapter/SharedTables/PostgresTest.php index 4de48ee1d..df85dfeb0 100644 --- a/tests/e2e/Adapter/SharedTables/PostgresTest.php +++ b/tests/e2e/Adapter/SharedTables/PostgresTest.php @@ -28,7 +28,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -47,7 +47,6 @@ public function getDatabase(): Database $database = new Database(new Postgres($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/e2e/Adapter/SharedTables/SQLiteTest.php b/tests/e2e/Adapter/SharedTables/SQLiteTest.php index a1254505d..a69984216 100644 --- a/tests/e2e/Adapter/SharedTables/SQLiteTest.php +++ b/tests/e2e/Adapter/SharedTables/SQLiteTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -53,7 +53,6 @@ public function getDatabase(): Database $database = new Database(new SQLite($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) diff --git a/tests/unit/Format.php b/tests/unit/Format.php index 92cf10f28..f4f4a4a0f 100644 --- a/tests/unit/Format.php +++ b/tests/unit/Format.php @@ -2,15 +2,14 @@ namespace Tests\Unit; -use Utopia\Http\Validator; -use Utopia\Http\Validator\Text; +use Utopia\Validator\Text; /** * Format Test for Email * * Validate that an variable is a valid email address * - * @package Utopia\Http\Validator + * @package Utopia\Validator */ class Format extends Text { diff --git a/tests/unit/Validator/AuthorizationTest.php b/tests/unit/Validator/AuthorizationTest.php index 37e5a6e22..08c1e46f2 100644 --- a/tests/unit/Validator/AuthorizationTest.php +++ b/tests/unit/Validator/AuthorizationTest.php @@ -9,15 +9,11 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Database\Validator\Authorization\Input; class AuthorizationTest extends TestCase { - protected Authorization $authorization; - public function setUp(): void { - $this->authorization = new Authorization(); } public function tearDown(): void @@ -26,7 +22,7 @@ public function tearDown(): void public function testValues(): void { - $this->authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); $document = new Document([ '$id' => ID::unique(), @@ -39,88 +35,88 @@ public function testValues(): void Permission::delete(Role::any()), ], ]); + $object = new Authorization(Database::PERMISSION_READ); - $object = $this->authorization; - - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, [])), false); + $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(''), false); + $this->assertEquals($object->isValid([]), false); $this->assertEquals($object->getDescription(), 'No permissions provided for action \'read\''); - $this->authorization->addRole(Role::user('456')->toString()); - $this->authorization->addRole(Role::user('123')->toString()); + Authorization::setRole(Role::user('456')->toString()); + Authorization::setRole(Role::user('123')->toString()); - $this->assertEquals($this->authorization->isRole(Role::user('456')->toString()), true); - $this->assertEquals($this->authorization->isRole(Role::user('457')->toString()), false); - $this->assertEquals($this->authorization->isRole(''), false); - $this->assertEquals($this->authorization->isRole(Role::any()->toString()), true); + $this->assertEquals(Authorization::isRole(Role::user('456')->toString()), true); + $this->assertEquals(Authorization::isRole(Role::user('457')->toString()), false); + $this->assertEquals(Authorization::isRole(''), false); + $this->assertEquals(Authorization::isRole(Role::any()->toString()), true); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->cleanRoles(); + Authorization::cleanRoles(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->addRole(Role::team('123')->toString()); + Authorization::setRole(Role::team('123')->toString()); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->cleanRoles(); - $this->authorization->disable(); + Authorization::cleanRoles(); + Authorization::disable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->reset(); + Authorization::reset(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->setDefaultStatus(false); - $this->authorization->disable(); + Authorization::setDefaultStatus(false); + Authorization::disable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->reset(); + Authorization::reset(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->enable(); + Authorization::enable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->addRole('textX'); + Authorization::setRole('textX'); - $this->assertContains('textX', $this->authorization->getRoles()); + $this->assertContains('textX', Authorization::getRoles()); - $this->authorization->removeRole('textX'); + Authorization::unsetRole('textX'); - $this->assertNotContains('textX', $this->authorization->getRoles()); + $this->assertNotContains('textX', Authorization::getRoles()); // Test skip method - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->assertEquals($this->authorization->skip(function () use ($object, $document) { - return $object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())); + $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals(Authorization::skip(function () use ($object, $document) { + return $object->isValid($document->getRead()); }), true); } public function testNestedSkips(): void { - $this->assertEquals(true, $this->authorization->getStatus()); + $this->assertEquals(true, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(false, $this->authorization->getStatus()); + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(false, $this->authorization->getStatus()); + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(true, $this->authorization->getStatus()); + $this->assertEquals(true, Authorization::$status); } } diff --git a/tests/unit/Validator/DateTimeTest.php b/tests/unit/Validator/DateTimeTest.php index d8ababb6f..b9157e8b8 100644 --- a/tests/unit/Validator/DateTimeTest.php +++ b/tests/unit/Validator/DateTimeTest.php @@ -128,7 +128,7 @@ public function testOffset(): void $threwException = false; try { $dateValidator = new DatetimeValidator(offset: -60); - } catch (\Exception $e) { + } catch(\Exception $e) { $threwException = true; } $this->assertTrue($threwException); From 169977b8ac2cc731ff86efaa56193e60a58ba02f Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:07:12 +1300 Subject: [PATCH 098/103] Fix test refs --- tests/e2e/Adapter/Base.php | 344 ++++++++++++++++++------------------- 1 file changed, 172 insertions(+), 172 deletions(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index d9dd2ff77..9aba9ac99 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -65,7 +65,7 @@ public function testPing(): void public function testCreateExistsDelete(): void { - $schemaSupport = $this->getDatabase()->getAdapter()->getSupportForSchemas(); + $schemaSupport = static::getDatabase()->getAdapter()->getSupportForSchemas(); if (!$schemaSupport) { $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); $this->assertEquals(true, static::getDatabase()->create()); @@ -751,7 +751,7 @@ public function testPreserveDatesUpdate(): void $doc1 = static::getDatabase()->getDocument('preserve_update_dates', 'doc1'); $this->assertEquals($newDate, $doc1->getAttribute('$updatedAt')); - $this->getDatabase()->updateDocuments( + static::getDatabase()->updateDocuments( 'preserve_update_dates', new Document([ '$updatedAt' => $newDate @@ -976,7 +976,7 @@ public function testCreatedAtUpdatedAt(): void public function testQueryTimeout(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForTimeouts()) { + if (!static::getDatabase()->getAdapter()->getSupportForTimeouts()) { $this->expectNotToPerformAssertions(); return; } @@ -1081,13 +1081,13 @@ public function testSizeCollection(): void static::getDatabase()->analyzeCollection('sizeTest2'); - $size2 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + $size2 = static::getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertGreaterThan($size1, $size2); self::$authorization->skip(function () use ($loopCount) { for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); + static::getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); } }); @@ -1095,40 +1095,40 @@ public function testSizeCollection(): void static::getDatabase()->analyzeCollection('sizeTest2'); - $size3 = $this->getDatabase()->getSizeOfCollection('sizeTest2'); + $size3 = static::getDatabase()->getSizeOfCollection('sizeTest2'); $this->assertLessThan($size2, $size3); } public function testSizeCollectionOnDisk(): void { - $this->getDatabase()->createCollection('sizeTestDisk1'); - $this->getDatabase()->createCollection('sizeTestDisk2'); + static::getDatabase()->createCollection('sizeTestDisk1'); + static::getDatabase()->createCollection('sizeTestDisk2'); - $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk1'); - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); + $size1 = static::getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk1'); + $size2 = static::getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); $sizeDifference = abs($size1 - $size2); // Size of an empty collection returns either 172032 or 167936 bytes randomly // Therefore asserting with a tolerance of 5000 bytes $byteDifference = 5000; $this->assertLessThan($byteDifference, $sizeDifference); - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string1', Database::VAR_STRING, 20000, true); - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string2', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createAttribute('sizeTestDisk2', 'string3', Database::VAR_STRING, 254 + 1, true); - $this->getDatabase()->createIndex('sizeTestDisk2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + static::getDatabase()->createAttribute('sizeTestDisk2', 'string1', Database::VAR_STRING, 20000, true); + static::getDatabase()->createAttribute('sizeTestDisk2', 'string2', Database::VAR_STRING, 254 + 1, true); + static::getDatabase()->createAttribute('sizeTestDisk2', 'string3', Database::VAR_STRING, 254 + 1, true); + static::getDatabase()->createIndex('sizeTestDisk2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 40; for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->createDocument('sizeTestDisk2', new Document([ + static::getDatabase()->createDocument('sizeTestDisk2', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, ])); } - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); + $size2 = static::getDatabase()->getSizeOfCollectionOnDisk('sizeTestDisk2'); $this->assertGreaterThan($size1, $size2); } @@ -1143,7 +1143,7 @@ public function testSizeFullText(): void static::getDatabase()->createCollection('fullTextSizeTest'); - $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size1 = static::getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); static::getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); static::getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); @@ -1160,13 +1160,13 @@ public function testSizeFullText(): void ])); } - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size2 = static::getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size1, $size2); static::getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); - $size3 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size3 = static::getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size2, $size3); } @@ -2270,7 +2270,7 @@ public function testFulltextIndexWithInteger(): void { $this->expectException(Exception::class); - if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectExceptionMessage('Fulltext index is not supported'); } else { $this->expectExceptionMessage('Attribute "integer_signed" cannot be part of a FULLTEXT index, must be of type string'); @@ -2281,7 +2281,7 @@ public function testFulltextIndexWithInteger(): void public function testListDocumentSearch(): void { - $fulltextSupport = $this->getDatabase()->getAdapter()->getSupportForFulltextIndex(); + $fulltextSupport = static::getDatabase()->getAdapter()->getSupportForFulltextIndex(); if (!$fulltextSupport) { $this->expectNotToPerformAssertions(); return; @@ -2344,7 +2344,7 @@ public function testEmptyTenant(): void public function testEmptySearch(): void { - $fulltextSupport = $this->getDatabase()->getAdapter()->getSupportForFulltextIndex(); + $fulltextSupport = static::getDatabase()->getAdapter()->getSupportForFulltextIndex(); if (!$fulltextSupport) { $this->expectNotToPerformAssertions(); return; @@ -2381,7 +2381,7 @@ public function testUpdateDocument(Document $document): Document ->setAttribute('colors', 'red', Document::SET_TYPE_APPEND) ->setAttribute('with-dash', 'Works'); - $new = $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); + $new = static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); $this->assertNotEmpty(true, $new->getId()); $this->assertIsString($new->getAttribute('string')); @@ -2408,9 +2408,9 @@ public function testUpdateDocument(Document $document): Document ->setAttribute('$permissions', Permission::update(Role::guests()), Document::SET_TYPE_APPEND) ->setAttribute('$permissions', Permission::delete(Role::guests()), Document::SET_TYPE_APPEND); - $this->getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); + static::getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); - $new = $this->getDatabase()->getDocument($new->getCollection(), $new->getId()); + $new = static::getDatabase()->getDocument($new->getCollection(), $new->getId()); $this->assertContains('guests', $new->getRead()); $this->assertContains('guests', $new->getWrite()); @@ -2420,9 +2420,9 @@ public function testUpdateDocument(Document $document): Document $new->setAttribute('$permissions', $oldPermissions); - $this->getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); + static::getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); - $new = $this->getDatabase()->getDocument($new->getCollection(), $new->getId()); + $new = static::getDatabase()->getDocument($new->getCollection(), $new->getId()); $this->assertNotContains('guests', $new->getRead()); $this->assertNotContains('guests', $new->getWrite()); @@ -2434,12 +2434,12 @@ public function testUpdateDocument(Document $document): Document $id = $new->getId(); $newId = 'new-id'; $new->setAttribute('$id', $newId); - $new = $this->getDatabase()->updateDocument($new->getCollection(), $id, $new); + $new = static::getDatabase()->updateDocument($new->getCollection(), $id, $new); $this->assertEquals($newId, $new->getId()); // Reset ID $new->setAttribute('$id', $id); - $new = $this->getDatabase()->updateDocument($new->getCollection(), $newId, $new); + $new = static::getDatabase()->updateDocument($new->getCollection(), $newId, $new); $this->assertEquals($id, $new->getId()); return $document; @@ -2498,16 +2498,16 @@ public function testUpdateDocuments(array $documents): void public function testUpdateDocumentConflict(Document $document): void { $document->setAttribute('integer_signed', 7); - $result = $this->getDatabase()->withRequestTimestamp(new \DateTime(), function () use ($document) { - return $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); + $result = static::getDatabase()->withRequestTimestamp(new \DateTime(), function () use ($document) { + return static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->assertEquals(7, $result->getAttribute('integer_signed')); $oneHourAgo = (new \DateTime())->sub(new \DateInterval('PT1H')); $document->setAttribute('integer_signed', 8); try { - $this->getDatabase()->withRequestTimestamp($oneHourAgo, function () use ($document) { - return $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); + static::getDatabase()->withRequestTimestamp($oneHourAgo, function () use ($document) { + return static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->fail('Failed to throw exception'); } catch(Throwable $e) { @@ -2523,8 +2523,8 @@ public function testDeleteDocumentConflict(Document $document): void { $oneHourAgo = (new \DateTime())->sub(new \DateInterval('PT1H')); $this->expectException(ConflictException::class); - $this->getDatabase()->withRequestTimestamp($oneHourAgo, function () use ($document) { - return $this->getDatabase()->deleteDocument($document->getCollection(), $document->getId()); + static::getDatabase()->withRequestTimestamp($oneHourAgo, function () use ($document) { + return static::getDatabase()->deleteDocument($document->getCollection(), $document->getId()); }); } @@ -2533,7 +2533,7 @@ public function testDeleteDocumentConflict(Document $document): void */ public function testUpdateDocumentDuplicatePermissions(Document $document): Document { - $new = $this->getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); + $new = static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); $new ->setAttribute('$permissions', Permission::read(Role::guests()), Document::SET_TYPE_APPEND) @@ -2541,9 +2541,9 @@ public function testUpdateDocumentDuplicatePermissions(Document $document): Docu ->setAttribute('$permissions', Permission::create(Role::guests()), Document::SET_TYPE_APPEND) ->setAttribute('$permissions', Permission::create(Role::guests()), Document::SET_TYPE_APPEND); - $this->getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); + static::getDatabase()->updateDocument($new->getCollection(), $new->getId(), $new); - $new = $this->getDatabase()->getDocument($new->getCollection(), $new->getId()); + $new = static::getDatabase()->getDocument($new->getCollection(), $new->getId()); $this->assertContains('guests', $new->getRead()); $this->assertContains('guests', $new->getCreate()); @@ -2556,8 +2556,8 @@ public function testUpdateDocumentDuplicatePermissions(Document $document): Docu */ public function testDeleteDocument(Document $document): void { - $result = $this->getDatabase()->deleteDocument($document->getCollection(), $document->getId()); - $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); + $result = static::getDatabase()->deleteDocument($document->getCollection(), $document->getId()); + $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $result); $this->assertEquals(true, $document->isEmpty()); @@ -2728,7 +2728,7 @@ public function testArrayAttribute(): void $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); } catch(Throwable $e) { - if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->assertEquals('"Fulltext" index is forbidden on array attributes', $e->getMessage()); } else { $this->assertEquals('Fulltext index is not supported', $e->getMessage()); @@ -2777,7 +2777,7 @@ public function testArrayAttribute(): void $this->assertTrue($database->createIndex($collection, 'indx6', Database::INDEX_KEY, ['age', 'names'], [null, 999], [])); $this->assertTrue($database->createIndex($collection, 'indx7', Database::INDEX_KEY, ['age', 'booleans'], [0, 999], [])); - if ($this->getDatabase()->getAdapter()->getSupportForQueryContains()) { + if (static::getDatabase()->getAdapter()->getSupportForQueryContains()) { try { $database->find($collection, [ Query::equal('names', ['Joe']), @@ -3197,7 +3197,7 @@ public function testFindFloat(): void public function testFindContains(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForQueryContains()) { + if (!static::getDatabase()->getAdapter()->getSupportForQueryContains()) { $this->expectNotToPerformAssertions(); return; } @@ -3239,7 +3239,7 @@ public function testFindFulltext(): void /** * Fulltext search */ - if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $success = static::getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); $this->assertEquals(true, $success); @@ -3256,7 +3256,7 @@ public function testFindFulltext(): void // TODO: Looks like the MongoDB implementation is a bit more complex, skipping that for now. // TODO: I think this needs a changes? how do we distinguish between regular full text and wildcard? - if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildCardIndex()) { + if (static::getDatabase()->getAdapter()->getSupportForFulltextWildCardIndex()) { $documents = static::getDatabase()->find('movies', [ Query::search('name', 'cap'), ]); @@ -4337,7 +4337,7 @@ public function testFindStartsWith(): void $this->assertEquals(2, count($documents)); - if ($this->getDatabase()->getAdapter() instanceof SQL) { + if (static::getDatabase()->getAdapter() instanceof SQL) { $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', '%ork'), ]); @@ -5145,10 +5145,10 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void public function testExceptionAttributeLimit(): void { - if ($this->getDatabase()->getLimitForAttributes() > 0) { + if (static::getDatabase()->getLimitForAttributes() > 0) { // Load the collection up to the limit $attributes = []; - for ($i = 0; $i < $this->getDatabase()->getLimitForAttributes(); $i++) { + for ($i = 0; $i < static::getDatabase()->getLimitForAttributes(); $i++) { $attributes[] = new Document([ '$id' => ID::custom("test{$i}"), 'type' => Database::VAR_INTEGER, @@ -5176,7 +5176,7 @@ public function testExceptionAttributeLimit(): void */ public function testCheckAttributeCountLimit(): void { - if ($this->getDatabase()->getLimitForAttributes() > 0) { + if (static::getDatabase()->getLimitForAttributes() > 0) { $collection = static::getDatabase()->getCollection('attributeLimit'); // create same attribute in testExceptionAttributeLimit @@ -5338,7 +5338,7 @@ public function testExceptionIndexLimit(): void // Testing for indexLimit // Add up to the limit, then check if the next index throws IndexLimitException - for ($i = 0; $i < ($this->getDatabase()->getLimitForIndexes()); $i++) { + for ($i = 0; $i < (static::getDatabase()->getLimitForIndexes()); $i++) { $this->assertEquals(true, static::getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); } $this->expectException(LimitException::class); @@ -5447,12 +5447,12 @@ public function testUniqueIndexDuplicateUpdate(): void public function testGetAttributeLimit(): void { - $this->assertIsInt($this->getDatabase()->getLimitForAttributes()); + $this->assertIsInt(static::getDatabase()->getLimitForAttributes()); } public function testGetIndexLimit(): void { - $this->assertEquals(58, $this->getDatabase()->getLimitForIndexes()); + $this->assertEquals(58, static::getDatabase()->getLimitForIndexes()); } public function testGetId(): void @@ -15690,7 +15690,7 @@ public function testDeleteBulkDocuments(): void $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); $this->assertEquals(5, $deleted); - $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); + $this->assertEquals(0, count(static::getDatabase()->find('bulk_delete'))); // TEST: Make sure we can't delete documents we don't have permissions for static::getDatabase()->updateCollection('bulk_delete', [ @@ -15713,7 +15713,7 @@ public function testDeleteBulkDocuments(): void Permission::delete(Role::any()) ], false); static::getDatabase()->deleteDocuments('bulk_delete'); - $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); + $this->assertEquals(0, count(static::getDatabase()->find('bulk_delete'))); // Teardown static::getDatabase()->deleteCollection('bulk_delete'); @@ -15726,22 +15726,22 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void return; } - $this->getDatabase()->createCollection('bulk_delete_person_o2o'); - $this->getDatabase()->createCollection('bulk_delete_library_o2o'); + static::getDatabase()->createCollection('bulk_delete_person_o2o'); + static::getDatabase()->createCollection('bulk_delete_library_o2o'); - $this->getDatabase()->createAttribute('bulk_delete_person_o2o', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_o2o', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_o2o', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_person_o2o', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_o2o', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_o2o', 'area', Database::VAR_STRING, 255, true); // Restrict - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'bulk_delete_person_o2o', relatedCollection: 'bulk_delete_library_o2o', type: Database::RELATION_ONE_TO_ONE, onDelete: Database::RELATION_MUTATE_RESTRICT ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15761,20 +15761,20 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); // Delete person try { - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2o'); $this->fail('Failed to throw exception'); } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } - $this->getDatabase()->updateDocument('bulk_delete_person_o2o', 'person1', new Document([ + static::getDatabase()->updateDocument('bulk_delete_person_o2o', 'person1', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15785,19 +15785,19 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void 'bulk_delete_library_o2o' => null, ])); - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2o')); // NULL - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'bulk_delete_person_o2o', id: 'bulk_delete_library_o2o', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15817,35 +15817,35 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); - $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2o')); + $this->assertCount(1, static::getDatabase()->find('bulk_delete_person_o2o')); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person->getAttribute('bulk_delete_library_o2o'); $this->assertNull($library); // NULL - Cleanup - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2o')); // Cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'bulk_delete_person_o2o', id: 'bulk_delete_library_o2o', onDelete: Database::RELATION_MUTATE_CASCADE ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15865,27 +15865,27 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); - $this->assertCount(1, $this->getDatabase()->find('bulk_delete_person_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2o')); + $this->assertCount(1, static::getDatabase()->find('bulk_delete_person_o2o')); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person->getAttribute('bulk_delete_library_o2o'); $this->assertEmpty($library); $this->assertNotNull($library); // Test Bulk delete parent - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2o')); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15905,14 +15905,14 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_o2o'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('bulk_delete_person_o2o', $library); - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2o')); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2o')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2o')); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2o')); } public function testDeleteBulkDocumentsOneToManyRelationship(): void @@ -15922,22 +15922,22 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void return; } - $this->getDatabase()->createCollection('bulk_delete_person_o2m'); - $this->getDatabase()->createCollection('bulk_delete_library_o2m'); + static::getDatabase()->createCollection('bulk_delete_person_o2m'); + static::getDatabase()->createCollection('bulk_delete_library_o2m'); - $this->getDatabase()->createAttribute('bulk_delete_person_o2m', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_o2m', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_o2m', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_person_o2m', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_o2m', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_o2m', 'area', Database::VAR_STRING, 255, true); // Restrict - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'bulk_delete_person_o2m', relatedCollection: 'bulk_delete_library_o2m', type: Database::RELATION_ONE_TO_MANY, onDelete: Database::RELATION_MUTATE_RESTRICT ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -15969,33 +15969,33 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); $libraries = $person1->getAttribute('bulk_delete_library_o2m'); $this->assertCount(2, $libraries); // Delete person try { - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2m'); $this->fail('Failed to throw exception'); } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Restrict Cleanup - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2m')); - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2m')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2m')); // NULL - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'bulk_delete_person_o2m', id: 'bulk_delete_library_o2m', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -16027,30 +16027,30 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); $libraries = $person1->getAttribute('bulk_delete_library_o2m'); $this->assertCount(2, $libraries); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2m')); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); $libraries = $person->getAttribute('bulk_delete_library_o2m'); $this->assertEmpty($libraries); // NULL - Cleanup - $this->getDatabase()->deleteDocuments('bulk_delete_person_o2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_o2m')); + static::getDatabase()->deleteDocuments('bulk_delete_person_o2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_o2m')); // Cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'bulk_delete_person_o2m', id: 'bulk_delete_library_o2m', onDelete: Database::RELATION_MUTATE_CASCADE ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_o2m', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -16082,14 +16082,14 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); $libraries = $person1->getAttribute('bulk_delete_library_o2m'); $this->assertCount(2, $libraries); - $this->getDatabase()->deleteDocuments('bulk_delete_library_o2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_o2m')); + static::getDatabase()->deleteDocuments('bulk_delete_library_o2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_o2m')); - $person = $this->getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); + $person = static::getDatabase()->getDocument('bulk_delete_person_o2m', 'person1'); $libraries = $person->getAttribute('bulk_delete_library_o2m'); $this->assertEmpty($libraries); } @@ -16101,22 +16101,22 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void return; } - $this->getDatabase()->createCollection('bulk_delete_person_m2m'); - $this->getDatabase()->createCollection('bulk_delete_library_m2m'); + static::getDatabase()->createCollection('bulk_delete_person_m2m'); + static::getDatabase()->createCollection('bulk_delete_library_m2m'); - $this->getDatabase()->createAttribute('bulk_delete_person_m2m', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_m2m', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_person_m2m', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_m2m', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_m2m', 'area', Database::VAR_STRING, 255, true); // Many-to-Many Relationship - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'bulk_delete_person_m2m', relatedCollection: 'bulk_delete_library_m2m', type: Database::RELATION_MANY_TO_MANY, onDelete: Database::RELATION_MUTATE_RESTRICT ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2m', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_m2m', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -16148,25 +16148,25 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void ], ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2m', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_m2m', 'person1'); $libraries = $person1->getAttribute('bulk_delete_library_m2m'); $this->assertCount(2, $libraries); // Delete person try { - $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); + static::getDatabase()->deleteDocuments('bulk_delete_person_m2m'); $this->fail('Failed to throw exception'); } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Restrict Cleanup - $this->getDatabase()->deleteRelationship('bulk_delete_person_m2m', 'bulk_delete_library_m2m'); - $this->getDatabase()->deleteDocuments('bulk_delete_library_m2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2m')); + static::getDatabase()->deleteRelationship('bulk_delete_person_m2m', 'bulk_delete_library_m2m'); + static::getDatabase()->deleteDocuments('bulk_delete_library_m2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_m2m')); - $this->getDatabase()->deleteDocuments('bulk_delete_person_m2m'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2m')); + static::getDatabase()->deleteDocuments('bulk_delete_person_m2m'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_m2m')); } public function testDeleteBulkDocumentsManyToOneRelationship(): void @@ -16176,22 +16176,22 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void return; } - $this->getDatabase()->createCollection('bulk_delete_person_m2o'); - $this->getDatabase()->createCollection('bulk_delete_library_m2o'); + static::getDatabase()->createCollection('bulk_delete_person_m2o'); + static::getDatabase()->createCollection('bulk_delete_library_m2o'); - $this->getDatabase()->createAttribute('bulk_delete_person_m2o', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('bulk_delete_library_m2o', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_person_m2o', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_m2o', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('bulk_delete_library_m2o', 'area', Database::VAR_STRING, 255, true); // Many-to-One Relationship - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'bulk_delete_person_m2o', relatedCollection: 'bulk_delete_library_m2o', type: Database::RELATION_MANY_TO_ONE, onDelete: Database::RELATION_MUTATE_RESTRICT ); - $person1 = $this->getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ + $person1 = static::getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -16211,7 +16211,7 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void ], ])); - $person2 = $this->getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ + $person2 = static::getDatabase()->createDocument('bulk_delete_person_m2o', new Document([ '$id' => 'person2', '$permissions' => [ Permission::read(Role::any()), @@ -16224,30 +16224,30 @@ public function testDeleteBulkDocumentsManyToOneRelationship(): void ] ])); - $person1 = $this->getDatabase()->getDocument('bulk_delete_person_m2o', 'person1'); + $person1 = static::getDatabase()->getDocument('bulk_delete_person_m2o', 'person1'); $library = $person1->getAttribute('bulk_delete_library_m2o'); $this->assertEquals('library1', $library['$id']); // Delete library try { - $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); + static::getDatabase()->deleteDocuments('bulk_delete_library_m2o'); $this->fail('Failed to throw exception'); } catch (RestrictedException $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } - $this->assertEquals(2, count($this->getDatabase()->find('bulk_delete_person_m2o'))); + $this->assertEquals(2, count(static::getDatabase()->find('bulk_delete_person_m2o'))); // Test delete people - $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); - $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete_person_m2o'))); + static::getDatabase()->deleteDocuments('bulk_delete_person_m2o'); + $this->assertEquals(0, count(static::getDatabase()->find('bulk_delete_person_m2o'))); // Restrict Cleanup - $this->getDatabase()->deleteDocuments('bulk_delete_library_m2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_library_m2o')); + static::getDatabase()->deleteDocuments('bulk_delete_library_m2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_library_m2o')); - $this->getDatabase()->deleteDocuments('bulk_delete_person_m2o'); - $this->assertCount(0, $this->getDatabase()->find('bulk_delete_person_m2o')); + static::getDatabase()->deleteDocuments('bulk_delete_person_m2o'); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_person_m2o')); } public function testUpdateDocuments(): void @@ -16523,7 +16523,7 @@ public function testUpdateDocumentsPermissions(): void $documents = static::$authorization ->skip(function () use ($collection) { - return $this->getDatabase()->find($collection); + return static::getDatabase()->find($collection); }); $this->assertCount(11, $documents); @@ -16544,7 +16544,7 @@ public function testUpdateDocumentsPermissions(): void public function testUpdateDocumentsRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForBatchOperations() || !$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations() || !static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -16552,7 +16552,7 @@ public function testUpdateDocumentsRelationships(): void self::$authorization->cleanRoles(); self::$authorization->addRole(Role::any()->toString()); - $this->getDatabase()->createCollection('testUpdateDocumentsRelationships1', attributes: [ + static::getDatabase()->createCollection('testUpdateDocumentsRelationships1', attributes: [ new Document([ '$id' => ID::custom('string'), 'type' => Database::VAR_STRING, @@ -16566,7 +16566,7 @@ public function testUpdateDocumentsRelationships(): void Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('testUpdateDocumentsRelationships2', attributes: [ + static::getDatabase()->createCollection('testUpdateDocumentsRelationships2', attributes: [ new Document([ '$id' => ID::custom('string'), 'type' => Database::VAR_STRING, @@ -16580,46 +16580,46 @@ public function testUpdateDocumentsRelationships(): void Permission::delete(Role::any()) ]); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'testUpdateDocumentsRelationships1', relatedCollection: 'testUpdateDocumentsRelationships2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ + static::getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ '$id' => 'doc1', 'string' => 'text📝', ])); - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ + static::getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ '$id' => 'doc1', 'string' => 'text📝', 'testUpdateDocumentsRelationships1' => 'doc1' ])); - $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); + $sisterDocument = static::getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); $this->assertNotNull($sisterDocument); - $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships1', new Document([ + static::getDatabase()->updateDocuments('testUpdateDocumentsRelationships1', new Document([ 'string' => 'text📝 updated', ])); - $document = $this->getDatabase()->findOne('testUpdateDocumentsRelationships1'); + $document = static::getDatabase()->findOne('testUpdateDocumentsRelationships1'); $this->assertNotFalse($document); $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $sisterDocument = $this->getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); + $sisterDocument = static::getDatabase()->getDocument('testUpdateDocumentsRelationships2', 'doc1'); $this->assertNotNull($sisterDocument); $relationalDocument = $sisterDocument->getAttribute('testUpdateDocumentsRelationships1'); $this->assertEquals('text📝 updated', $relationalDocument->getAttribute('string')); // Check relationship value updating between each other. - $this->getDatabase()->deleteRelationship('testUpdateDocumentsRelationships1', 'testUpdateDocumentsRelationships2'); + static::getDatabase()->deleteRelationship('testUpdateDocumentsRelationships1', 'testUpdateDocumentsRelationships2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'testUpdateDocumentsRelationships1', relatedCollection: 'testUpdateDocumentsRelationships2', type: Database::RELATION_ONE_TO_MANY, @@ -16627,27 +16627,27 @@ public function testUpdateDocumentsRelationships(): void ); for ($i = 2; $i < 11; $i++) { - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ + static::getDatabase()->createDocument('testUpdateDocumentsRelationships1', new Document([ '$id' => 'doc' . $i, 'string' => 'text📝', ])); - $this->getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ + static::getDatabase()->createDocument('testUpdateDocumentsRelationships2', new Document([ '$id' => 'doc' . $i, 'string' => 'text📝', 'testUpdateDocumentsRelationships1' => 'doc' . $i ])); } - $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ + static::getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ 'testUpdateDocumentsRelationships1' => null ])); - $this->getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ + static::getDatabase()->updateDocuments('testUpdateDocumentsRelationships2', new Document([ 'testUpdateDocumentsRelationships1' => 'doc1' ])); - $documents = $this->getDatabase()->find('testUpdateDocumentsRelationships2'); + $documents = static::getDatabase()->find('testUpdateDocumentsRelationships2'); foreach ($documents as $document) { $this->assertEquals('doc1', $document->getAttribute('testUpdateDocumentsRelationships1')->getId()); @@ -16690,7 +16690,7 @@ public function testEvents(): void $this->assertEquals($shifted, $event); }); - if ($this->getDatabase()->getAdapter()->getSupportForSchemas()) { + if (static::getDatabase()->getAdapter()->getSupportForSchemas()) { $database->setDatabase('hellodb'); $database->create(); } else { From 0cbdb248443be23dfe588b89f6bf01df530cc677 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:07:18 +1300 Subject: [PATCH 099/103] Update cache --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a99e03468..d24cea9a1 100755 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ "ext-mbstring": "*", "php": ">=8.0", "utopia-php/framework": "0.33.*", - "utopia-php/cache": "0.10.*", + "utopia-php/cache": "0.11.*", "utopia-php/mongo": "0.3.*" }, "require-dev": { From 1c0edebab050443921f1e0629a4f5e64840a2062 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:13:04 +1300 Subject: [PATCH 100/103] Update framework --- tests/e2e/Adapter/Base.php | 85 +++++++++----------------------------- 1 file changed, 19 insertions(+), 66 deletions(-) diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 9aba9ac99..1ac815705 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1085,7 +1085,7 @@ public function testSizeCollection(): void $this->assertGreaterThan($size1, $size2); - self::$authorization->skip(function () use ($loopCount) { + Authorization::skip(function () use ($loopCount) { for ($i = 0; $i < $loopCount; $i++) { static::getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); } @@ -2445,58 +2445,12 @@ public function testUpdateDocument(Document $document): Document return $document; } - /** - * @depends testCreateDocuments - * @param array $documents - */ - public function testUpdateDocuments(array $documents): void - { - $collection = 'testCreateDocuments'; - - foreach ($documents as $document) { - $document - ->setAttribute('string', 'text📝 updated') - ->setAttribute('integer', 6) - ->setAttribute('$permissions', [ - Permission::read(Role::users()), - Permission::create(Role::users()), - Permission::update(Role::users()), - Permission::delete(Role::users()), - ]); - } - - $documents = static::getDatabase()->updateDocuments( - $collection, - $documents, - \count($documents) - ); - - foreach ($documents as $document) { - $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $this->assertEquals(6, $document->getAttribute('integer')); - } - - $documents = static::getDatabase()->find($collection, [ - Query::limit(\count($documents)) - ]); - - foreach ($documents as $document) { - $this->assertEquals('text📝 updated', $document->getAttribute('string')); - $this->assertEquals(6, $document->getAttribute('integer')); - $this->assertEquals([ - Permission::read(Role::users()), - Permission::create(Role::users()), - Permission::update(Role::users()), - Permission::delete(Role::users()), - ], $document->getAttribute('$permissions')); - } - } - /** * @depends testUpdateDocument */ public function testUpdateDocumentConflict(Document $document): void { + $document->setAttribute('integer_signed', 7); $result = static::getDatabase()->withRequestTimestamp(new \DateTime(), function () use ($document) { return static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); @@ -15701,7 +15655,7 @@ public function testDeleteBulkDocuments(): void $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); $this->assertEquals(0, $deleted); - $documents = static::$authorization->skip(function () { + $documents = Authorization::skip(function () { return static::getDatabase()->find('bulk_delete'); }); @@ -16258,8 +16212,8 @@ public function testUpdateDocuments(): void } $collection = 'testUpdateDocuments'; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); static::getDatabase()->createCollection($collection, attributes: [ new Document([ @@ -16363,7 +16317,7 @@ public function testUpdateDocuments(): void // Check document level permissions static::getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { static::getDatabase()->updateDocument($collection, 'doc0', new Document([ 'string' => 'text📝 updated all', '$permissions' => [ @@ -16375,7 +16329,7 @@ public function testUpdateDocuments(): void ])); }); - static::$authorization->addRole(Role::user('asd')->toString()); + Authorization::setRole(Role::user('asd')->toString()); static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'permission text', @@ -16387,7 +16341,7 @@ public function testUpdateDocuments(): void $this->assertCount(1, $documents); - self::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { $unmodifiedDocuments = static::getDatabase()->find($collection, [ Query::equal('string', ['text📝 updated all']), ]); @@ -16395,7 +16349,7 @@ public function testUpdateDocuments(): void $this->assertCount(9, $unmodifiedDocuments); }); - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { static::getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::any()), @@ -16419,8 +16373,8 @@ public function testUpdateDocuments(): void $this->assertEquals('batchSize Test', $document->getAttribute('string')); } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); } public function testUpdateDocumentsPermissions(): void @@ -16442,7 +16396,7 @@ public function testUpdateDocumentsPermissions(): void ], permissions: [], documentSecurity: true); // Test we can bulk update permissions we have access to - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { for ($i = 0; $i < 10; $i++) { static::getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, @@ -16477,7 +16431,7 @@ public function testUpdateDocumentsPermissions(): void ], ])); - $documents = static::$authorization->skip(function () use ($collection) { + $documents = Authorization::skip(function () use ($collection) { return static::getDatabase()->find($collection); }); @@ -16506,7 +16460,7 @@ public function testUpdateDocumentsPermissions(): void $this->assertCount(1, $unmodifiedDocuments); - static::$authorization->addRole(Role::user('user2')->toString()); + Authorization::setRole(Role::user('user2')->toString()); // Test Bulk permission update with data $affected = static::getDatabase()->updateDocuments($collection, new Document([ @@ -16521,10 +16475,9 @@ public function testUpdateDocumentsPermissions(): void $this->assertEquals(10, $affected); - $documents = static::$authorization - ->skip(function () use ($collection) { - return static::getDatabase()->find($collection); - }); + $documents = Authorization::skip(function () use ($collection) { + return static::getDatabase()->find($collection); + }); $this->assertCount(11, $documents); @@ -16549,8 +16502,8 @@ public function testUpdateDocumentsRelationships(): void return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); static::getDatabase()->createCollection('testUpdateDocumentsRelationships1', attributes: [ new Document([ From 15c0b000a8a9221cdd956d145cae1cd7acb48441 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:13:17 +1300 Subject: [PATCH 101/103] Update test auth refs --- composer.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.lock b/composer.lock index 2021f0b9e..455293f53 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "8a6537ec5c4f47cd0b6c34e9ceda042b", + "content-hash": "0ad14b2121f07c2fe936eaaa82186cbc", "packages": [ { "name": "brick/math", @@ -2002,16 +2002,16 @@ }, { "name": "utopia-php/cache", - "version": "0.10.2", + "version": "0.11.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247" + "reference": "8ebcab5aac7606331cef69b0081f6c9eff2e58bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/b22c6eb6d308de246b023efd0fc9758aee8b8247", - "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/8ebcab5aac7606331cef69b0081f6c9eff2e58bc", + "reference": "8ebcab5aac7606331cef69b0081f6c9eff2e58bc", "shasum": "" }, "require": { @@ -2022,7 +2022,7 @@ }, "require-dev": { "laravel/pint": "1.2.*", - "phpstan/phpstan": "1.9.x-dev", + "phpstan/phpstan": "^1.12", "phpunit/phpunit": "^9.3", "vimeo/psalm": "4.13.1" }, @@ -2046,9 +2046,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/0.10.2" + "source": "https://github.com/utopia-php/cache/tree/0.11.0" }, - "time": "2024-06-25T20:36:35+00:00" + "time": "2024-11-05T16:53:58+00:00" }, { "name": "utopia-php/compression", From 7c4237e7e3b1c12238dd28d41e3478d2f0739326 Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:53:47 +1300 Subject: [PATCH 102/103] Format --- composer.json | 12 +++++-- src/Database/Adapter/MariaDB.php | 18 +++++------ src/Database/Adapter/Mongo.php | 7 ++--- src/Database/Adapter/Postgres.php | 10 +++--- src/Database/Adapter/SQL.php | 6 ++-- src/Database/Adapter/SQLite.php | 8 ++--- src/Database/Exception.php | 2 +- src/Database/Query.php | 4 +-- src/Database/Validator/Datetime.php | 18 +++++------ src/Database/Validator/Index.php | 14 ++++----- src/Database/Validator/Queries.php | 4 +-- src/Database/Validator/Query/Filter.php | 18 +++++------ src/Database/Validator/Structure.php | 2 +- tests/e2e/Adapter/Base.php | 42 ++++++++++++------------- tests/unit/Validator/DateTimeTest.php | 2 +- 15 files changed, 86 insertions(+), 81 deletions(-) diff --git a/composer.json b/composer.json index d24cea9a1..2f99ab9f2 100755 --- a/composer.json +++ b/composer.json @@ -27,15 +27,15 @@ "Composer\\Config::disableProcessTimeout", "docker compose exec tests vendor/bin/phpunit --configuration phpunit.xml" ], - "lint": "./vendor/bin/pint --test", - "format": "./vendor/bin/pint", + "lint": "php -d memory_limit=2G ./vendor/bin/pint --test", + "format": "php -d memory_limit=2G ./vendor/bin/pint", "check": "./vendor/bin/phpstan analyse --level 7 src tests --memory-limit 2G", "coverage": "./vendor/bin/coverage-check ./tmp/clover.xml 90" }, "require": { + "php": ">=8.3", "ext-pdo": "*", "ext-mbstring": "*", - "php": ">=8.0", "utopia-php/framework": "0.33.*", "utopia-php/cache": "0.11.*", "utopia-php/mongo": "0.3.*" @@ -55,5 +55,11 @@ "ext-redis": "Needed to support Redis Cache Adapter", "ext-pdo": "Needed to support MariaDB, MySQL or SQLite Database Adapter", "mongodb/mongodb": "Needed to support MongoDB Database Adapter" + }, + "config": { + "allow-plugins": { + "php-http/discovery": true, + "tbachert/spi": true + } } } diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index 73bf4d6a4..2aa524c52 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -731,7 +731,7 @@ public function createIndex(string $collection, string $id, string $type, array $attributes[$i] = "`{$attr}`{$length} {$order}"; - if(!empty($collectionAttribute['array']) && $this->castIndexArray()) { + if (!empty($collectionAttribute['array']) && $this->castIndexArray()) { $attributes[$i] = '(CAST(' . $attr . ' AS char(' . Database::ARRAY_INDEX_LENGTH . ') ARRAY))'; } } @@ -915,7 +915,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions->execute(); } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -963,7 +963,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_createdAt'] = $document->getCreatedAt(); $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if(!empty($document->getInternalId())) { + if (!empty($document->getInternalId())) { $attributes['_id'] = $document->getInternalId(); } @@ -1043,7 +1043,7 @@ public function createDocuments(string $collection, array $documents, int $batch } } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1291,7 +1291,7 @@ public function updateDocument(string $collection, string $id, Document $documen } } catch (\Throwable $e) { - if($e instanceof PDOException) { + if ($e instanceof PDOException) { switch ($e->getCode()) { case 1062: case 23000: @@ -1848,7 +1848,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1976,7 +1976,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2193,7 +2193,7 @@ protected function getSQLCondition(Query $query): string return "`table_main`.{$attribute} {$this->getSQLOperator($query->getMethod())}"; case Query::TYPE_CONTAINS: - if($this->getSupportForJSONOverlaps() && $query->onArray()) { + if ($this->getSupportForJSONOverlaps() && $query->onArray()) { return "JSON_OVERLAPS(`table_main`.{$attribute}, :{$placeholder}_0)"; } @@ -2219,7 +2219,7 @@ protected function getSQLCondition(Query $query): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSON'; } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index 1bd7a095b..4b4215a36 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -3,7 +3,6 @@ namespace Utopia\Database\Adapter; use Exception; - use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -302,7 +301,7 @@ public function getSizeOfCollection(string $collection): int } else { throw new DatabaseException('No size found'); } - } catch(Exception $e) { + } catch (Exception $e) { throw new DatabaseException('Failed to get collection size: ' . $e->getMessage()); } } @@ -1434,7 +1433,7 @@ protected function buildFilters(array $queries, string $separator = '$and'): arr $queries = Query::groupByType($queries)['filters']; foreach ($queries as $query) { /* @var $query Query */ - if($query->isNested()) { + if ($query->isNested()) { $operator = $this->getQueryOperator($query->getMethod()); $filters[$separator][] = $this->buildFilters($query->getValues(), $operator); } else { @@ -1488,7 +1487,7 @@ protected function buildFilter(Query $query): array } elseif ($operator == '$ne' && \is_array($value)) { $filter[$attribute]['$nin'] = $value; } elseif ($operator == '$in') { - if($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { + if ($query->getMethod() === Query::TYPE_CONTAINS && !$query->onArray()) { $filter[$attribute]['$regex'] = new Regex(".*{$this->escapeWildcards($value)}.*", 'i'); } else { $filter[$attribute]['$in'] = $query->getValues(); diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index fbc1aaa44..af8a15c89 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -876,7 +876,7 @@ public function createDocument(string $collection, Document $document): Document $queryPermissions = $this->trigger(Database::EVENT_PERMISSIONS_CREATE, $queryPermissions); $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($sqlTenant) { + if ($sqlTenant) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -935,7 +935,7 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -1768,7 +1768,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -1896,7 +1896,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) $queries = array_map(fn ($query) => clone $query, $queries); $conditions = $this->getSQLConditions($queries); - if(!empty($conditions)) { + if (!empty($conditions)) { $where[] = $conditions; } @@ -2136,7 +2136,7 @@ protected function getFulltextValue(string $value): string */ protected function getSQLType(string $type, int $size, bool $signed = true, bool $array = false): string { - if($array === true) { + if ($array === true) { return 'JSONB'; } diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index 567b0f6c1..b06492f3f 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -828,14 +828,14 @@ protected function bindConditionValue(mixed $stmt, Query $query): void return; } - if($query->isNested()) { + if ($query->isNested()) { foreach ($query->getValues() as $value) { $this->bindConditionValue($stmt, $value); } return; } - if($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { + if ($this->getSupportForJSONOverlaps() && $query->onArray() && $query->getMethod() == Query::TYPE_CONTAINS) { $placeholder = $this->getSQLPlaceholder($query) . '_0'; $stmt->bindValue($placeholder, json_encode($query->getValues()), PDO::PARAM_STR); return; @@ -1085,7 +1085,7 @@ public function getSQLConditions(array $queries = [], string $separator = 'AND') continue; } - if($query->isNested()) { + if ($query->isNested()) { $conditions[] = $this->getSQLConditions($query->getValues(), $query->getMethod()); } else { $conditions[] = $this->getSQLCondition($query); diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 27d7379ef..55494fa55 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -460,7 +460,7 @@ public function createDocument(string $collection, Document $document): Document $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -534,7 +534,7 @@ public function createDocument(string $collection, Document $document): Document $stmtPermissions = $this->getPDO()->prepare($queryPermissions); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtPermissions->bindValue(':_tenant', $this->tenant); } } @@ -579,7 +579,7 @@ public function updateDocument(string $collection, string $id, Document $documen $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = json_encode($document->getPermissions()); - if($this->sharedTables) { + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -713,7 +713,7 @@ public function updateDocument(string $collection, string $id, Document $documen $stmtAddPermissions = $this->getPDO()->prepare($sql); $stmtAddPermissions->bindValue(":_uid", $document->getId()); - if($this->sharedTables) { + if ($this->sharedTables) { $stmtAddPermissions->bindValue(":_tenant", $this->tenant); } diff --git a/src/Database/Exception.php b/src/Database/Exception.php index 64ad3c997..94099c6ae 100644 --- a/src/Database/Exception.php +++ b/src/Database/Exception.php @@ -8,7 +8,7 @@ class Exception extends \Exception { public function __construct(string $message, int|string $code = 0, Throwable $previous = null) { - if(\is_string($code)) { + if (\is_string($code)) { if (\is_numeric($code)) { $code = (int) $code; } else { diff --git a/src/Database/Query.php b/src/Database/Query.php index 6af553415..aab17c195 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -297,7 +297,7 @@ public function toArray(): array { $array = ['method' => $this->method]; - if(!empty($this->attribute)) { + if (!empty($this->attribute)) { $array['attribute'] = $this->attribute; } @@ -690,7 +690,7 @@ public static function groupByType(array $queries): array */ public function isNested(): bool { - if(in_array($this->getMethod(), self::LOGICAL_TYPES)) { + if (in_array($this->getMethod(), self::LOGICAL_TYPES)) { return true; } diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index e8ffee5ff..812669d7a 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -33,7 +33,7 @@ class Datetime extends Validator */ public function __construct(bool $requireDateInFuture = false, string $precision = self::PRECISION_ANY, int $offset = 0) { - if($offset < 0) { + if ($offset < 0) { throw new \Exception('Offset must be a positive number.'); } @@ -50,13 +50,13 @@ public function getDescription(): string { $message = 'Value must be valid date'; - if($this->offset > 0) { + if ($this->offset > 0) { $message .= " at least " . $this->offset . " seconds in future"; - } elseif($this->requireDateInFuture) { + } elseif ($this->requireDateInFuture) { $message .= " in future"; } - if($this->precision !== self::PRECISION_ANY) { + if ($this->precision !== self::PRECISION_ANY) { $message .= " with " . $this->precision . " precision"; } @@ -84,9 +84,9 @@ public function isValid($value): bool return false; } - if($this->offset !== 0) { + if ($this->offset !== 0) { $diff = $date->getTimestamp() - $now->getTimestamp(); - if($diff <= $this->offset) { + if ($diff <= $this->offset) { return false; } } @@ -109,12 +109,12 @@ public function isValid($value): bool break; } - foreach($denyConstants as $constant) { - if(\intval($date->format($constant)) !== 0) { + foreach ($denyConstants as $constant) { + if (\intval($date->format($constant)) !== 0) { return false; } } - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index b24e39f73..fdaa1efe0 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -126,30 +126,30 @@ public function checkArrayIndex(Document $index): bool foreach ($attributes as $attributePosition => $attributeName) { $attribute = $this->attributes[\strtolower($attributeName)] ?? new Document(); - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { // Database::INDEX_UNIQUE Is not allowed! since mariaDB VS MySQL makes the unique Different on values - if($index->getAttribute('type') != Database::INDEX_KEY) { + if ($index->getAttribute('type') != Database::INDEX_KEY) { $this->message = '"' . ucfirst($index->getAttribute('type')) . '" index is forbidden on array attributes'; return false; } - if(empty($lengths[$attributePosition])) { + if (empty($lengths[$attributePosition])) { $this->message = 'Index length for array not specified'; return false; } $arrayAttributes[] = $attribute->getAttribute('key', ''); - if(count($arrayAttributes) > 1) { + if (count($arrayAttributes) > 1) { $this->message = 'An index may only contain one array attribute'; return false; } $direction = $orders[$attributePosition] ?? ''; - if(!empty($direction)) { + if (!empty($direction)) { $this->message = 'Invalid index order "' . $direction . '" on array attribute "'. $attribute->getAttribute('key', '') .'"'; return false; } - } elseif($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { + } elseif ($attribute->getAttribute('type') !== Database::VAR_STRING && !empty($lengths[$attributePosition])) { $this->message = 'Cannot set a length on "'. $attribute->getAttribute('type') . '" attributes'; return false; } @@ -188,7 +188,7 @@ public function checkIndexLength(Document $index): bool break; } - if($attribute->getAttribute('array', false)) { + if ($attribute->getAttribute('array', false)) { $attributeSize = Database::ARRAY_INDEX_LENGTH; $indexLength = Database::ARRAY_INDEX_LENGTH; } diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index 2e4aac71a..b1d67aad0 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -71,8 +71,8 @@ public function isValid($value): bool } } - if($query->isNested()) { - if(!self::isValid($query->getValues())) { + if ($query->isNested()) { + if (!self::isValid($query->getValues())) { return false; } } diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index 635fa4732..1fb50f9fc 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -131,29 +131,29 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s } } - if($attributeSchema['type'] === 'relationship') { + if ($attributeSchema['type'] === 'relationship') { /** * We can not disable relationship query since we have logic that use it, * so instead we validate against the relation type */ $options = $attributeSchema['options']; - if($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_ONE_TO_ONE && $options['twoWay'] === false && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { + if ($options['relationType'] === Database::RELATION_ONE_TO_MANY && $options['side'] === Database::RELATION_SIDE_PARENT) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { + if ($options['relationType'] === Database::RELATION_MANY_TO_ONE && $options['side'] === Database::RELATION_SIDE_CHILD) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } - if($options['relationType'] === Database::RELATION_MANY_TO_MANY) { + if ($options['relationType'] === Database::RELATION_MANY_TO_MANY) { $this->message = 'Cannot query on virtual relationship attribute'; return false; } @@ -161,7 +161,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s $array = $attributeSchema['array'] ?? false; - if( + if ( !$array && $method === Query::TYPE_CONTAINS && $attributeSchema['type'] !== Database::VAR_STRING @@ -170,7 +170,7 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s return false; } - if( + if ( $array && !in_array($method, [Query::TYPE_CONTAINS, Query::TYPE_IS_NULL, Query::TYPE_IS_NOT_NULL]) ) { @@ -253,12 +253,12 @@ public function isValid($value): bool case Query::TYPE_AND: $filters = Query::groupByType($value->getValues())['filters']; - if(count($value->getValues()) !== count($filters)) { + if (count($value->getValues()) !== count($filters)) { $this->message = \ucfirst($method) . ' queries can only contain filter queries'; return false; } - if(count($filters) < 2) { + if (count($filters) < 2) { $this->message = \ucfirst($method) . ' queries require at least two queries'; return false; } diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 46b1edafd..2e4cfde97 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -311,7 +311,7 @@ protected function checkForInvalidAttributeValues(array $structure, array $keys) continue; } - if($type === Database::VAR_RELATIONSHIP) { + if ($type === Database::VAR_RELATIONSHIP) { continue; } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 1ac815705..351665005 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -1002,7 +1002,7 @@ public function testQueryTimeout(): void Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); - } catch(TimeoutException $ex) { + } catch (TimeoutException $ex) { static::getDatabase()->clearTimeout(); static::getDatabase()->deleteCollection('global-timeouts'); } @@ -1909,7 +1909,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertStringContainsString('Invalid document structure: Attribute "float_unsigned" has invalid type. Value must be a valid range between 0 and', $e->getMessage()); } @@ -1928,7 +1928,7 @@ public function testCreateDocument(): Document 'empty' => [], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof StructureException); $this->assertEquals('Invalid document structure: Attribute "bigint_unsigned" has invalid type. Value must be a valid range between 0 and 9,223,372,036,854,775,807', $e->getMessage()); } @@ -2319,7 +2319,7 @@ public function testListDocumentSearch(): void public function testEmptyTenant(): void { - if(static::getDatabase()->getAdapter()->getSharedTables()) { + if (static::getDatabase()->getAdapter()->getSharedTables()) { $this->expectNotToPerformAssertions(); return; } @@ -2464,7 +2464,7 @@ public function testUpdateDocumentConflict(Document $document): void return static::getDatabase()->updateDocument($document->getCollection(), $document->getId(), $document); }); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertTrue($e instanceof ConflictException); $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); } @@ -2605,7 +2605,7 @@ public function testArrayAttribute(): void try { $database->createDocument($collection, new Document([])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Missing required attribute "booleans"', $e->getMessage()); } @@ -2625,7 +2625,7 @@ public function testArrayAttribute(): void 'short' => ['More than 5 size'], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "short[\'0\']" has invalid type. Value must be a valid string and no longer than 5 chars', $e->getMessage()); } @@ -2634,7 +2634,7 @@ public function testArrayAttribute(): void 'names' => ['Joe', 100], ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "names[\'1\']" has invalid type. Value must be a valid string and no longer than 255 chars', $e->getMessage()); } @@ -2643,7 +2643,7 @@ public function testArrayAttribute(): void 'age' => 1.5, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid integer', $e->getMessage()); } @@ -2652,7 +2652,7 @@ public function testArrayAttribute(): void 'age' => -100, ])); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid document structure: Attribute "age" has invalid type. Value must be a valid range between 0 and 2,147,483,647', $e->getMessage()); } @@ -2681,7 +2681,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { if (static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->assertEquals('"Fulltext" index is forbidden on array attributes', $e->getMessage()); } else { @@ -2692,7 +2692,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx', Database::INDEX_KEY, ['numbers', 'names'], [100,100]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('An index may only contain one array attribute', $e->getMessage()); } @@ -2713,7 +2713,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx_numbers', Database::INDEX_KEY, ['tv_show', 'numbers'], [], []); // [700, 255] $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Index length is longer than the maximum: 768', $e->getMessage()); } } @@ -2724,7 +2724,7 @@ public function testArrayAttribute(): void try { $database->createIndex($collection, 'indx4', Database::INDEX_KEY, ['age', 'names'], [10, 255], []); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Cannot set a length on "integer" attributes', $e->getMessage()); } @@ -2737,7 +2737,7 @@ public function testArrayAttribute(): void Query::equal('names', ['Joe']), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query equal on attribute "names" because it is an array.', $e->getMessage()); } @@ -2746,7 +2746,7 @@ public function testArrayAttribute(): void Query::contains('age', [10]) ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "age" because it is not an array or string.', $e->getMessage()); } @@ -3182,7 +3182,7 @@ public function testFindContains(): void Query::contains('price', [10.5]), ]); $this->fail('Failed to throw exception'); - } catch(Throwable $e) { + } catch (Throwable $e) { $this->assertEquals('Invalid query: Cannot query contains on attribute "price" because it is not an array or string.', $e->getMessage()); $this->assertTrue($e instanceof DatabaseException); } @@ -4089,7 +4089,7 @@ public function testOrSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: Or queries require at least two queries', $e->getMessage()); } } @@ -4149,7 +4149,7 @@ public function testAndSingleQuery(): void ]) ]); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertEquals('Invalid query: And queries require at least two queries', $e->getMessage()); } } @@ -4997,7 +4997,7 @@ public function testStructureValidationAfterRelationsAttribute(): void 'name' => 'Frozen', // Unknown attribute 'name' after relation attribute ])); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(StructureException::class, $e); } } @@ -5072,7 +5072,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void try { static::getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); diff --git a/tests/unit/Validator/DateTimeTest.php b/tests/unit/Validator/DateTimeTest.php index b9157e8b8..d8ababb6f 100644 --- a/tests/unit/Validator/DateTimeTest.php +++ b/tests/unit/Validator/DateTimeTest.php @@ -128,7 +128,7 @@ public function testOffset(): void $threwException = false; try { $dateValidator = new DatetimeValidator(offset: -60); - } catch(\Exception $e) { + } catch (\Exception $e) { $threwException = true; } $this->assertTrue($threwException); From 2626a7463bf5096ebe7a44f7d18e90ce84be261f Mon Sep 17 00:00:00 2001 From: Jake Barnby Date: Mon, 13 Jan 2025 16:54:41 +1300 Subject: [PATCH 103/103] Sync database --- src/Database/Database.php | 1043 ++++++++++++++++++++++--------------- 1 file changed, 634 insertions(+), 409 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 8957f0072..11a3df434 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -9,6 +9,7 @@ use Utopia\Database\Exception\Conflict as ConflictException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Limit as LimitException; +use Utopia\Database\Exception\NotFound as NotFoundException; use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Exception\Relationship as RelationshipException; use Utopia\Database\Exception\Restricted as RestrictedException; @@ -139,17 +140,6 @@ class Database public const INSERT_BATCH_SIZE = 100; public const DELETE_BATCH_SIZE = 100; - protected Adapter $adapter; - - protected Cache $cache; - - protected string $cacheName = 'default'; - - /** - * @var array - */ - protected array $map = []; - /** * List of Internal attributes * @@ -291,6 +281,17 @@ class Database 'indexes' => [], ]; + protected Adapter $adapter; + + protected Cache $cache; + + protected string $cacheName = 'default'; + + /** + * @var array + */ + protected array $map = []; + /** * @var array */ @@ -302,14 +303,14 @@ class Database protected array $instanceFilters = []; /** - * @var array + * @var array> */ protected array $listeners = [ '*' => [], ]; /** - * Array in which the keys are the names of databse listeners that + * Array in which the keys are the names of database listeners that * should be skipped when dispatching events. null $silentListeners * will skip all listeners. * @@ -321,6 +322,8 @@ class Database protected bool $resolveRelationships = true; + protected bool $checkRelationshipsExist = true; + protected int $relationshipFetchDepth = 1; protected bool $filter = true; @@ -329,6 +332,10 @@ class Database protected bool $preserveDates = false; + protected int $maxQueryValues = 100; + + protected bool $migrating = false; + /** * Stack of collection IDs when creating or updating related documents * @var array @@ -350,8 +357,11 @@ class Database * @param Cache $cache * @param array $filters */ - public function __construct(Adapter $adapter, Cache $cache, array $filters = []) - { + public function __construct( + Adapter $adapter, + Cache $cache, + array $filters = [] + ) { $this->adapter = $adapter; $this->cache = $cache; $this->instanceFilters = $filters; @@ -401,13 +411,12 @@ function (mixed $value) { self::addFilter( 'datetime', /** - * @param string|null $value - * @return string|null - * @throws Exception + * @param mixed $value + * @return mixed */ - function (?string $value) { + function (mixed $value) { if (is_null($value)) { - return null; + return; } try { $value = new \DateTime($value); @@ -433,9 +442,9 @@ function (?string $value) { * @param string $event * @param string $name * @param callable $callback - * @return self + * @return static */ - public function on(string $event, string $name, callable $callback): self + public function on(string $event, string $name, callable $callback): static { if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; @@ -453,7 +462,7 @@ public function on(string $event, string $name, callable $callback): self * @param callable $callback * @return $this */ - public function before(string $event, string $name, callable $callback): self + public function before(string $event, string $name, callable $callback): static { $this->adapter->before($event, $name, $callback); @@ -468,7 +477,7 @@ public function before(string $event, string $name, callable $callback): self * @param array|null $listeners List of listeners to silence; if null, all listeners will be silenced * @return T */ - public function silent(callable $callback, array $listeners = null): mixed + public function silent(callable $callback, ?array $listeners = null): mixed { $previous = $this->silentListeners; @@ -489,6 +498,17 @@ public function silent(callable $callback, array $listeners = null): mixed } } + /** + * Get getConnection Id + * + * @return string + * @throws Exception + */ + public function getConnectionId(): string + { + return $this->adapter->getConnectionId(); + } + /** * Skip relationships for all the calls inside the callback * @@ -508,6 +528,18 @@ public function skipRelationships(callable $callback): mixed } } + public function skipRelationshipsExistCheck(callable $callback): mixed + { + $previous = $this->checkRelationshipsExist; + $this->checkRelationshipsExist = false; + + try { + return $callback(); + } finally { + $this->checkRelationshipsExist = $previous; + } + } + /** * Trigger callback for events * @@ -566,7 +598,7 @@ public function withRequestTimestamp(?\DateTime $requestTimestamp, callable $cal * * @throws DatabaseException */ - public function setNamespace(string $namespace): self + public function setNamespace(string $namespace): static { $this->adapter->setNamespace($namespace); @@ -590,10 +622,10 @@ public function getNamespace(): string * * @param string $name * - * @return self + * @return static * @throws DatabaseException */ - public function setDatabase(string $name): self + public function setDatabase(string $name): static { $this->adapter->setDatabase($name); @@ -620,7 +652,7 @@ public function getDatabase(): string * * @return $this */ - public function setCache(Cache $cache): self + public function setCache(Cache $cache): static { $this->cache = $cache; return $this; @@ -642,7 +674,7 @@ public function getCache(): Cache * @param string $name * @return $this */ - public function setCacheName(string $name): self + public function setCacheName(string $name): static { $this->cacheName = $name; @@ -664,9 +696,9 @@ public function getCacheName(): string * * @param string $key * @param mixed $value - * @return self + * @return static */ - public function setMetadata(string $key, mixed $value): self + public function setMetadata(string $key, mixed $value): static { $this->adapter->setMetadata($key, $value); @@ -698,10 +730,10 @@ public function resetMetadata(): void * * @param int $milliseconds * @param string $event - * @return self + * @return static * @throws Exception */ - public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): self + public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): static { $this->adapter->setTimeout($milliseconds, $event); @@ -724,10 +756,9 @@ public function clearTimeout(string $event = Database::EVENT_ALL): void * * @return $this */ - public function enableFilters(): self + public function enableFilters(): static { $this->filter = true; - return $this; } @@ -736,13 +767,33 @@ public function enableFilters(): self * * @return $this */ - public function disableFilters(): self + public function disableFilters(): static { $this->filter = false; - return $this; } + /** + * Skip filters + * + * Execute a callback without filters + * + * @template T + * @param callable(): T $callback + * @return T + */ + public function skipFilters(callable $callback): mixed + { + $initial = $this->filter; + $this->disableFilters(); + + try { + return $callback(); + } finally { + $this->filter = $initial; + } + } + /** * Get instance filters * @@ -758,7 +809,7 @@ public function getInstanceFilters(): array * * @return $this */ - public function enableValidation(): self + public function enableValidation(): static { $this->validate = true; @@ -770,7 +821,7 @@ public function enableValidation(): self * * @return $this */ - public function disableValidation(): self + public function disableValidation(): static { $this->validate = false; @@ -780,7 +831,7 @@ public function disableValidation(): self /** * Skip Validation * - * Skips validation for the code to be executed inside the callback + * Execute a callback without validation * * @template T * @param callable(): T $callback @@ -799,14 +850,25 @@ public function skipValidation(callable $callback): mixed } /** - * Set Share Tables + * Get shared tables + * + * Get whether to share tables between tenants + * @return bool + */ + public function getSharedTables(): bool + { + return $this->adapter->getSharedTables(); + } + + /** + * Set shard tables * * Set whether to share tables between tenants * * @param bool $sharedTables - * @return self + * @return static */ - public function setSharedTables(bool $sharedTables): self + public function setSharedTables(bool $sharedTables): static { $this->adapter->setSharedTables($sharedTables); @@ -819,22 +881,96 @@ public function setSharedTables(bool $sharedTables): self * Set tenant to use if tables are shared * * @param ?int $tenant - * @return self + * @return static */ - public function setTenant(?int $tenant): self + public function setTenant(?int $tenant): static { $this->adapter->setTenant($tenant); return $this; } - public function setPreserveDates(bool $preserve): self + /** + * Get Tenant + * + * Get tenant to use if tables are shared + * + * @return ?int + */ + public function getTenant(): ?int + { + return $this->adapter->getTenant(); + } + + /** + * With Tenant + * + * Execute a callback with a specific tenant + * + * @param int|null $tenant + * @param callable $callback + * @return mixed + */ + public function withTenant(?int $tenant, callable $callback): mixed + { + $previous = $this->adapter->getTenant(); + $this->adapter->setTenant($tenant); + + try { + return $callback(); + } finally { + $this->adapter->setTenant($previous); + } + } + + public function getPreserveDates(): bool + { + return $this->preserveDates; + } + + public function setPreserveDates(bool $preserve): static { $this->preserveDates = $preserve; return $this; } + public function setMigrating(bool $migrating): self + { + $this->migrating = $migrating; + + return $this; + } + + public function isMigrating(): bool + { + return $this->migrating; + } + + public function withPreserveDates(callable $callback): mixed + { + $previous = $this->preserveDates; + $this->preserveDates = true; + + try { + return $callback(); + } finally { + $this->preserveDates = $previous; + } + } + + public function setMaxQueryValues(int $max): self + { + $this->maxQueryValues = $max; + + return $this; + } + + public function getMaxQueryValues(): int + { + return$this->maxQueryValues; + } + /** * Get list of keywords that cannot be used * @@ -921,17 +1057,16 @@ public function ping(): bool /** * Create the database * - * @throws DatabaseException - * + * @param string|null $database * @return bool + * @throws DuplicateException + * @throws LimitException + * @throws Exception */ public function create(?string $database = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } + $database ??= $this->adapter->getDatabase(); - $database = $database ?? $this->adapter->getDatabase(); $this->adapter->create($database); /** @@ -960,11 +1095,7 @@ public function create(?string $database = null): bool */ public function exists(?string $database = null, ?string $collection = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - - $database = $database ?? $this->adapter->getDatabase(); + $database ??= $this->adapter->getDatabase(); return $this->adapter->exists($database, $collection); } @@ -976,10 +1107,6 @@ public function exists(?string $database = null, ?string $collection = null): bo */ public function list(): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $databases = $this->adapter->list(); $this->trigger(self::EVENT_DATABASE_LIST, $databases); @@ -992,13 +1119,10 @@ public function list(): array * * @param string|null $database * @return bool + * @throws DatabaseException */ public function delete(?string $database = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $database = $database ?? $this->adapter->getDatabase(); $deleted = $this->adapter->delete($database); @@ -1008,6 +1132,8 @@ public function delete(?string $database = null): bool 'deleted' => $deleted ]); + $this->cache->flush(); + return $deleted; } @@ -1017,19 +1143,15 @@ public function delete(?string $database = null): bool * @param string $id * @param array $attributes * @param array $indexes - * @param array $permissions + * @param array|null $permissions * @param bool $documentSecurity * @return Document * @throws DatabaseException * @throws DuplicateException * @throws LimitException */ - public function createCollection(string $id, array $attributes = [], array $indexes = [], array $permissions = null, bool $documentSecurity = true): Document + public function createCollection(string $id, array $attributes = [], array $indexes = [], ?array $permissions = null, bool $documentSecurity = true): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $permissions ??= [ Permission::create(Role::any()), ]; @@ -1059,7 +1181,8 @@ public function createCollection(string $id, array $attributes = [], array $inde if ($this->validate) { $validator = new IndexValidator( $attributes, - $this->adapter->getMaxIndexLength() + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() ); foreach ($indexes as $index) { if (!$validator->isValid($index)) { @@ -1068,12 +1191,6 @@ public function createCollection(string $id, array $attributes = [], array $inde } } - $this->adapter->createCollection($id, $attributes, $indexes); - - if ($id === self::METADATA) { - return new Document(self::COLLECTION); - } - // Check index limits, if given if ($indexes && $this->adapter->getCountOfIndexes($collection) > $this->adapter->getLimitForIndexes()) { throw new LimitException('Index limit of ' . $this->adapter->getLimitForIndexes() . ' exceeded. Cannot create collection.'); @@ -1085,17 +1202,23 @@ public function createCollection(string $id, array $attributes = [], array $inde $this->adapter->getLimitForAttributes() > 0 && $this->adapter->getCountOfAttributes($collection) > $this->adapter->getLimitForAttributes() ) { - throw new LimitException('Column limit of ' . $this->adapter->getLimitForAttributes() . ' exceeded. Cannot create collection.'); + throw new LimitException('Attribute limit of ' . $this->adapter->getLimitForAttributes() . ' exceeded. Cannot create collection.'); } if ( $this->adapter->getDocumentSizeLimit() > 0 && $this->adapter->getAttributeWidth($collection) > $this->adapter->getDocumentSizeLimit() ) { - throw new LimitException('Row width limit of ' . $this->adapter->getDocumentSizeLimit() . ' exceeded. Cannot create collection.'); + throw new LimitException('Document size limit of ' . $this->adapter->getDocumentSizeLimit() . ' exceeded. Cannot create collection.'); } } + $this->adapter->createCollection($id, $attributes, $indexes); + + if ($id === self::METADATA) { + return new Document(self::COLLECTION); + } + $createdCollection = $this->silent(fn () => $this->createDocument(self::METADATA, $collection)); $this->trigger(self::EVENT_COLLECTION_CREATE, $createdCollection); @@ -1116,10 +1239,6 @@ public function createCollection(string $id, array $attributes = [], array $inde */ public function updateCollection(string $id, array $permissions, bool $documentSecurity): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($this->validate) { $validator = new Permissions(); if (!$validator->isValid($permissions)) { @@ -1130,14 +1249,14 @@ public function updateCollection(string $id, array $permissions, bool $documentS $collection = $this->silent(fn () => $this->getCollection($id)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ( $this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant() ) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $collection @@ -1161,16 +1280,15 @@ public function updateCollection(string $id, array $permissions, bool $documentS */ public function getCollection(string $id): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getDocument(self::METADATA, $id)); + $tenant = $collection->getAttribute('$tenant'); + if ( $id !== self::METADATA && $this->adapter->getSharedTables() - && $collection->getAttribute('$tenant') != $this->adapter->getTenant() + && $tenant !== null + && $tenant != $this->adapter->getTenant() ) { return new Document(); } @@ -1191,60 +1309,47 @@ public function getCollection(string $id): Document */ public function listCollections(int $limit = 25, int $offset = 0): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $result = $this->silent(fn () => $this->find(self::METADATA, [ Query::limit($limit), Query::offset($offset) ])); - if ($this->adapter->getSharedTables()) { - $result = \array_filter($result, function ($collection) { - return $collection->getAttribute('$tenant') == $this->adapter->getTenant(); - }); - } - $this->trigger(self::EVENT_COLLECTION_LIST, $result); return $result; } /** - * Get Collection Size on disk + * Get Collection Size * * @param string $collection * * @return int + * @throws Exception */ - public function getSizeOfCollectionOnDisk(string $collection): int + public function getSizeOfCollection(string $collection): int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); + return $this->adapter->getSizeOfCollection($collection->getId()); } /** - * Get Collection Size of Data + * Get Collection Size on disk * * @param string $collection * * @return int */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -1253,14 +1358,14 @@ public function getSizeOfCollection(string $collection): int $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - return $this->adapter->getSizeOfCollection($collection->getId()); + return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); } /** @@ -1273,24 +1378,20 @@ public function getSizeOfCollection(string $collection): int */ public function deleteCollection(string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getDocument(self::METADATA, $id)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $relationships = \array_filter( $collection->getAttribute('attributes'), fn ($attribute) => - $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP + $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP ); foreach ($relationships as $relationship) { @@ -1309,6 +1410,8 @@ public function deleteCollection(string $id): bool $this->trigger(self::EVENT_COLLECTION_DELETE, $collection); } + $this->purgeCachedCollection($id); + return $deleted; } @@ -1334,24 +1437,17 @@ public function deleteCollection(string $id): bool * @throws DuplicateException * @throws LimitException * @throws StructureException + * @throws Exception */ - public function createAttribute(string $collection, string $id, string $type, int $size, bool $required, mixed $default = null, bool $signed = true, bool $array = false, string $format = null, array $formatOptions = [], array $filters = []): bool + public function createAttribute(string $collection, string $id, string $type, int $size, bool $required, mixed $default = null, bool $signed = true, bool $array = false, ?string $format = null, array $formatOptions = [], array $filters = []): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); - } - - // Attribute IDs are case insensitive + // Attribute IDs are case-insensitive $attributes = $collection->getAttribute('attributes', []); /** @var array $attributes */ foreach ($attributes as $attribute) { @@ -1360,9 +1456,9 @@ public function createAttribute(string $collection, string $id, string $type, in } } - /** Ensure required filters for the attribute are passed */ + // Ensure required filters for the attribute are passed $requiredFilters = $this->getRequiredFilters($type); - if (!empty(array_diff($requiredFilters, $filters))) { + if (!empty(\array_diff($requiredFilters, $filters))) { throw new DatabaseException("Attribute of type: $type requires the following filters: " . implode(",", $requiredFilters)); } @@ -1424,10 +1520,10 @@ public function createAttribute(string $collection, string $id, string $type, in throw new DatabaseException('Unknown attribute type: ' . $type . '. Must be one of ' . self::VAR_STRING . ', ' . self::VAR_INTEGER . ', ' . self::VAR_FLOAT . ', ' . self::VAR_BOOLEAN . ', ' . self::VAR_DATETIME . ', ' . self::VAR_RELATIONSHIP); } - // only execute when $default is given + // Only execute when $default is given if (!\is_null($default)) { if ($required === true) { - throw new DatabaseException('Cannot set a default value on a required attribute'); + throw new DatabaseException('Cannot set a default value for a required attribute'); } $this->validateDefaultTypes($type, $default); @@ -1441,7 +1537,7 @@ public function createAttribute(string $collection, string $id, string $type, in } } catch (DuplicateException $e) { // HACK: Metadata should still be updated, can be removed when null tenant collections are supported. - if (!$this->adapter->getSharedTables()) { + if (!$this->adapter->getSharedTables() || !$this->isMigrating()) { throw $e; } } @@ -1479,7 +1575,7 @@ protected function getRequiredFilters(?string $type): array * @param string $type Type of the attribute * @param mixed $default Default value of the attribute * - * @throws Exception + * @throws DatabaseException * @return void */ protected function validateDefaultTypes(string $type, mixed $default): void @@ -1530,10 +1626,6 @@ protected function validateDefaultTypes(string $type, mixed $default): void */ protected function updateIndexMeta(string $collection, string $id, callable $updateCallback): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() === self::METADATA) { @@ -1544,7 +1636,7 @@ protected function updateIndexMeta(string $collection, string $id, callable $upd $index = \array_search($id, \array_map(fn ($index) => $index['$id'], $indexes)); if ($index === false) { - throw new DatabaseException('Index not found'); + throw new NotFoundException('Index not found'); } // Execute update from callback @@ -1573,10 +1665,6 @@ protected function updateIndexMeta(string $collection, string $id, callable $upd */ protected function updateAttributeMeta(string $collection, string $id, callable $updateCallback): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() === self::METADATA) { @@ -1587,14 +1675,14 @@ protected function updateAttributeMeta(string $collection, string $id, callable $index = \array_search($id, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); if ($index === false) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } // Execute update from callback $updateCallback($attributes[$index], $collection, $index); // Save - $collection->setAttribute('attributes', $attributes, Document::SET_TYPE_ASSIGN); + $collection->setAttribute('attributes', $attributes); $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); @@ -1700,7 +1788,7 @@ public function updateAttributeDefault(string $collection, string $id, mixed $de /** * Update Attribute. This method is for updating data that causes underlying structure to change. Check out other updateAttribute methods if you are looking for metadata adjustments. - * To update attribute key (ID), use renameAttribute instead. + * * @param string $collection * @param string $id * @param string|null $type @@ -1716,7 +1804,7 @@ public function updateAttributeDefault(string $collection, string $id, mixed $de * @return Document * @throws Exception */ - public function updateAttribute(string $collection, string $id, string $type = null, int $size = null, bool $required = null, mixed $default = null, bool $signed = null, bool $array = null, string $format = null, ?array $formatOptions = null, ?array $filters = null, ?string $newKey = null): Document + public function updateAttribute(string $collection, string $id, ?string $type = null, ?int $size = null, ?bool $required = null, mixed $default = null, ?bool $signed = null, ?bool $array = null, ?string $format = null, ?array $formatOptions = null, ?array $filters = null, ?string $newKey = null): Document { return $this->updateAttributeMeta($collection, $id, function ($attribute, $collectionDoc, $attributeIndex) use ($collection, $id, $type, $size, $required, $default, $signed, $array, $format, $formatOptions, $filters, $newKey) { $altering = !\is_null($type) @@ -1807,15 +1895,13 @@ public function updateAttribute(string $collection, string $id, string $type = n $this->adapter->getDocumentSizeLimit() > 0 && $this->adapter->getAttributeWidth($collectionDoc) >= $this->adapter->getDocumentSizeLimit() ) { - throw new LimitException('Row width limit reached. Cannot create new attribute.'); + throw new LimitException('Row width limit reached. Cannot update attribute.'); } if ($altering) { - $updated = $this->adapter->updateAttribute($collection, $id, $type, $size, $signed, $array, $newKey); - - if ($id !== $newKey) { - $indexes = $collectionDoc->getAttribute('indexes'); + $indexes = $collectionDoc->getAttribute('indexes'); + if (!\is_null($newKey) && $id !== $newKey) { foreach ($indexes as $index) { if (in_array($id, $index['attributes'])) { $index['attributes'] = array_map(function ($attribute) use ($id, $newKey) { @@ -1825,6 +1911,25 @@ public function updateAttribute(string $collection, string $id, string $type = n } } + /** + * Since we allow changing type & size we need to validate index length + */ + if ($this->validate) { + $validator = new IndexValidator( + $attributes, + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() + ); + + foreach ($indexes as $index) { + if (!$validator->isValid($index)) { + throw new DatabaseException($validator->getDescription()); + } + } + } + + $updated = $this->adapter->updateAttribute($collection, $id, $type, $size, $signed, $array, $newKey); + if (!$updated) { throw new DatabaseException('Failed to update attribute'); } @@ -1849,10 +1954,6 @@ public function updateAttribute(string $collection, string $id, string $type = n */ public function checkAttribute(Document $collection, Document $attribute): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = clone $collection; $collection->setAttribute('attributes', $attribute, Document::SET_TYPE_APPEND); @@ -1886,10 +1987,6 @@ public function checkAttribute(Document $collection, Document $attribute): bool */ public function deleteAttribute(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); @@ -1905,7 +2002,7 @@ public function deleteAttribute(string $collection, string $id): bool } if (\is_null($attribute)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } if ($attribute['type'] === self::VAR_RELATIONSHIP) { @@ -1960,43 +2057,47 @@ public function deleteAttribute(string $collection, string $id): bool */ public function renameAttribute(string $collection, string $old, string $new): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); + + /** + * @var array $attributes + */ $attributes = $collection->getAttribute('attributes', []); - $indexes = $collection->getAttribute('indexes', []); - $attribute = \in_array($old, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); + /** + * @var array $indexes + */ + $indexes = $collection->getAttribute('indexes', []); - if ($attribute === false) { - throw new DatabaseException('Attribute not found'); - } + $attribute = new Document(); - $attributeNew = \in_array($new, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); + foreach ($attributes as $value) { + if ($value->getId() === $old) { + $attribute = $value; + } - if ($attributeNew !== false) { - throw new DuplicateException('Attribute name already used'); + if ($value->getId() === $new) { + throw new DuplicateException('Attribute name already used'); + } } - foreach ($attributes as $key => $value) { - if (isset($value['$id']) && $value['$id'] === $old) { - $attributes[$key]['key'] = $new; - $attributes[$key]['$id'] = $new; - $attributeNew = $attributes[$key]; - break; - } + if ($attribute->isEmpty()) { + throw new NotFoundException('Attribute not found'); } + $attribute->setAttribute('$id', $new); + $attribute->setAttribute('key', $new); + foreach ($indexes as $index) { $indexAttributes = $index->getAttribute('attributes', []); - $indexAttributes = \array_map(fn ($attribute) => ($attribute === $old) ? $new : $attribute, $indexAttributes); + $indexAttributes = \array_map(fn ($attr) => ($attr === $old) ? $new : $attr, $indexAttributes); $index->setAttribute('attributes', $indexAttributes); } + $renamed = $this->adapter->renameAttribute($collection->getId(), $old, $new); + $collection->setAttribute('attributes', $attributes); $collection->setAttribute('indexes', $indexes); @@ -2004,9 +2105,7 @@ public function renameAttribute(string $collection, string $old, string $new): b $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); } - $renamed = $this->adapter->renameAttribute($collection->getId(), $old, $new); - - $this->trigger(self::EVENT_ATTRIBUTE_UPDATE, $attributeNew); + $this->trigger(self::EVENT_ATTRIBUTE_UPDATE, $attribute); return $renamed; } @@ -2038,20 +2137,16 @@ public function createRelationship( ?string $twoWayKey = null, string $onDelete = Database::RELATION_MUTATE_RESTRICT ): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $relatedCollection = $this->silent(fn () => $this->getCollection($relatedCollection)); if ($relatedCollection->isEmpty()) { - throw new DatabaseException('Related collection not found'); + throw new NotFoundException('Related collection not found'); } $id ??= $relatedCollection->getId(); @@ -2230,10 +2325,6 @@ public function updateRelationship( ?bool $twoWay = null, ?string $onDelete = null ): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ( \is_null($newKey) && \is_null($newTwoWayKey) @@ -2253,7 +2344,20 @@ public function updateRelationship( throw new DuplicateException('Attribute already exists'); } - $this->updateAttributeMeta($collection->getId(), $id, function ($attribute) use ($collection, $id, $newKey, $newTwoWayKey, $twoWay, $onDelete) { + $attributeIndex = array_search($id, array_map(fn ($attribute) => $attribute['$id'], $attributes)); + + if ($attributeIndex === false) { + throw new NotFoundException('Attribute not found'); + } + + $attribute = $attributes[$attributeIndex]; + $type = $attribute['options']['relationType']; + $side = $attribute['options']['side']; + + $relatedCollectionId = $attribute['options']['relatedCollection']; + $relatedCollection = $this->getCollection($relatedCollectionId); + + $this->updateAttributeMeta($collection->getId(), $id, function ($attribute) use ($collection, $id, $newKey, $newTwoWayKey, $twoWay, $onDelete, $type, $side) { $altering = (!\is_null($newKey) && $newKey !== $id) || (!\is_null($newTwoWayKey) && $newTwoWayKey !== $attribute['options']['twoWayKey']); @@ -2268,9 +2372,6 @@ public function updateRelationship( throw new DuplicateException('Related attribute already exists'); } - $type = $attribute['options']['relationType']; - $side = $attribute['options']['side']; - $newKey ??= $attribute['key']; $twoWayKey = $attribute['options']['twoWayKey']; $newTwoWayKey ??= $attribute['options']['twoWayKey']; @@ -2332,68 +2433,76 @@ public function updateRelationship( throw new DatabaseException('Failed to update relationship'); } } + }); - $this->purgeCachedCollection($collection->getId()); - $this->purgeCachedCollection($relatedCollection->getId()); + // Update Indexes + $renameIndex = function (string $collection, string $key, string $newKey) { + $this->updateIndexMeta( + $collection, + '_index_' . $key, + function ($index) use ($newKey) { + $index->setAttribute('attributes', [$newKey]); + } + ); + $this->silent( + fn () => + $this->renameIndex($collection, '_index_' . $key, '_index_' . $newKey) + ); + }; - $renameIndex = function (string $collection, string $key, string $newKey) { - $this->updateIndexMeta( - $collection, - '_index_' . $key, - fn ($index) => - $index->setAttribute('attributes', [$newKey]) - ); - $this->silent( - fn () => - $this->renameIndex($collection, '_index_' . $key, '_index_' . $newKey) - ); - }; + $newKey ??= $attribute['key']; + $twoWayKey = $attribute['options']['twoWayKey']; + $newTwoWayKey ??= $attribute['options']['twoWayKey']; + $twoWay ??= $attribute['options']['twoWay']; + $onDelete ??= $attribute['options']['onDelete']; - switch ($type) { - case self::RELATION_ONE_TO_ONE: - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - if ($twoWay && $twoWayKey !== $newTwoWayKey) { + switch ($type) { + case self::RELATION_ONE_TO_ONE: + if ($id !== $newKey) { + $renameIndex($collection->getId(), $id, $newKey); + } + if ($twoWay && $twoWayKey !== $newTwoWayKey) { + $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); + } + break; + case self::RELATION_ONE_TO_MANY: + if ($side === Database::RELATION_SIDE_PARENT) { + if ($twoWayKey !== $newTwoWayKey) { $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); } - break; - case self::RELATION_ONE_TO_MANY: - if ($side === Database::RELATION_SIDE_PARENT) { - if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); - } - } else { - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - } - break; - case self::RELATION_MANY_TO_ONE: - if ($side === Database::RELATION_SIDE_PARENT) { - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - } else { - if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); - } + } else { + if ($id !== $newKey) { + $renameIndex($collection->getId(), $id, $newKey); } - break; - case self::RELATION_MANY_TO_MANY: - $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); - + } + break; + case self::RELATION_MANY_TO_ONE: + if ($side === Database::RELATION_SIDE_PARENT) { if ($id !== $newKey) { - $renameIndex($junction, $id, $newKey); + $renameIndex($collection->getId(), $id, $newKey); } + } else { if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($junction, $twoWayKey, $newTwoWayKey); + $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); } - break; - default: - throw new RelationshipException('Invalid relationship type.'); - } - }); + } + break; + case self::RELATION_MANY_TO_MANY: + $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); + + if ($id !== $newKey) { + $renameIndex($junction, $id, $newKey); + } + if ($twoWayKey !== $newTwoWayKey) { + $renameIndex($junction, $twoWayKey, $newTwoWayKey); + } + break; + default: + throw new RelationshipException('Invalid relationship type.'); + } + + $this->purgeCachedCollection($collection->getId()); + $this->purgeCachedCollection($relatedCollection->getId()); return true; } @@ -2412,10 +2521,6 @@ public function updateRelationship( */ public function deleteRelationship(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $relationship = null; @@ -2429,7 +2534,7 @@ public function deleteRelationship(string $collection, string $id): bool } if (\is_null($relationship)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $collection->setAttribute('attributes', \array_values($attributes)); @@ -2540,10 +2645,6 @@ public function deleteRelationship(string $collection, string $id): bool */ public function renameIndex(string $collection, string $old, string $new): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $indexes = $collection->getAttribute('indexes', []); @@ -2551,7 +2652,7 @@ public function renameIndex(string $collection, string $old, string $new): bool $index = \in_array($old, \array_map(fn ($index) => $index['$id'], $indexes)); if ($index === false) { - throw new DatabaseException('Index not found'); + throw new NotFoundException('Index not found'); } $indexNew = \in_array($new, \array_map(fn ($index) => $index['$id'], $indexes)); @@ -2603,10 +2704,6 @@ public function renameIndex(string $collection, string $old, string $new): bool */ public function createIndex(string $collection, string $id, string $type, array $attributes, array $lengths = [], array $orders = []): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (empty($attributes)) { throw new DatabaseException('Missing attributes'); } @@ -2656,6 +2753,16 @@ public function createIndex(string $collection, string $id, string $type, array foreach ($attributes as $i => $attr) { foreach ($collectionAttributes as $collectionAttribute) { if ($collectionAttribute->getAttribute('key') === $attr) { + + /** + * mysql does not save length in collection when length = attributes size + */ + if ($collectionAttribute->getAttribute('type') === Database::VAR_STRING) { + if (!empty($lengths[$i]) && $lengths[$i] === $collectionAttribute->getAttribute('size') && $this->adapter->getMaxIndexLength() > 0) { + $lengths[$i] = null; + } + } + $isArray = $collectionAttribute->getAttribute('array', false); if ($isArray) { if ($this->adapter->getMaxIndexLength() > 0) { @@ -2682,7 +2789,8 @@ public function createIndex(string $collection, string $id, string $type, array if ($this->validate) { $validator = new IndexValidator( $collection->getAttribute('attributes', []), - $this->adapter->getMaxIndexLength() + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() ); if (!$validator->isValid($index)) { throw new DatabaseException($validator->getDescription()); @@ -2697,7 +2805,8 @@ public function createIndex(string $collection, string $id, string $type, array } } catch (DuplicateException $e) { // HACK: Metadata should still be updated, can be removed when null tenant collections are supported. - if (!$this->adapter->getSharedTables()) { + + if (!$this->adapter->getSharedTables() || !$this->isMigrating()) { throw $e; } } @@ -2725,10 +2834,6 @@ public function createIndex(string $collection, string $id, string $type, array */ public function deleteIndex(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $indexes = $collection->getAttribute('indexes', []); @@ -2741,14 +2846,14 @@ public function deleteIndex(string $collection, string $id): bool } } + $deleted = $this->adapter->deleteIndex($collection->getId(), $id); + $collection->setAttribute('indexes', \array_values($indexes)); if ($collection->getId() !== self::METADATA) { $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); } - $deleted = $this->adapter->deleteIndex($collection->getId(), $id); - $this->trigger(self::EVENT_INDEX_DELETE, $indexDeleted); return $deleted; @@ -2767,16 +2872,12 @@ public function deleteIndex(string $collection, string $id): bool */ public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($collection === self::METADATA && $id === self::METADATA) { return new Document(self::COLLECTION); } if (empty($collection)) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if (empty($id)) { @@ -2786,7 +2887,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $attributes = $collection->getAttribute('attributes', []); @@ -2901,7 +3002,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); $hasTwoWayRelationship = false; @@ -2914,7 +3015,6 @@ public function getDocument(string $collection, string $id, array $queries = [], /** * Bug with function purity in PHPStan means it thinks $this->map is always empty - * * @phpstan-ignore-next-line */ foreach ($this->map as $key => $value) { @@ -2930,10 +3030,10 @@ public function getDocument(string $collection, string $id, array $queries = [], } } - // Don't save to cache if it's part of a two-way relationship or a relationship at all + // Don't save to cache if it's part of a relationship if (!$hasTwoWayRelationship && empty($relationships)) { $this->cache->save($documentCacheKey, $document->getArrayCopy(), $documentCacheHash); - //add document reference to the collection key + // Add document reference to the collection key $this->cache->save($collectionCacheKey, 'empty', $documentCacheKey); } @@ -2944,7 +3044,7 @@ public function getDocument(string $collection, string $id, array $queries = [], if ($query->getMethod() === Query::TYPE_SELECT) { $values = $query->getValues(); foreach ($this->getInternalAttributes() as $internalAttribute) { - if (!in_array($internalAttribute['$id'], $values)) { + if (!\in_array($internalAttribute['$id'], $values)) { $document->removeAttribute($internalAttribute['$id']); } } @@ -3018,8 +3118,8 @@ private function populateDocumentRelationships(Document $collection, Document $d // collection as an existing relationship, but a different two-way key (the third condition), // or the same two-way key as an existing relationship, but a different key (the fourth condition). $transitive = (($existingKey === $twoWayKey - && $existingCollection === $relatedCollection->getId() - && $existingSide !== $side) + && $existingCollection === $relatedCollection->getId() + && $existingSide !== $side) || ($existingTwoWayKey === $key && $existingRelatedCollection === $collection->getId() && $existingSide !== $side) @@ -3203,7 +3303,11 @@ private function populateDocumentRelationships(Document $collection, Document $d */ public function createDocument(string $collection, Document $document): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { + if ( + $collection !== self::METADATA + && $this->adapter->getSharedTables() + && empty($this->adapter->getTenant()) + ) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } @@ -3240,7 +3344,11 @@ public function createDocument(string $collection, Document $document): Document } } - $structure = new Structure($collection); + $structure = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$structure->isValid($document)) { throw new StructureException($structure->getDescription()); } @@ -3260,6 +3368,7 @@ public function createDocument(string $collection, Document $document): Document $document = $this->decode($collection, $document); $this->trigger(self::EVENT_DOCUMENT_CREATE, $document); + return $document; } @@ -3278,10 +3387,6 @@ public function createDocument(string $collection, Document $document): Document */ public function createDocuments(string $collection, array $documents, int $batchSize = self::INSERT_BATCH_SIZE): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (empty($documents)) { return []; } @@ -3302,7 +3407,11 @@ public function createDocuments(string $collection, array $documents, int $batch $document = $this->encode($collection, $document); - $validator = new Structure($collection); + $validator = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($document)) { throw new StructureException($validator->getDescription()); } @@ -3326,7 +3435,10 @@ public function createDocuments(string $collection, array $documents, int $batch $documents[$key] = $this->decode($collection, $document); } - $this->trigger(self::EVENT_DOCUMENTS_CREATE, $documents); + $this->trigger(self::EVENT_DOCUMENTS_CREATE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); return $documents; } @@ -3344,7 +3456,7 @@ private function createDocumentRelationships(Document $collection, Document $doc $relationships = \array_filter( $attributes, fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); $stackCount = count($this->relationshipWriteStack); @@ -3613,7 +3725,7 @@ private function relateDocumentsById( // Get the related document, will be empty on permissions failure $related = $this->skipRelationships(fn () => $this->getDocument($relatedCollection->getId(), $relationId)); - if ($related->isEmpty()) { + if ($related->isEmpty() && $this->checkRelationshipsExist) { return; } @@ -3642,7 +3754,7 @@ private function relateDocumentsById( $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); $this->skipRelationships(fn () => $this->createDocument($junction, new Document([ - $key => $related->getId(), + $key => $relationId, $twoWayKey => $documentId, '$permissions' => [ Permission::read(Role::any()), @@ -3669,10 +3781,6 @@ private function relateDocumentsById( */ public function updateDocument(string $collection, string $id, Document $document): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (!$id) { throw new DatabaseException('Must define $id attribute'); } @@ -3829,7 +3937,11 @@ public function updateDocument(string $collection, string $id, Document $documen $document = $this->encode($collection, $document); - $structureValidator = new Structure($collection); + $structureValidator = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$structureValidator->isValid($document)) { // Make sure updated structure still apply collection rules (if any) throw new StructureException($structureValidator->getDescription()); } @@ -3866,24 +3978,48 @@ public function updateDocument(string $collection, string $id, Document $documen * @param array $queries * @param int $batchSize * - * @return int + * @return array * * @throws AuthorizationException * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int + public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($updates->isEmpty()) { - return 0; + return []; } - $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); + if ($collection->isEmpty()) { + throw new DatabaseException('Collection not found'); + } + + $attributes = $collection->getAttribute('attributes', []); + $indexes = $collection->getAttribute('indexes', []); + + if ($this->validate) { + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); + + if (!$validator->isValid($queries)) { + throw new QueryException($validator->getDescription()); + } + } + + $grouped = Query::groupByType($queries); + $limit = $grouped['limit']; + $cursor = $grouped['cursor']; + + if (!empty($cursor) && $cursor->getCollection() !== $collection->getId()) { + throw new DatabaseException("cursor Document must be from the same Collection."); + } + unset($updates['$id']); unset($updates['$createdAt']); unset($updates['$tenant']); @@ -3895,35 +4031,49 @@ public function updateDocuments(string $collection, Document $updates, array $qu $updates = $this->encode($collection, $updates); // Check new document structure - $validator = new PartialStructure($collection); + $validator = new PartialStructure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); + if (!$validator->isValid($updates)) { throw new StructureException($validator->getDescription()); } - $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $updates) { + $documents = $this->withTransaction(function () use ($collection, $queries, $batchSize, $updates, $limit, $cursor) { $lastDocument = null; - $totalModified = 0; - $affectedDocumentIds = []; + $documents = []; $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $collection->getUpdate())); + $authorization = new Authorization(self::PERMISSION_UPDATE); + $skipAuth = $authorization->isValid($collection->getUpdate()); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } + $originalLimit = $limit; + $lastDocument = $cursor; + // Resolve and update relationships while (true) { - $affectedDocuments = $this->find($collection->getId(), array_merge( + if ($limit && $limit < $batchSize) { + $batchSize = $limit; + } elseif (!empty($limit)) { + $limit -= $batchSize; + } + + $affectedDocuments = $this->silent(fn () => $this->find($collection->getId(), array_merge( + $queries, empty($lastDocument) ? [ Query::limit($batchSize), ] : [ Query::limit($batchSize), Query::cursorAfter($lastDocument), - ], - $queries, - ), forPermission: Database::PERMISSION_UPDATE); + ] + ), forPermission: Database::PERMISSION_UPDATE)); if (empty($affectedDocuments)) { break; @@ -3931,12 +4081,21 @@ public function updateDocuments(string $collection, Document $updates, array $qu foreach ($affectedDocuments as $document) { if ($this->resolveRelationships) { - $newDocument = array_merge($document->getArrayCopy(), $updates->getArrayCopy()); + $newDocument = new Document(array_merge($document->getArrayCopy(), $updates->getArrayCopy())); + $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, $newDocument)); + $documents[] = $newDocument; + } - $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, new Document($newDocument))); + // Check if document was updated after the request timestamp + try { + $oldUpdatedAt = new \DateTime($document->getUpdatedAt()); + } catch (Exception $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - $affectedDocumentIds[] = $document->getId(); + if (!is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + throw new ConflictException('Document was updated after the request timestamp'); + } } $getResults = fn () => $this->adapter->updateDocuments( @@ -3945,28 +4104,31 @@ public function updateDocuments(string $collection, Document $updates, array $qu $affectedDocuments ); - $result = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); - - $totalModified += $result; + $skipAuth ? $authorization->skip($getResults) : $getResults(); if (count($affectedDocuments) < $batchSize) { break; - } else { - $lastDocument = end($affectedDocuments); + } elseif ($originalLimit && count($documents) == $originalLimit) { + break; } - } - $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); + $lastDocument = end($affectedDocuments); + } - foreach ($affectedDocumentIds as $id) { - $this->purgeRelatedDocuments($collection, $id); - $this->purgeCachedDocument($collection->getId(), $id); + foreach ($documents as $document) { + $this->purgeRelatedDocuments($collection, $document->getId()); + $this->purgeCachedDocument($collection->getId(), $document->getId()); } - return $totalModified; + $this->trigger(self::EVENT_DOCUMENTS_UPDATE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); + + return $documents; }); - return $affected; + return $documents; } /** @@ -4122,7 +4284,7 @@ private function updateDocumentRelationships(Document $collection, Document $old $document->setAttribute($key, $related->getId()); break; } - // no break + // no break case 'NULL': if (!\is_null($oldValue?->getId())) { $oldRelated = $this->skipRelationships( @@ -4380,10 +4542,6 @@ private function getJunctionCollection(Document $collection, Document $relatedCo */ public function increaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $max = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($value <= 0) { // Can be a float throw new DatabaseException('Value must be numeric and greater than 0'); } @@ -4393,7 +4551,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4414,7 +4572,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string }); if (empty($attr)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $whiteList = [self::VAR_INTEGER, self::VAR_FLOAT]; @@ -4475,10 +4633,6 @@ public function increaseDocumentAttribute(string $collection, string $id, string */ public function decreaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $min = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($value <= 0) { // Can be a float throw new DatabaseException('Value must be numeric and greater than 0'); } @@ -4488,7 +4642,7 @@ public function decreaseDocumentAttribute(string $collection, string $id, string /* @var $document Document */ $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4509,7 +4663,7 @@ public function decreaseDocumentAttribute(string $collection, string $id, string }); if (empty($attr)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $whiteList = [self::VAR_INTEGER, self::VAR_FLOAT]; @@ -4566,24 +4720,18 @@ public function decreaseDocumentAttribute(string $collection, string $id, string * @throws ConflictException * @throws DatabaseException * @throws RestrictedException - * @throws StructureException */ public function deleteDocument(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $deleted = $this->withTransaction(function () use ($collection, $id, &$document) { - /* @var $document Document */ $document = Authorization::skip(fn () => $this->silent( fn () => $this->getDocument($collection->getId(), $id, forUpdate: true) )); - if($document->isEmpty()) { + if ($document->isEmpty()) { return false; } @@ -4606,7 +4754,7 @@ public function deleteDocument(string $collection, string $id): bool throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - if (!is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + if (!\is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { throw new ConflictException('Document was updated after the request timestamp'); } @@ -4690,8 +4838,8 @@ private function deleteDocumentRelationships(Document $collection, Document $doc // collection as an existing relationship, but a different two-way key (the third condition), // or the same two-way key as an existing relationship, but a different key (the fourth condition). $transitive = (($existingKey === $twoWayKey - && $existingCollection === $relatedCollection->getId() - && $existingSide !== $side) + && $existingCollection === $relatedCollection->getId() + && $existingSide !== $side) || ($existingTwoWayKey === $key && $existingRelatedCollection === $collection->getId() && $existingSide !== $side) @@ -5015,48 +5163,84 @@ private function deleteCascade(Document $collection, Document $relatedCollection * @param array $queries * @param int $batchSize * - * @return int + * @return array * * @throws AuthorizationException * @throws DatabaseException * @throws RestrictedException */ - public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): int + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): array { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); - $affectedDocumentIds = []; - $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { - $lastDocument = null; + if ($collection->isEmpty()) { + throw new DatabaseException('Collection not found'); + } + + $attributes = $collection->getAttribute('attributes', []); + $indexes = $collection->getAttribute('indexes', []); + + if ($this->validate) { + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime() + ); + + if (!$validator->isValid($queries)) { + throw new QueryException($validator->getDescription()); + } + } + + $grouped = Query::groupByType($queries); + $limit = $grouped['limit']; + $cursor = $grouped['cursor']; + + if (!empty($cursor) && $cursor->getCollection() !== $collection->getId()) { + throw new DatabaseException("cursor Document must be from the same Collection."); + } + $documents = $this->withTransaction(function () use ($collection, $queries, $batchSize, $limit, $cursor) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, $collection->getDelete())); + $authorization = new Authorization(self::PERMISSION_DELETE); + $skipAuth = $authorization->isValid($collection->getDelete()); + $documents = []; if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } + $originalLimit = $limit; + $lastDocument = $cursor; + while (true) { - $affectedDocuments = $this->find($collection->getId(), array_merge( + if ($limit && $limit < $batchSize) { + $batchSize = $limit; + } elseif (!empty($limit)) { + $limit -= $batchSize; + } + + $affectedDocuments = $this->silent(fn () => $this->find($collection->getId(), array_merge( + $queries, empty($lastDocument) ? [ Query::limit($batchSize), ] : [ Query::limit($batchSize), Query::cursorAfter($lastDocument), - ], - $queries, - ), forPermission: Database::PERMISSION_DELETE); + ] + ), forPermission: Database::PERMISSION_DELETE)); if (empty($affectedDocuments)) { break; } - $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); + $documents = array_merge($affectedDocuments, $documents); foreach ($affectedDocuments as $document) { // Delete Relationships @@ -5064,28 +5248,45 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $document = $this->silent(fn () => $this->deleteDocumentRelationships($collection, $document)); } + // Check if document was updated after the request timestamp + try { + $oldUpdatedAt = new \DateTime($document->getUpdatedAt()); + } catch (Exception $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); + } + + if (!\is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + throw new ConflictException('Document was updated after the request timestamp'); + } + $this->purgeRelatedDocuments($collection, $document->getId()); $this->purgeCachedDocument($collection->getId(), $document->getId()); } if (count($affectedDocuments) < $batchSize) { break; - } else { - $lastDocument = end($affectedDocuments); + } elseif ($originalLimit && count($documents) == $originalLimit) { + break; } + + $lastDocument = end($affectedDocuments); } - if (empty($affectedDocumentIds)) { - return 0; + if (empty($documents)) { + return []; } - $this->trigger(self::EVENT_DOCUMENTS_DELETE, $affectedDocumentIds); + $this->trigger(self::EVENT_DOCUMENTS_DELETE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); + + $this->adapter->deleteDocuments($collection->getId(), array_map(fn ($document) => $document->getId(), $documents)); - // Mass delete using adapter with query - return $this->adapter->deleteDocuments($collection->getId(), $affectedDocumentIds); + return $documents; }); - return $deleted; + return $documents; } /** @@ -5138,24 +5339,27 @@ public function purgeCachedDocument(string $collectionId, string $id): bool * @throws DatabaseException * @throws QueryException * @throws TimeoutException + * @throws Exception */ public function find(string $collection, array $queries = [], string $forPermission = Database::PERMISSION_READ): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } @@ -5163,7 +5367,7 @@ public function find(string $collection, array $queries = [], string $forPermiss $authorization = new Authorization(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $authorization->isValid($collection->getPermissionsByType($forPermission))); + $skipAuth = $authorization->isValid($collection->getPermissionsByType($forPermission)); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { throw new AuthorizationException($authorization->getDescription()); @@ -5256,7 +5460,7 @@ public function find(string $collection, array $queries = [], string $forPermiss $results = $skipAuth ? Authorization::skip($getResults) : $getResults(); - foreach ($results as &$node) { + foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { $node = $this->silent(fn () => $this->populateDocumentRelationships($collection, $node, $nestedSelections)); } @@ -5326,16 +5530,18 @@ public function findOne(string $collection, array $queries = []): Document */ public function count(string $collection, array $queries = [], ?int $max = null): int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } @@ -5372,16 +5578,18 @@ public function count(string $collection, array $queries = [], ?int $max = null) */ public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): float|int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } @@ -5440,12 +5648,12 @@ public function encode(Document $collection, Document $document): Document $filters = $attribute['filters'] ?? []; $value = $document->getAttribute($key); - // continue on optional param with no default + // Continue on optional param with no default if (is_null($value) && is_null($default)) { continue; } - // assign default only if no value provided + // Assign default only if no value provided // False positive "Call to function is_null() with mixed will always evaluate to false" // @phpstan-ignore-next-line if (is_null($value) && !is_null($default)) { @@ -5486,13 +5694,13 @@ public function decode(Document $collection, Document $document, array $selectio $attributes = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] !== self::VAR_RELATIONSHIP + $attribute['type'] !== self::VAR_RELATIONSHIP ); $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === self::VAR_RELATIONSHIP + $attribute['type'] === self::VAR_RELATIONSHIP ); foreach ($relationships as $relationship) { @@ -5625,11 +5833,11 @@ public function casting(Document $collection, Document $document): Document protected function encodeAttribute(string $name, mixed $value, Document $document): mixed { if (!array_key_exists($name, self::$filters) && !array_key_exists($name, $this->instanceFilters)) { - throw new DatabaseException("Filter: {$name} not found"); + throw new NotFoundException("Filter: {$name} not found"); } try { - if (array_key_exists($name, $this->instanceFilters)) { + if (\array_key_exists($name, $this->instanceFilters)) { $value = $this->instanceFilters[$name]['encode']($value, $document, $this); } else { $value = self::$filters[$name]['encode']($value, $document, $this); @@ -5661,7 +5869,7 @@ protected function decodeAttribute(string $name, mixed $value, Document $documen } if (!array_key_exists($name, self::$filters) && !array_key_exists($name, $this->instanceFilters)) { - throw new DatabaseException('Filter not found'); + throw new NotFoundException('Filter not found'); } if (array_key_exists($name, $this->instanceFilters)) { @@ -5760,11 +5968,16 @@ public function getLimitForIndexes(): int * @param array $queries * @return array * @throws QueryException + * @throws Exception */ public static function convertQueries(Document $collection, array $queries): array { $attributes = $collection->getAttribute('attributes', []); + foreach (Database::INTERNAL_ATTRIBUTES as $attribute) { + $attributes[] = new Document($attribute); + } + foreach ($attributes as $attribute) { foreach ($queries as $query) { if ($query->getAttribute() === $attribute->getId()) { @@ -5808,7 +6021,7 @@ private function purgeRelatedDocuments(Document $collection, string $id): void $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); if (empty($relationships)) { @@ -5852,4 +6065,16 @@ public function analyzeCollection(string $collection): bool { return $this->adapter->analyzeCollection($collection); } + + /** + * Get Schema Attributes + * + * @param string $collection + * @return array + * @throws DatabaseException + */ + public function getSchemaAttributes(string $collection): array + { + return $this->adapter->getSchemaAttributes($collection); + } }